You are on page 1of 6

library(tidyverse)

library(tidyquant)
library(flextable)
library(kableExtra)

nse <- c("^NSEI") %>% tq_get(get = "stock.prices",


from = "2008-04-01",
to = "2020-06-30") %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "weekly")

stocks <-
c("ICICIBANK.NS","AXISBANK.NS","SBIN.NS","FEDERALBNK.NS","BHEL.NS","NTPC.NS","HINDA
LCO.NS","TATAMOTORS.NS","TATASTEEL.NS") %>%
tq_get(get = "stock.prices",
from = "2008-04-01",
to = "2020-06-30") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "weekly")

ir<- left_join(stocks,nse,by="date") %>% drop_na()

# Measures how well the stock has performed in comparison to the benchmark.High
alpha is good.
alpha <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = CAPM.alpha
)

# Jenson's alpha
j.alpha <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = CAPM.jensenAlpha
)

# How volatile a stock price has been in comparison to benchmark.


beta <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = CAPM.beta
)

# Systematic risk
sys.risk <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = SystematicRisk
)

# Specific risk
sp.risk <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = SpecificRisk
)

# Total risk = systematic risk + specific risk


# https://www.wallstreetmojo.com/systematic-risk-vs-unsystematic-risk/
tot.risk <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = TotalRisk
)

# Treynor ratio: Similar to Sharpe ratio, but uses beta as a measure of risk.
treynor <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = TreynorRatio
)

# Appraisal ratio: Jensen's alpha divided by specific risk


appraisal <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = AppraisalRatio,
method = "appraisal"
)

# Tracking error
tracking <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = TrackingError
)

# Information ratio: ratio of degree to which investment has beaten the benchmark
to the consistency.
information <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
Rb = weekly.returns.y,
performance_fun = InformationRatio
)

# Downside frequency
sml <- ir %>% group_by(symbol) %>%
tq_performance(
Ra = weekly.returns.x,
performance_fun = DownsideFrequency,
MAR = 0.005
)

measures <- list(

alpha,j.alpha,beta,sys.risk,sp.risk,tot.risk,treynor,appraisal,tracking,information
) %>% purrr::reduce(inner_join,by = "symbol")

measures %>% kbl(digits = 3) %>%


kableExtra::kable_styling()

###################################################################################
###########

---
title: "portfolio"
author: "Gopikumar V"
date: "11/08/2021"
output: html_document
---

```{r}

library(tidyverse)
library(tidyquant)
library(PortfolioAnalytics)
library(ROI)
library(ROI.plugin.quadprog)
library(ROI.plugin.glpk)
library(timetk)

rm(list = ls())

```

```{r}

stocks <-
c("ICICIBANK.NS","AXISBANK.NS","SBIN.NS","FEDERALBNK.NS","BHEL.NS","NTPC.NS","HINDA
LCO.NS","TATAMOTORS.NS","TATASTEEL.NS","RELIANCE.NS") %>%
tq_get(get = "stock.prices",
from = "2008-04-01",
to = "2020-06-30") %>%
group_by(symbol) %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "weekly")

pf <- stocks %>% pivot_wider(


.,
names_from = symbol,
values_from = weekly.returns
)

pf <- timetk::tk_xts(pf,date_var = date)

# Create the portfolio specification


port_spec <- portfolio.spec(colnames(pf))

# Add a full investment constraint such that the weights sum to 1


port_spec <- add.constraint(portfolio = port_spec, type = "full_investment")

# Add a long only constraint such that the weight of an asset is between 0 and 1
port_spec <- add.constraint(portfolio = port_spec, type = "long_only")

# Add an objective to minimize portfolio standard deviation


port_spec <- add.objective(portfolio = port_spec, type = "risk", name = "StdDev")

# Solve the optimization problem


opt <- optimize.portfolio(pf, portfolio = port_spec, optimize_method = "ROI",trace
= TRUE)

# Extract the optimal weights


wts <- extractWeights(opt)

# Chart the optimal weights


chart.Weights(opt)

```

```{r}

# Create the portfolio specification


port_spec <- portfolio.spec(assets = colnames(pf))

# Add a full investment constraint such that the weights sum to 1


port_spec <- add.constraint(portfolio = port_spec, type = "full_investment")

# Add a long only constraint such that the weight of an asset is between 0 and 1.
# This is a box constraint.
port_spec <- add.constraint(portfolio = port_spec, type = "long_only")

# Add an objective to maximize portfolio mean return


port_spec <- add.objective(portfolio = port_spec, type = "return", name = "mean")

# Add an objective to minimize portfolio variance


port_spec <- add.objective(portfolio = port_spec, type = "risk", name = "var")

# Solve the optimization problem


opt <- optimize.portfolio(R = pf, portfolio = port_spec, optimize_method = "ROI")

# Extract the optimal weights


wts <- extractWeights(opt)

# Chart the optimal weights


chart.Weights(opt)

```

```{r}

# Create the portfolio specification


port_spec <- portfolio.spec(assets = colnames(pf))

# Add a full investment constraint such that the weights sum to 1


port_spec <- add.constraint(portfolio = port_spec, type = "full_investment")
# Add a long only constraint such that the weight of an asset is between 0 and 1.
# This is a box constraint.
#port_spec <- add.constraint(portfolio = port_spec, type = "box",min = 0.1, max =
0.4)

# Diversification constraint
# port_spec <- add.constraint(portfolio=port_spec, type="diversification",
div_target=0.7)

# Add an objective to maximize portfolio mean return


port_spec <- add.objective(portfolio = port_spec, type = "return", name = "mean")

# Add an objective to minimize portfolio variance


port_spec <- add.objective(portfolio = port_spec, type = "risk", name = "ETL")

# Solve the optimization problem


opt <- optimize.portfolio(R = pf, portfolio = port_spec, optimize_method =
"ROI",trace = TRUE)

# Extract the optimal weights


wts <- extractWeights(opt)

# Chart the optimal weights


#chart.Weights(opt)

```

```{r}

# Efficient frontier

ef <- extractEfficientFrontier(
opt,
match.col = "StdDev",
n.portfolios = 25,
risk_aversion = NULL
)

chart.EfficientFrontier(ef,
match.col="StdDev", # which column to use for risk
type="l",
RAR.text="Sharpe Ratio",
tangent.line = TRUE,
chart.assets=TRUE,
labels.assets=TRUE,
rf = 0.06/52)

```

```{r}

# Backtesting

equal_weights <- rep(1/ncol(pf),ncol(pf))


benchmark <- Return.portfolio(pf,weights = equal_weights)
colnames(benchmark) <- "bench.ret"

pfret <- Return.portfolio(pf,weights = wts)

# Nifty returns

nse <- c("^NSEI") %>% tq_get(get = "stock.prices",


from = "2008-04-01",
to = "2020-06-30") %>%
tq_transmute(select = adjusted,
mutate_fun = periodReturn,
period = "weekly")

nse <- timetk::tk_xts(nse,date_var = date)


colnames(nse) <- "Nifty"

# Compare performance

bktest <- cbind(pfret,benchmark,nse)

charts.PerformanceSummary(bktest)

```

You might also like