library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Registered S3 method overwritten by 'xts':
##   method     from
##   as.zoo.xts zoo
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## Version 0.4-0 included new data defaults. See ?getSymbols.
library(timetk)
library(readr)
library(pacman)
library(xts)
library(quadprog)
library(lpSolve)
library(fBasics)
## Loading required package: timeDate
## Loading required package: timeSeries
## 
## Attaching package: 'timeSeries'
## The following object is masked from 'package:zoo':
## 
##     time<-
## 
## Attaching package: 'fBasics'
## The following object is masked from 'package:TTR':
## 
##     volatility
library(xts)
library(kernlab)
library(reshape2)

#Question 1,2

data <- readRDS('hist_prices_df.rds')
data.1 <- data[,c("date","1708", "1713", "1714", "1718", "5519", "1723", "9902", "3052", "1731", "2032")]
sum(is.na(data.1))
## [1] 202
data.xts <- xts(data.1[,-1], order.by= as.Date(as.character(data.1[,1]), format = '%Y%m%d'))
con = gzcon(url('http://www.systematicportfolio.com/sit.gz','rb'))
source(con)
close(con)

#Question 3

data.monthly <- to.monthly(data.xts, indexAt = 'lastof', OHLC=F)
## Warning in to.period(x, "months", indexAt = indexAt, name = name, ...): missing
## values removed from data
data.monthly.1 <- data.monthly["2007/2017"]
data <- new.env()
data$prices <- data.monthly.1
data$weight <- data.monthly.1
data$execution.price <- data$prices
data$execution.price[] <- NA
data$symbolnames <- colnames(data$prices)
prices <- data$prices
n <-  ncol(prices)
data$weight <- ntop(prices, n)
model <- list()
model$equal.weight <- bt.run(data, trade.summary = T)
## Latest weights :
##            1708 1713 1714 1718 5519 1723 9902 3052 1731 2032
## 2017-12-31   10   10   10   10   10   10   10   10   10   10
## 
## Performance summary :
##  CAGR    Best    Worst   
##  10.6    26.6    -28.2   
bt.detail.summary(model$equal.weight)
## $System
## $System$Period
## [1] "Jan2007 - Dec2017"
## 
## $System$Cagr
## [1] 10.58
## 
## $System$Sharpe
## [1] 0.52
## 
## $System$DVR
##      [,1]
## 1708 0.32
## 
## $System$Volatility
## [1] 25.43
## 
## $System$MaxDD
## [1] -49.73
## 
## $System$AvgDD
## [1] -13.27
## 
## $System$VaR
##    5% 
## -9.15 
## 
## $System$CVaR
## [1] -14.34
## 
## $System$Exposure
## [1] 99.24
## 
## 
## $Trade
## $Trade$Win.Percent
## [1] 90
## 
## $Trade$Avg.Trade
## [1] 12.9
## 
## $Trade$Avg.Win
## [1] 14.9
## 
## $Trade$Avg.Loss
## [1] -4.9
## 
## $Trade$Best.Trade
## [1] 36.06
## 
## $Trade$Worst.Trade
## [1] -4.93
## 
## $Trade$WinLoss.Ratio
## [1] 3.03
## 
## $Trade$Avg.Len
## [1] 131
## 
## $Trade$Num.Trades
## [1] 10
## 
## 
## $Period
## $Period$Win.Percent.Day
## [1] 53
## 
## $Period$Best.Day
## [1] 26.6
## 
## $Period$Worst.Day
## [1] -28.2
## 
## $Period$Win.Percent.Month
## [1] 53
## 
## $Period$Best.Month
## [1] 26.6
## 
## $Period$Worst.Month
## [1] -28.2
## 
## $Period$Win.Percent.Year
## [1] 54.5
## 
## $Period$Best.Year
## [1] 109
## 
## $Period$Worst.Year
## [1] -24.8

#Question 4

data.monthly.2 <- data.monthly["2004/2017"]
data.monthly.3 <- data.monthly["2004/2006"]
Sigma_monthly <- cov(data.monthly.3)
head(Sigma_monthly)
##            1708      1713       1714       1718      5519       1723      9902
## 1708  2.9985143 0.6214619 -1.0546590 -3.2502848  2.224481  3.9768743 -2.402710
## 1713  0.6214619 0.8667075  0.3426158  0.1586206  0.183942  0.8376774  1.126442
## 1714 -1.0546590 0.3426158  1.4912294  2.6232761 -1.281822 -2.2930874  3.103961
## 1718 -3.2502848 0.1586206  2.6232761  5.9555571 -3.122330 -5.1379131  5.704093
## 5519  2.2244810 0.1839420 -1.2818225 -3.1223301  2.016203  3.2585998 -2.811774
## 1723  3.9768743 0.8376774 -2.2930874 -5.1379131  3.258600  7.2159450 -4.914742
##            3052       1731     2032
## 1708 -0.6312200 -0.4557943 1.982423
## 1713  0.3027507  0.2447943 1.842651
## 1714  0.9200193  0.4674571 1.644582
## 1718  1.5386279  0.9051571 1.463885
## 5519 -0.7660879 -0.4646000 0.250786
## 1723 -1.5141779 -0.8708057 2.070795
ones = rep(1,10)     
one.vec = matrix(ones, ncol=1)
a = inv(Sigma_monthly) %*% one.vec
b = t(one.vec)%*%a
mvp.w.monthly =a / as.numeric(b)
mvp.w.monthly
##             [,1]
## 1708 -0.06403169
## 1713 -0.26837154
## 1714  0.58007478
## 1718  0.06287213
## 5519  0.20637394
## 1723  0.28494740
## 9902 -0.03243128
## 3052  0.21393282
## 1731  0.14440728
## 2032 -0.12777384

#Question 5

data$prices = data$weight = data$execution.price = data.monthly.1
data$execution.price[] <- NA
prices <- data$prices
n <- ncol(prices)
constraints = new.constraints(n, lb = -Inf, ub = +Inf)
constraints = add.constraints(rep(1, n), 1, type = '=', constraints)
ret = prices / mlag(prices) - 1
weight = coredata(prices)
weight[] = NA
nrow(prices)
## [1] 132
hist <- na.omit(ret[1:36,])
cov(hist)
##             1708        1713        1714        1718        5519        1723
## 1708 0.051846557 0.006688473 0.009392361 0.001983360 0.010841043 0.006997206
## 1713 0.006688473 0.015882476 0.014742581 0.010471039 0.007878406 0.004408409
## 1714 0.009392361 0.014742581 0.019829908 0.011684862 0.011756705 0.004756198
## 1718 0.001983360 0.010471039 0.011684862 0.019828342 0.010828291 0.005521033
## 5519 0.010841043 0.007878406 0.011756705 0.010828291 0.029603520 0.005765633
## 1723 0.006997206 0.004408409 0.004756198 0.005521033 0.005765633 0.008216194
## 9902 0.008949932 0.016344588 0.013662488 0.013567533 0.012838044 0.007914785
## 3052 0.010654929 0.013723443 0.014458830 0.011019938 0.009215870 0.005337135
## 1731 0.014675060 0.014498605 0.012990188 0.018611052 0.008140295 0.010149682
## 2032 0.008830856 0.016877816 0.017033794 0.013273381 0.014840743 0.006096138
##             9902        3052        1731        2032
## 1708 0.008949932 0.010654929 0.014675060 0.008830856
## 1713 0.016344588 0.013723443 0.014498605 0.016877816
## 1714 0.013662488 0.014458830 0.012990188 0.017033794
## 1718 0.013567533 0.011019938 0.018611052 0.013273381
## 5519 0.012838044 0.009215870 0.008140295 0.014840743
## 1723 0.007914785 0.005337135 0.010149682 0.006096138
## 9902 0.042596166 0.018020297 0.027109915 0.023678635
## 3052 0.018020297 0.027081196 0.012625387 0.018469599
## 1731 0.027109915 0.012625387 0.050988824 0.016482832
## 2032 0.023678635 0.018469599 0.016482832 0.033562240
ia = create.historical.ia(hist,12)
s0 = apply(coredata(hist), 2 , sd)
ia$cov = cor(coredata(hist), use='complete.obs',method='pearson') * (s0 %*% t(s0))
weight[36,] = min.risk.portfolio(ia, constraints)
weight[36,]
##        1708        1713        1714        1718        5519        1723 
##  0.03509311  0.42841746 -0.09390037  0.14316361  0.03558416  0.72476735 
##        9902        3052        1731        2032 
## -0.04849357 -0.00409913 -0.12897499 -0.09155763
model$min.var.monthly <- bt.run(data, trade.summary = T)
## Latest weights :
##            1708 1713 1714 1718 5519  1723 9902 3052 1731 2032
## 2017-12-31 2880 1690 1045 1045 1020 12650 1010  830 1400 1000
## 
## Performance summary :
##  CAGR    Best    Worst   
##  -100    3191    -3640   
sum(as.numeric(weight[36,])*as.numeric(ret[37,]))
## [1] -0.04730427
model$min.var.monthly$ret[37, ]
##            1708
## 2010-01-31   -1
plotbt.strategy.sidebyside(model, return.table=T, make.plot = T)
## Warning in max(mret, na.rm = T): no non-missing arguments to max; returning -Inf
## Warning in min(mret, na.rm = T): no non-missing arguments to min; returning Inf

##            equal.weight        min.var.monthly    
## Period     "Jan2007 - Dec2017" "Jan2007 - Dec2017"
## Cagr       "10.58"             "-100"             
## Sharpe     "0.52"              "-0.54"            
## DVR        "0.32"              "-0.01"            
## Volatility "25.43"             "1053.53"          
## MaxDD      "-49.73"            "-100"             
## AvgDD      "-13.27"            "-100"             
## VaR        "-9.15"             "-100"             
## CVaR       "-14.34"            "NaN"              
## Exposure   "99.24"             "99.24"