投资中性模型。可以让我们的投资组合的风险敞口极小。
# 滚动计算相关性
data <- cbind(ret_xom,ret_cvx)
correlation <- function(x){
result <- cor(x[,1],x[,2],use = "na.or.complete")
return(result)
}
corr <- rollapply(data,252,correlation,by.column=FALSE)
plot(corr)
# 滚动计算上下边界
hedge_ratio <- xom / cvx
roll_me <- rollapply(hedge_ratio,14,mean,na.rm=TRUE)
roll_std <- rollapply(hedge_ratio,14,sd,na.rm=TRUE)
# n是关键值
n <-1
roll_ub <- roll_me + n * roll_std
roll_lb <- roll_me - n * roll_std
# 交易信号
signal <- NULL
signal <- ifelse(hedge_ratio > roll_ub,-1,
ifelse(hedge_ratio<roll_lb,1,0)) lagsignal <- lag(signal,1) signal ifelse(lagsignal="=" -1 & hedge_ratio>roll_me,-1,
ifelse(lagsignal == 1 & hedge_ratio <roll_me,1,0)) # 计算收益 spread_return <- ret_xom - lag(hedge_ratio) * ret_cvx cost 0 trade_return lag(signal) names(trade_return)<- "tradstrat_pt#2" 交易效果和绩效指标 summary(as.vector(trade_return)) cumm_ret return.cumulative(trade_return) annual_ret return.annualized(trade_return) par(mfrow="c(1,1))" charts.performancesummary(trade_return,main="交易报告" ) tail(cumm_ret) maxdrawdown(trade_return) stddev(trade_return) stddev.annualized(trade_return) var(trade_return) sharperatio(trade_return,rf="0,FUN="StdDev")" sharperatio.annualized(trade_return,rf="0)" ``` ![file](http: imgow.oss-cn-beijing.aliyuncs.com image-1581145816970.png) ```r> # 交易效果和绩效指标
> summary(as.vector(trade_return))
Min. 1st Qu. Median Mean
-0.036732 -0.000437 0.000000 -0.000148
3rd Qu. Max. NA's
0.000290 0.031850 15
> cumm_ret <- Return.cumulative(trade_return)
> annual_ret <- Return.annualized(trade_return)
> par(mfrow=c(1,1))
> charts.PerformanceSummary(trade_return,main="交易报告")
> tail(cumm_ret)
TradStrat_PT#2
Cumulative Return -0.2141587
> maxDrawdown(trade_return)
[1] 0.274468
> StdDev(trade_return)
[,1]
StdDev 0.005041639
> StdDev.annualized(trade_return)
TradStrat_PT#2
Annualized Standard Deviation 0.08003354
> VaR(trade_return)
TradStrat_PT#2
VaR -0.007856979
> SharpeRatio(trade_return,Rf=0,FUN="StdDev")
TradStrat_PT#2
StdDev Sharpe (Rf=0%, p=95%): -0.02944995
> SharpeRatio.annualized(trade_return,Rf=0)
TradStrat_PT#2
Annualized Sharpe Ratio (Rf=0%) -0.4974092
>
收益真惨🤣还有极大的优化空间。</roll_me,1,0))></roll_lb,1,0))>
来源:oschina
链接:https://my.oschina.net/changzw/blog/3164291