#create vectors for tickers
Tickers <- c("BOIL",
             "FNGU",
             "LHX",
             "QYLD",
             "TIP",
             "UCO",
             "VXX"
)

Weighttt <- c(0.183063534373911,
              0.259080918568534,
              0.100913509961015,
              0.0987658790679151, 
              0.111754243846366,
              0.126084186527601,
              0.120337727654657 
)

sum(Weighttt)
## [1] 1
SP500 <- c("SPY")

#Create vector for risk free rate
rfr <- (.02827)
rfr252 <- rfr/252
#get price data
fieldRets <- "PX_last"
dateStart <- as.Date("2022-01-15")
dateEnd <- as.Date("2022-04-15")



PortPrices <- NULL
for(ticker in Tickers) {
  PortPrices <- cbind(PortPrices,
                      getSymbols(ticker, from = dateStart, to = dateEnd, periodicity = "daily", auto.assign=FALSE)[,4])
}
## 'getSymbols' currently uses auto.assign=TRUE by default, but will
## use auto.assign=FALSE in 0.5-0. You will still be able to use
## 'loadSymbols' to automatically load data. getOption("getSymbols.env")
## and getOption("getSymbols.auto.assign") will still be checked for
## alternate defaults.
## 
## This message is shown once per session and may be disabled by setting 
## options("getSymbols.warning4.0"=FALSE). See ?getSymbols for details.
SPYprices <- NULL
for(ticker in SP500) {
  SPYprices <- cbind(SPYprices,
                     getSymbols(ticker, from = dateStart, to = dateEnd, periodicity = "daily", auto.assign=FALSE)[,4])
}

#get daily returns
PortReturns <- na.omit(ROC(PortPrices))
SPYreturns <- na.omit(ROC(SPYprices))
PortWeightedReturns <- Return.portfolio(PortReturns, weights = Weighttt)
#daily log returns
highchart(type = "stock") %>%
  hc_add_series(PortReturns$BOIL.Close,
                name = "ProShares Ultra Bloomberg Natural Gas ETF") %>%
  hc_add_series(PortReturns$FNGU.Close,
                name = "Microsectors FANG+ Index 3x") %>%
  hc_add_series(PortReturns$LHX.Close,
                name = "L3 Harris Technologies") %>%
  hc_add_series(PortReturns$QYLD.Close,
                name = "Global X Nasdaq 100 Covered Call ETF") %>%
  hc_add_series(PortReturns$TIP.Close,
                name = "IShares TIPS Bond ETF") %>%
  hc_add_series(PortReturns$UCO.Close,
                name = "ProShares Ultra Bloomberg Crude Oil") %>%
  hc_add_series(PortReturns$VXX.Close,
                name = "IPath Series B S&P 500 VIX") %>%
  hc_add_theme(hc_theme_flat()) %>%
  hc_navigator(enabled = FALSE) %>%
  hc_scrollbar(enabled = FALSE) %>%
  hc_exporting(enabled = TRUE) %>%
  hc_title(text = "Daily Log Returns")
#performance of portfolio
charts.PerformanceSummary(PortReturns, main ="P/L Over Time")

#Benchmark Portfolio
EqualWeight <- rep(1 / ncol(PortReturns), ncol(PortReturns))

EqualReturns <- Return.portfolio(PortReturns, weights = EqualWeight)
#Rebalance Portfolio
Portt <- portfolio.spec(names(PortReturns))

Portt <- add.constraint(Portt,type = "weight_sum", min_sum =.99, max_sum  = 1.01)
Portt <- add.constraint(Portt, type = "long_only")
Portt <- add.constraint(Portt, type = "box", min = 0.07, max = .40)
Portt <- add.objective(Portt, type = "return", name = "mean")
Portt <- add.objective(Portt, type = "risk", name = "StdDev")
chart.Weights(opt_rebal)

RebalanceWeights <- extractWeights(opt_rebal)

rebal_returns <- Return.portfolio(PortReturns, weights = RebalanceWeights)
## Warning in Return.portfolio.geometric(R = R, weights = weights, wealth.index =
## wealth.index, : The weights for one or more periods do not sum up to 1: assuming
## a return of 0 for the residual weights
#rename columns
names(PortWeightedReturns) <- "Portfolio"
names(EqualReturns) <- "Equal Portfolio Returns"
names(SPYreturns) <- "SPY Benchmark"
names(rebal_returns) <- "Rebalanced Portfolio"
#Comparative Returns
BenchComp <- cbind(SPYreturns,PortWeightedReturns)
charts.PerformanceSummary(BenchComp, main ="P/L Over Time")

EqualComp <- cbind(EqualReturns,PortWeightedReturns)
charts.PerformanceSummary(EqualComp, main ="P/L Over Time")

REBALcomp <- cbind(rebal_returns,PortWeightedReturns)
charts.PerformanceSummary(REBALcomp, main ="P/L Over Time")

sum(PortWeightedReturns) * 100
## [1] 18.2898
sum(EqualReturns) * 100
## [1] 19.86101
sum(rebal_returns) * 100
## [1] 21.27019
sum(SPYreturns) * 100
## [1] -4.182741
#Regression of Portfolio
Comb_Ret <- cbind(PortWeightedReturns, SPYreturns)

Comb_Ret %>% 
  ggplot(aes(x =Comb_Ret$Portfolio, y = Comb_Ret$SPY.Benchmark)) +
  geom_point(alpha = 0.3) +
  geom_smooth(method = lm) + 
  theme_classic()+ 
  labs(x = 'Benchmark Returns',
       y= 'Portfolio Returns',
       title = "Portfolio Returns vs Benchmark returns") +
  scale_x_continuous(breaks = seq(-0.1,0.1,0.01),
                     labels = scales::percent) +
  scale_y_continuous(breaks = seq(-0.1,0.1,0.01),
                     labels = scales::percent)
## `geom_smooth()` using formula 'y ~ x'

model <- lm(Comb_Ret$Portfolio ~ Comb_Ret$SPY.Benchmark)
model_alpha <- model$coefficients[1]
model_beta <- model$coefficients[2]
cat("The portfolio alpha is", model_alpha, "and the portfolio beta is", model_beta)
## The portfolio alpha is 0.003353449 and the portfolio beta is 0.5178993
#Portfolio Beta
CAPM.beta(PortWeightedReturns, SPYreturns, rfr252)
## [1] 0.5178993
#beta in positive Market conditions only
CAPM.beta.bull(PortWeightedReturns, SPYreturns, rfr/252)
## [1] -0.1365649
#beta in negative market conditions only
CAPM.beta.bear(PortWeightedReturns, SPYreturns, rfr/252)
## [1] 0.8500343
#Alpha of Portfolio
CAPM.alpha(PortWeightedReturns, SPYreturns, rfr/252)
## [1] 0.003299365
#Jensen Alpha
CAPM.jensenAlpha(PortWeightedReturns, SPYreturns, rfr/252)
## [1] 1.06228
#Treynor Ratio
TreynorRatio(PortWeightedReturns,SPYreturns,Rf = rfr252)
## [1] 1.767615
#Active Premium over the market, this is annualized
ActivePremium(PortWeightedReturns, SPYreturns, scale = 252)
## [1] 1.148063
#SharpeRatio
SharpeRatio(PortWeightedReturns, Rf = rfr252)
##                               Portfolio
## StdDev Sharpe (Rf=0%, p=95%): 0.1165162
## VaR Sharpe (Rf=0%, p=95%):    0.0714168
## ES Sharpe (Rf=0%, p=95%):     0.0510762
#Information Ratio
InformationRatio(PortWeightedReturns, SPYreturns)
## [1] 2.935557
#risk premium
CAPM.RiskPremium(PortWeightedReturns,Rf = rfr)*100
##                        Portfolio
## Risk Premium (Rf=2.8%) -2.527167
#standard deviation
PortSD <- StdDev(PortWeightedReturns)
PortSD <- round(PortSD * 100, 2)
PortSD
##        [,1]
## StdDev 2.48
#annualized returns
Return.annualized(PortWeightedReturns)
##                   Portfolio
## Annualized Return 0.9702391
Return.annualized(EqualReturns)
##                   Equal Portfolio Returns
## Annualized Return                1.154973
Return.annualized(rebal_returns)
##                   Rebalanced Portfolio
## Annualized Return             1.251079
#skewness
PortSkew <- skewness(PortWeightedReturns)
PortSkew
## [1] -0.4995225
#Correlation Matrix
chart.Correlation(PortReturns)