# 股票投资组合-前进优化方法（Walk forward optimization）

## 前进优化方法（Walk forward optimization）

### R语言案例演示Walk forward optimization

``require(quantmod)require(PerformanceAnalytics)setSymbolLookup(GZMT=list(name ="600519.SS", src='yahoo')) # 贵州茅台setSymbolLookup(MSYH=list(name ="600016.SS", src='yahoo')) # 民生银行``getSymbols(c("GZMT", "MSYH"), from="2009-01-01")``

``## [1] "GZMT" "MSYH"``

``returns <- merge(Return.calculate(Ad(GZMT)), Return.calculate(Ad(MSYH)), join='inner')``returns <- returns[-1,]``

1. 不同组合权重下的累计收益率

``configs <- list()for(i in 1:21) {weightSPY <- (i-1)*.05weightTLT <- 1-weightSPYconfig <- Return.portfolio(R = returns, weights=c(weightSPY, weightTLT), rebalance_on = "months")configs[[i]] <- config}configs <- do.call(cbind, configs)``cumRets <- cumprod(1+configs)``

1. 测算不同权重配比，最大限度地提高每月月底的夏普比率

``period <- 72roll72CumAnn <- (cumRets/lag(cumRets, period))^(252/period) - 1roll72SD <- sapply(X = configs, runSD, n=period)*sqrt(252)sd_f_factor <- 2.5modSharpe <- roll72CumAnn/roll72SD^sd_f_factormonthlyModSharpe <- modSharpe[endpoints(modSharpe, on="months"),]findMax <- function(data) {return(data==max(data))}weights <- t(apply(monthlyModSharpe, 1, findMax))weights <- weights*1weights <- xts(weights, order.by=as.Date(rownames(weights)))weights[is.na(weights)] <- 0weights\$zeroes <- 1-rowSums(weights)``configs\$zeroes <- 0``

1. 组合表现及结果

``stratRets <- Return.portfolio(R = configs, weights = weights)``rbind(table.AnnualizedReturns(stratRets), maxDrawdown(stratRets))``

``## portfolio.returns## Annualized Return 0.2061000## Annualized Std Dev 0.3152000## Annualized Sharpe (Rf=0%) 0.6540000``## 4 0.4358557``

``charts.PerformanceSummary(stratRets)``

1. 加入比较项-非组合下的单只表现

``stratAndComponents <- merge(returns, stratRets, join='inner')``charts.PerformanceSummary(stratAndComponents)``

``rbind(table.AnnualizedReturns(stratAndComponents), maxDrawdown(stratAndComponents))``

``## X600519.SS.Adjusted X600016.SS.Adjusted## Annualized Return 0.182100 0.1611000## Annualized Std Dev 0.319500 0.3451000## Annualized Sharpe (Rf=0%) 0.570000 0.4667000## Worst Drawdown 0.529815 0.4379973## portfolio.returns## Annualized Return 0.2061000## Annualized Std Dev 0.3152000## Annualized Sharpe (Rf=0%) 0.6540000``## Worst Drawdown 0.4358557``

1. 年华收益率比较

``apply.yearly(stratAndComponents, Return.cumulative)``

``## X600519.SS.Adjusted X600016.SS.Adjusted portfolio.returns## 2009-12-31 0.6628246 0.76865724 0.33702777## 2010-12-31 0.0952092 -0.36536060 -0.34610867## 2011-12-30 0.1826568 0.19551653 0.15907019## 2012-12-31 0.1019296 0.45991037 0.57773693## 2013-12-31 -0.3611985 0.02297592 0.00699064## 2014-12-31 0.6790561 0.71832221 1.18715154``## 2015-11-26 0.2587723 -0.17880127 0.04664253``

### 反馈与建议

• 参考：The Logical-Invest “Universal Investment Strategy”–A Walk Forward Process on SPY and TLT
• 作者：ShangFR
• 邮箱：shangfr@foxmail.com