原创R语言TMA三均线策略实现附代码数据.docx
- 文档编号:1004734
- 上传时间:2023-04-30
- 格式:DOCX
- 页数:39
- 大小:198.34KB
原创R语言TMA三均线策略实现附代码数据.docx
《原创R语言TMA三均线策略实现附代码数据.docx》由会员分享,可在线阅读,更多相关《原创R语言TMA三均线策略实现附代码数据.docx(39页珍藏版)》请在冰点文库上搜索。
原创R语言TMA三均线策略实现附代码数据
source('in-sample_period.R')
library(TTR)
getOrders<-function(store,newRowList,currentPos,params){
allzero<-rep(0,length(newRowList))#usedforinitializingvectors
################################################
#Youdonotneedtoeditthispartofthecode
#thatinitializesandupdatesthestore
################################################
if(is.null(store))
store<-initStore(newRowList)
else
store<-updateStore(store,newRowList)
################################################
pos<-allzero
################################################
#Thisnextcodesectionistheonlyoneyou
#needtoeditforgetOrders
#
#Theifconditionisalreadycorrect:
#youshouldonlystartcomputingthemoving
#averageswhenyouhaveenoughcloseprices
#forthelongmovingaverage
################################################
if(store$iter>params$lookbacks$long){
for(indexin1:
length(params$series)){
current_close=last(store$cl[[index]])
close=store$cl[[index]]
xtsclose=as.xts(close)
GETtma=getTMA(xtsclose,params$lookbacks)
pos=getPosSignFromTMA(GETtma)*getPosSize(current_close)
}
}
################################################
#Youdonotneedtoeditthispartofthecode
#thatinitializesandupdatesthestore
################################################
marketOrders<--currentPos+pos
return(list(store=store,marketOrders=marketOrders,
limitOrders1=allzero,limitPrices1=allzero,
limitOrders2=allzero,limitPrices2=allzero))
}
########################################################################
#Thefollowingfunctionshouldbeeditedtocompletesteps1to3
#ofcomp22assignment2
getTMA<-function(close_prices,lookbacks){
if(!
("long"%in%names(lookbacks)&&"short"%in%names(lookbacks)&&"medium"%in%names(lookbacks)))
stop("E01:
Atleastoneof\"short\",\"medium\",\"long\"ismissingfromnames(lookbacks)")
#ReplaceTRUEto
#checkthattheelementsoflookbacksareallintegers
if(!
(class(lookbacks[[1]])=="integer"&&class(lookbacks[[2]])=="integer"&&class(lookbacks[[3]])=="integer"))
stop("E02:
Atleastoneofthelookbacksisnotanintegeraccordingtois.integer()")
#ReplaceTRUEto
#checkthatlookbacks$short if(! (lookbacks[[1]] stop("E03: Thelookbacksdonotsatisfylookbacks$short #ReplaceTRUEto #checkthatclose_pricesisanxts if(! (class(close_prices)[1]=="xts")) stop("E04: close_pricesisnotanxtsaccordingtois.xts()") #ReplaceTRUEto #checkthatclose_priceshasenoughrows if(nrow(close_prices) stop("E05: close_pricesdoesnotenoughrows") #ReplaceTRUEto #checkthatclose_pricescontainsacolumncalled"Close" if(! (colnames(close_prices)=="Close")) stop("E06: close_pricesdoesnotcontainacolumn\"Close\"") sma=numeric(0) for(iin1: 3){ sma[i]<-as.numeric(last(SMA(close_prices,n=lookbacks[[i]])))#TTRversion#converttovectorfromxts } smalist<-list(short=sma[1],medium=sma[2],long=sma[3]) #Youneedtoreplacetheassignmenttoretsothatthe #returnedobject: #-isalist #-hastherightnames(short,medium,long),and #-containsnumericandnotxtsobjects #-andcontainsthecorrectmovingaveragevalues,whichshould #havewindowsofthecorrectsizeswhichshouldallendinthe #sameperiodwhichshouldbethelastrowofclose_prices return(smalist) } getPosSignFromTMA<-function(tma_list){ if(tma_list$short elseif(tma_list$long>tma_list$medium&&tma_list$medium>tma_list$short)ret=-1 elseret=0 return(ret) } getPosSize<-function(current_close,constant=1000){ return(floor(constant/current_close)) } getInSampleResult<-function(){ TIme=getInSamplePeriod('x1xxx') dataList<-getData(directory="A2") dataList<-lapply(dataList,function(x)x[TIme[1]: TIme[2]]) lookbacks<-list(short=as.integer(5),medium=as.integer(10),long=as.integer(20)) sMult<-0.2#slippagemultiplier newRowList=getRowList(dataList,1) numOfSeries=length(dataList) params<-list(lookbacks=lookbacks,sdParam=1,series=1: numOfSeries)#,posSizes=rep(1,getPosSize(newRowList[[1]]$Close))) results<-backtest(dataList,getOrders,params,sMult) pfolioPnL<-plotResults(dataList,results) pfolioPnL$fitAgg cat("PDratio",pfolioPnL$fitAgg) } getInSampleOptResult<-function(){ sMult<-0.2#slippagemultiplier TIme=getInSamplePeriod('x4wl1')##### dataList<-getData(directory="A2") dataList<-lapply(dataList,function(x)x[TIme[1]: TIme[2]]) sMult<-0.2#slippagemultiplier numOfSeries=length(dataList) medium<-seq(from=105,to=120,by=5) short<-seq(from=100,to=110,by=5) long<-seq(from=110,to=130,by=5) time<-matrix(0,28,3) row=1 for(zin1: length(long)) for(iin1: length(short)) for(jin1: length(medium))if(short[i] row=row+1} colnames(time)=c("short","medium","long") resultsMatrix<-matrix(nrow=nrow(time),ncol=4) colnames(resultsMatrix)<-c("short","medium","long","PDratio") pfolioPnLList<-vector(mode="list",length=nrow(time)) count<-1 for(iin1: nrow(time)){ newRowList=getRowList(dataList,count) short=as.integer(time[i,1]);medium=as.integer(time[i,2]);long=as.integer(time[i,3]); lookbacks<-list(short=short,medium=medium,long=long) params<-list(lookbacks=lookbacks,sdParam=1,series=1: numOfSeries,posSizes=rep(1,getPosSize(newRowList[[1]]$Close))) results<-backtest(dataList,getOrders,params,sMult) pfolioPnL<-plotResults(dataList,results) resultsMatrix[count,]<-c(lookbacks[[1]],lookbacks[[2]],lookbacks[[3]],pfolioPnL$fitAgg) pfolioPnLList[[count]]<-pfolioPnL cat("Justcompleted",count,"outof",time,"\n") print(resultsMatrix[count,]) count<-count+1 } print(resultsMatrix[order(resultsMatrix[,"PDratio"]),]) return(max(resultsMatrix[,4])) } ######################################################################## #ThefunctionsbelowdoNOTneedtobeeditedforcomp226assignment2 initClStore<-function(newRowList){ clStore<-lapply(newRowList,function(x)x$Close) return(clStore) } updateClStore<-function(clStore,newRowList){ clStore<-mapply(function(x,y)rbind(x,y$Close),clStore,newRowList,SIMPLIFY=FALSE) return(clStore) } initStore<-function(newRowList,series){ return(list(iter=1,cl=initClStore(newRowList))) } updateStore<-function(store,newRowList){ store$iter<-store$iter+1 store$cl<-updateClStore(store$cl,newRowList) return(store) } #############################test library(TTR) ############getTMA source('framework/data.R') ##Loadingrequiredpackage: xts ##Loadingrequiredpackage: zoo ## ##Attachingpackage: 'zoo' ##Thefollowingobjectsaremaskedfrom'package: base': ## ##as.Date,as.Date.numeric ##Version0.4-0includednewdatadefaults.See? getSymbols. source('framework/backtester.R') source('framework/processResults.R') lookbacks<-list(short=as.integer(5),medium=as.integer(10),long=as.integer(20)) #Readindata dataList<-getData(directory="A2") ##Read3seriesfromDATA/A2 close_prices<-dataList[[1]]$Close[1: 20] getTMA(close_prices,lookbacks) ##$short ##[1]16.948 ## ##$medium ##[1]17.086 ## ##$long ##[1]17.1525 getPosSignFromTMA(getTMA(close_prices,lookbacks)) ##[1]1 current_close<-100.5 getPosSize(current_close) ##[1]9 getInSampleResult() ##Read3seriesfromDATA/A2 ##PDratio-107565.9 getInSampleOptResult() ##Read3seriesfromDATA/A2 ##Justcompleted1outof100100100105100100100105105110100100100100105105105110110100100100100105105105110110105105110110105110115110115115105110115120110115120115120105110115120110115120115120110115115115120120120120120120125125125125125125125125125130130130130130130130130130 ##shortmediumlongPDratio ##100.00105.00110.00-71145.22 ##Justcompleted2outof100100100105100100100105105110100100100100105105105110110100100100100105105105110110105105110110105110115110115115105110115120110115120115120105110115120110115120115120110115115115120120120120120120125125125125125125125125125130130130130130130130130130 ##shortmediumlongPDratio ##100.00105.00115.00-44965.95 ##Justcompleted3outof100100100105100100100105105110100100100100105105105110110100100100100105105105110110105105110110105110115110115115105110115120110115120115120105110115120110115120115120110115115115120120120120120120125125125125125125125125125130130130130130130130130130 ##shortmediumlongPDratio ##100.00110.00115.00-51909.61 ##Justcompleted4outof100100100105100100100105105110100100100100105105105110110100100100100105105105110110105105110110105110115110115115105110115120110115120115120105110115120110115120115120110115115115120120120120120120125125125125125125125125125130130130130130130130130130 ##shortmediumlongPDratio ##105.00110.00115.00-80736.32 ##Justcompleted5outof1001001001051001001001051051101001001001001051051051101101001001001001051051051101101051051101101051101151101151151051
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 原创 语言 TMA 三均线 策略 实现 代码 数据
![提示](https://static.bingdoc.com/images/bang_tan.gif)