# required packages --------------------------------------------------
require(fImport)
require(ClustVarLV)
# --------------------------------------------------------------------

# some risky assets via ETFs
tix <- c('IWM', 'IWB', 'EFA', 'VWO', 'TLT', 
         'EDV', 'EMB', 'AGG', 'JNK', 'LTPZ', 
         'GSG', 'AMZ', 'GLD', 'VNQ', 'MNA', 
         'MCRO', 'QAI', 'CSLS', 'HDG', 'WDTI')

assetNames <- c('US.Large.Cap', 'US.Small.Cap', 'EAFE', 
                'EM.Mkts.Equity', 'US.Gov.Bonds', 'Intl.Gov.Bonds', 
                'EM.Mkts.Bonds', 'US.Agg.Bonds', 'US.HY.Bonds', 'US.TIPS', 
                'Commodities', 'MLP', 'Gold', 'REITs',
                'Merger.Arb', 'Global.Macro', 'Multi-Strat', 
                'Equity.Long.Short', 'Hedge.Replicator', 'CTA')

# get data from yahoo finance, open-high-low-close format
ohlc <- yahooSeries(tix, from = '1900-01-01', freq = 'monthly')
# get prices from every 6th column
prices <- ohlc[, seq(6, 6*length(tix), 6)]
colnames(prices) <- assetNames
# cut to common time period and caluclate returns
ret <- returns(prices, method = 'discrete')


clv.res <- CLV(ret, method = "local", sX = FALSE, nmax = 8)

opar <- par()
par(mar = c(7.5,4.1,4.1,2.1))
plot(clv.res, type = 'dendrogram')

par(mar = opar$mar)
plot(clv.res, type = 'delta')

summary(clv.res, 4)
## $number
## clusters
##  1  2  3  4 
## 12  4  3  1 
## 
## $groups
## $groups[[1]]
##                   cor in group  cor next group
## Hedge.Replicator          0.94            0.33
## US.Small.Cap              0.93            0.35
## EAFE                      0.93            0.37
## EM.Mkts.Equity            0.90            0.46
## US.HY.Bonds               0.88            0.54
## Global.Macro              0.88            0.47
## US.Large.Cap              0.87            0.30
## Multi-Strat               0.87            0.40
## REITs                     0.77            0.13
## EM.Mkts.Bonds             0.75            0.41
## Equity.Long.Short         0.68            0.32
## Merger.Arb                0.57            0.36
## 
## $groups[[2]]
##                cor in group  cor next group
## US.Gov.Bonds           0.98           -0.03
## Intl.Gov.Bonds         0.97           -0.04
## US.Agg.Bonds           0.83            0.21
## US.TIPS                0.80            0.26
## 
## $groups[[3]]
##             cor in group  cor next group
## Commodities         0.84            0.46
## Gold                0.81            0.27
## CTA                 0.24           -0.06
## 
## $groups[[4]]
##     cor in group  cor next group
## MLP            1            0.25
## 
## 
## $set_aside
## NULL
## 
## $cormatrix
##       Comp1 Comp2 Comp3 Comp4
## Comp1  1.00 -0.21  0.39  0.25
## Comp2 -0.21  1.00 -0.19 -0.04
## Comp3  0.39 -0.19  1.00 -0.18
## Comp4  0.25 -0.04 -0.18  1.00
plot_var(clv.res, K = 4)