Advertisement
Guest User

papakia

a guest
May 10th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.98 KB | None | 0 0
  1. ###################################################
  2. ### The Available Data
  3. ###################################################
  4. library(DMwR)
  5. data(GSPC)
  6.  
  7. ###################################################
  8. ### Handling time dependent data in R
  9. ###################################################
  10. library(xts)
  11. x1 <- xts(rnorm(100),seq(as.POSIXct("2000-01-01"),len=100,by="day"))
  12. x1[1:5]
  13. x2 <- xts(rnorm(100),seq(as.POSIXct("2000-01-01 13:00"),len=100,by="min"))
  14. x2[1:4]
  15. x3 <- xts(rnorm(3),as.Date(c('2005-01-01','2005-01-10','2005-01-12')))
  16. x3
  17.  
  18. x1[as.POSIXct("2000-01-04")]
  19. x1["2000-01-05"]
  20. x1["20000105"]
  21. x1["2000-04"]
  22. x1["2000-03-27/"]
  23. x1["2000-02-26/2000-03-03"]
  24. x1["/20000103"]
  25.  
  26. mts.vals <- matrix(round(rnorm(25),2),5,5)
  27. colnames(mts.vals) <- paste('ts',1:5,sep='')
  28. mts <- xts(mts.vals,as.POSIXct(c('2003-01-01','2003-01-04',
  29. '2003-01-05','2003-01-06','2003-02-16')))
  30. mts
  31. mts["2003-01",c("ts2","ts5")]
  32. index(mts)
  33. coredata(mts)
  34.  
  35. ###################################################
  36. ### Reading the data from the CSV file
  37. ###################################################
  38. GSPC <- as.xts(read.zoo('sp500.csv',header=T))
  39.  
  40.  
  41. ###################################################
  42. ### Getting the data from the Web
  43. ###################################################
  44. library(tseries)
  45. GSPC <- as.xts(get.hist.quote("^GSPC",start="1970-01-02",
  46. quote=c("Open", "High", "Low", "Close","Volume","AdjClose")))
  47. head(GSPC)
  48. GSPC <- as.xts(get.hist.quote("^GSPC",
  49. start="1970-01-02",end='2009-09-15',
  50. quote=c("Open", "High", "Low", "Close","Volume","AdjClose")))
  51.  
  52. library(quantmod)
  53. getSymbols('^GSPC')
  54.  
  55. getSymbols('^GSPC',from='1970-01-01',to='2009-09-15')
  56. colnames(GSPC) <- c("Open", "High", "Low", "Close","Volume","AdjClose")
  57.  
  58. setSymbolLookup(IBM=list(name='IBM',src='yahoo'),
  59. USDEUR=list(name='USD/EUR',src='oanda',
  60. from=as.Date('2009-01-01')))
  61. getSymbols(c('IBM','USDEUR'))
  62. head(IBM)
  63. head(USDEUR)
  64.  
  65. ###################################################
  66. ### Reading the data from a MySQL database
  67. ###################################################
  68. library(RODBC)
  69. ch <- odbcConnect("QuotesDSN",uid="myusername",pwd="mypassword")
  70. allQuotes <- sqlFetch(ch,"gspc")
  71. GSPC <- xts(allQuotes[,-1],order.by=as.Date(allQuotes[,1]))
  72. head(GSPC)
  73. odbcClose(ch)
  74.  
  75. library(DBI)
  76. library(RMySQL)
  77. drv <- dbDriver("MySQL")
  78. ch <- dbConnect(drv,dbname="Quotes","myusername","mypassword")
  79. allQuotes <- dbGetQuery(ch,"select * from gspc")
  80. GSPC <- xts(allQuotes[,-1],order.by=as.Date(allQuotes[,1]))
  81. head(GSPC)
  82. dbDisconnect(ch)
  83. dbUnloadDriver(drv)
  84.  
  85. setSymbolLookup(GSPC=list(name='gspc',src='mysql',
  86. db.fields=c('Index','Open','High','Low','Close','Volume','AdjClose'),
  87. user='xpto',password='ypto',dbname='Quotes'))
  88. getSymbols('GSPC')
  89.  
  90. ###################################################
  91. ### Defining the Prediction Tasks
  92. ###################################################
  93. T.ind <- function(quotes,tgt.margin=0.025,n.days=10) {
  94. v <- apply(HLC(quotes),1,mean)
  95.  
  96. r <- matrix(NA,ncol=n.days,nrow=NROW(quotes))
  97. ## The following statment is wrong in the book (page 109)!
  98. for(x in 1:n.days) r[,x] <- Next(Delt(Cl(quotes),v,k=x),x)
  99.  
  100. x <- apply(r,1,function(x) sum(x[x > tgt.margin | x < -tgt.margin]))
  101. if (is.xts(quotes)) xts(x,time(quotes)) else x
  102. }
  103.  
  104. candleChart(last(GSPC,'3 months'),theme='white',TA=NULL)
  105. avgPrice <- function(p) apply(HLC(p),1,mean)
  106. addAvgPrice <- newTA(FUN=avgPrice,col=1,legend='AvgPrice')
  107. addT.ind <- newTA(FUN=T.ind,col='red',legend='tgtRet')
  108. addAvgPrice(on=1)
  109. addT.ind()
  110.  
  111. myATR <- function(x) ATR(HLC(x))[,'atr']
  112. mySMI <- function(x) SMI(HLC(x))[,'SMI']
  113. myADX <- function(x) ADX(HLC(x))[,'ADX']
  114. myAroon <- function(x) aroon(x[,c('High','Low')])$oscillator
  115. myBB <- function(x) BBands(HLC(x))[,'pctB']
  116. myChaikinVol <- function(x) Delt(chaikinVolatility(x[,c("High","Low")]))[,1]
  117. myCLV <- function(x) EMA(CLV(HLC(x)))[,1]
  118. myEMV <- function(x) EMV(x[,c('High','Low')],x[,'Volume'])[,2]
  119. myMACD <- function(x) MACD(Cl(x))[,2]
  120. myMFI <- function(x) MFI(x[,c("High","Low","Close")], x[,"Volume"])
  121. mySAR <- function(x) SAR(x[,c('High','Close')]) [,1]
  122. myVolat <- function(x) volatility(OHLC(x),calc="garman")[,1]
  123.  
  124. library(randomForest)
  125. data.model <- specifyModel(T.ind(GSPC) ~ Delt(Cl(GSPC),k=1:10) +
  126. myATR(GSPC) + mySMI(GSPC) + myADX(GSPC) + myAroon(GSPC) +
  127. myBB(GSPC) + myChaikinVol(GSPC) + myCLV(GSPC) +
  128. CMO(Cl(GSPC)) + EMA(Delt(Cl(GSPC))) + myEMV(GSPC) +
  129. myVolat(GSPC) + myMACD(GSPC) + myMFI(GSPC) + RSI(Cl(GSPC)) +
  130. mySAR(GSPC) + runMean(Cl(GSPC)) + runSD(Cl(GSPC)))
  131. set.seed(1234)
  132. rf <- buildModel(data.model,method='randomForest',
  133. training.per=c(start(GSPC),index(GSPC["1999-12-31"])),
  134. ntree=50, importance=T)
  135.  
  136. ex.model <- specifyModel(T.ind(IBM) ~ Delt(Cl(IBM),k=1:3))
  137. data <- modelData(ex.model,data.window=c('2009-01-01','2009-08-10'))
  138.  
  139. varImpPlot(rf@fitted.model,type=1)
  140.  
  141. imp <- importance(rf@fitted.model,type=1)
  142. rownames(imp)[which(imp > 10)]
  143.  
  144. data.model <- specifyModel(T.ind(GSPC) ~ Delt(Cl(GSPC),k=1) + myATR(GSPC) + myADX(GSPC) + myEMV(GSPC) + myVolat(GSPC) + myMACD(GSPC) + mySAR(GSPC) + runMean(Cl(GSPC)) )
  145.  
  146. Tdata.train <- as.data.frame(modelData(data.model,
  147. data.window=c('1970-01-02','1999-12-31')))
  148. Tdata.eval <- na.omit(as.data.frame(modelData(data.model,
  149. data.window=c('2000-01-01','2009-09-15'))))
  150. Tform <- as.formula('T.ind.GSPC ~ .')
  151.  
  152. ###################################################
  153. ### The Prediction Models
  154. ###################################################
  155. set.seed(1234)
  156. library(nnet)
  157. norm.data <- scale(Tdata.train)
  158. nn <- nnet(Tform,norm.data[1:1000,],size=10,decay=0.01,maxit=1000,linout=T,trace=F)
  159. norm.preds <- predict(nn,norm.data[1001:2000,])
  160. preds <- unscale(norm.preds,norm.data)
  161.  
  162. sigs.nn <- trading.signals(preds,0.1,-0.1)
  163. true.sigs <- trading.signals(Tdata.train[1001:2000,'T.ind.GSPC'],0.1,-0.1)
  164. sigs.PR(sigs.nn,true.sigs)
  165.  
  166. set.seed(1234)
  167. library(nnet)
  168. signals <- trading.signals(Tdata.train[,'T.ind.GSPC'],0.1,-0.1)
  169. norm.data <- data.frame(signals=signals,scale(Tdata.train[,-1]))
  170. nn <- nnet(signals ~ .,norm.data[1:1000,],size=10,decay=0.01,maxit=1000,trace=F)
  171. preds <- predict(nn,norm.data[1001:2000,],type='class')
  172.  
  173. sigs.PR(preds,norm.data[1001:2000,1])
  174.  
  175. library(e1071)
  176. sv <- svm(Tform,Tdata.train[1:1000,],gamma=0.001,cost=100)
  177. s.preds <- predict(sv,Tdata.train[1001:2000,])
  178. sigs.svm <- trading.signals(s.preds,0.1,-0.1)
  179. true.sigs <- trading.signals(Tdata.train[1001:2000,'T.ind.GSPC'],0.1,-0.1)
  180. sigs.PR(sigs.svm,true.sigs)
  181.  
  182. library(kernlab)
  183. data <- cbind(signals=signals,Tdata.train[,-1])
  184. ksv <- ksvm(signals ~ .,data[1:1000,],C=10)
  185. ks.preds <- predict(ksv,data[1001:2000,])
  186. sigs.PR(ks.preds,data[1001:2000,1])
  187.  
  188. library(earth)
  189. e <- earth(Tform,Tdata.train[1:1000,])
  190. e.preds <- predict(e,Tdata.train[1001:2000,])
  191. sigs.e <- trading.signals(e.preds,0.1,-0.1)
  192. true.sigs <- trading.signals(Tdata.train[1001:2000,'T.ind.GSPC'],0.1,-0.1)
  193. sigs.PR(sigs.e,true.sigs)
  194.  
  195. ###################################################
  196. ### From Predictions into Actions
  197. ###################################################
  198. policy.1 <- function(signals,market,opened.pos,money,
  199. bet=0.2,hold.time=10,
  200. exp.prof=0.025, max.loss= 0.05
  201. )
  202. {
  203. d <- NROW(market) # this is the ID of today
  204. orders <- NULL
  205. nOs <- NROW(opened.pos)
  206. # nothing to do!
  207. if (!nOs && signals[d] == 'h') return(orders)
  208.  
  209. # First lets check if we can open new positions
  210. # i) long positions
  211. if (signals[d] == 'b' && !nOs) {
  212. quant <- round(bet*money/market[d,'Close'],0)
  213. if (quant > 0)
  214. orders <- rbind(orders,
  215. data.frame(order=c(1,-1,-1),order.type=c(1,2,3),
  216. val = c(quant,
  217. market[d,'Close']*(1+exp.prof),
  218. market[d,'Close']*(1-max.loss)
  219. ),
  220. action = c('open','close','close'),
  221. posID = c(NA,NA,NA)
  222. )
  223. )
  224.  
  225. # ii) short positions
  226. } else if (signals[d] == 's' && !nOs) {
  227. # this is the nr of stocks we already need to buy
  228. # because of currently opened short positions
  229. need2buy <- sum(opened.pos[opened.pos[,'pos.type']==-1,
  230. "N.stocks"])*market[d,'Close']
  231. quant <- round(bet*(money-need2buy)/market[d,'Close'],0)
  232. if (quant > 0)
  233. orders <- rbind(orders,
  234. data.frame(order=c(-1,1,1),order.type=c(1,2,3),
  235. val = c(quant,
  236. market[d,'Close']*(1-exp.prof),
  237. market[d,'Close']*(1+max.loss)
  238. ),
  239. action = c('open','close','close'),
  240. posID = c(NA,NA,NA)
  241. )
  242. )
  243. }
  244.  
  245. # Now lets check if we need to close positions
  246. # because their holding time is over
  247. if (nOs)
  248. for(i in 1:nOs) {
  249. if (d - opened.pos[i,'Odate'] >= hold.time)
  250. orders <- rbind(orders,
  251. data.frame(order=-opened.pos[i,'pos.type'],
  252. order.type=1,
  253. val = NA,
  254. action = 'close',
  255. posID = rownames(opened.pos)[i]
  256. )
  257. )
  258. }
  259.  
  260. orders
  261. }
  262.  
  263.  
  264. policy.2 <- function(signals,market,opened.pos,money,
  265. bet=0.2,exp.prof=0.025, max.loss= 0.05
  266. )
  267. {
  268. d <- NROW(market) # this is the ID of today
  269. orders <- NULL
  270. nOs <- NROW(opened.pos)
  271. # nothing to do!
  272. if (!nOs && signals[d] == 'h') return(orders)
  273.  
  274. # First lets check if we can open new positions
  275. # i) long positions
  276. if (signals[d] == 'b') {
  277. quant <- round(bet*money/market[d,'Close'],0)
  278. if (quant > 0)
  279. orders <- rbind(orders,
  280. data.frame(order=c(1,-1,-1),order.type=c(1,2,3),
  281. val = c(quant,
  282. market[d,'Close']*(1+exp.prof),
  283. market[d,'Close']*(1-max.loss)
  284. ),
  285. action = c('open','close','close'),
  286. posID = c(NA,NA,NA)
  287. )
  288. )
  289.  
  290. # ii) short positions
  291. } else if (signals[d] == 's') {
  292. # this is the money already committed to buy stocks
  293. # because of currently opened short positions
  294. need2buy <- sum(opened.pos[opened.pos[,'pos.type']==-1,
  295. "N.stocks"])*market[d,'Close']
  296. quant <- round(bet*(money-need2buy)/market[d,'Close'],0)
  297. if (quant > 0)
  298. orders <- rbind(orders,
  299. data.frame(order=c(-1,1,1),order.type=c(1,2,3),
  300. val = c(quant,
  301. market[d,'Close']*(1-exp.prof),
  302. market[d,'Close']*(1+max.loss)
  303. ),
  304. action = c('open','close','close'),
  305. posID = c(NA,NA,NA)
  306. )
  307. )
  308. }
  309.  
  310. orders
  311. }
  312.  
  313. # Train and test periods
  314. start <- 1
  315. len.tr <- 1000
  316. len.ts <- 500
  317. tr <- start:(start+len.tr-1)
  318. ts <- (start+len.tr):(start+len.tr+len.ts-1)
  319.  
  320. # getting the quotes for the testing period
  321. data(GSPC)
  322. date <- rownames(Tdata.train[start+len.tr,])
  323. market <- GSPC[paste(date,'/',sep='')][1:len.ts]
  324.  
  325. # learning the model and obtaining its signal predictions
  326. library(e1071)
  327. s <- svm(Tform,Tdata.train[tr,],cost=10,gamma=0.01)
  328. p <- predict(s,Tdata.train[ts,])
  329. sig <- trading.signals(p,0.1,-0.1)
  330.  
  331. # now using the simulated trader
  332. t1 <- trading.simulator(market,sig,
  333. 'policy.1',list(exp.prof=0.05,bet=0.2,hold.time=30))
  334.  
  335. t1
  336. summary(t1)
  337.  
  338. tradingEvaluation(t1)
  339.  
  340. plot(t1,market,theme='white',name='SP500')
  341.  
  342. t2 <- trading.simulator(market,sig,'policy.2',list(exp.prof=0.05,bet=0.3))
  343. summary(t2)
  344. tradingEvaluation(t2)
  345.  
  346. start <- 2000
  347. len.tr <- 1000
  348. len.ts <- 500
  349. tr <- start:(start+len.tr-1)
  350. ts <- (start+len.tr):(start+len.tr+len.ts-1)
  351. s <- svm(Tform,Tdata.train[tr,],cost=10,gamma=0.01)
  352. p <- predict(s,Tdata.train[ts,])
  353. sig <- trading.signals(p,0.1,-0.1)
  354. t2 <- trading.simulator(market,sig,'policy.2',list(exp.prof=0.05,bet=0.3))
  355. summary(t2)
  356. tradingEvaluation(t2)
  357.  
  358. ###################################################
  359. ### Model Evaluation and Selection
  360. ###################################################
  361. MC.svmR <- function(form,train,test,b.t=0.1,s.t=-0.1,...) {
  362. require(e1071)
  363. t <- svm(form,train,...)
  364. p <- predict(t,test)
  365. trading.signals(p,b.t,s.t)
  366. }
  367. MC.svmC <- function(form,train,test,b.t=0.1,s.t=-0.1,...) {
  368. require(e1071)
  369. tgtName <- all.vars(form)[1]
  370. train[,tgtName] <- trading.signals(train[,tgtName],b.t,s.t)
  371. t <- svm(form,train,...)
  372. p <- predict(t,test)
  373. factor(p,levels=c('s','h','b'))
  374. }
  375. MC.nnetR <- function(form,train,test,b.t=0.1,s.t=-0.1,...) {
  376. require(nnet)
  377. t <- nnet(form,train,...)
  378. p <- predict(t,test)
  379. trading.signals(p,b.t,s.t)
  380. }
  381. MC.nnetC <- function(form,train,test,b.t=0.1,s.t=-0.1,...) {
  382. require(nnet)
  383. tgtName <- all.vars(form)[1]
  384. train[,tgtName] <- trading.signals(train[,tgtName],b.t,s.t)
  385. t <- nnet(form,train,...)
  386. p <- predict(t,test,type='class')
  387. factor(p,levels=c('s','h','b'))
  388. }
  389. MC.earth <- function(form,train,test,b.t=0.1,s.t=-0.1,...) {
  390. require(earth)
  391. t <- earth(form,train,...)
  392. p <- predict(t,test)
  393. trading.signals(p,b.t,s.t)
  394. }
  395. singleModel <- function(form,train,test,learner,policy.func,...) {
  396. p <- do.call(paste('MC',learner,sep='.'),list(form,train,test,...))
  397. eval.stats(form,train,test,p,policy.func=policy.func)
  398. }
  399. slide <- function(form,train,test,learner,relearn.step,policy.func,...) {
  400. real.learner <- learner(paste('MC',learner,sep='.'),pars=list(...))
  401. p <- slidingWindowTest(real.learner,form,train,test,relearn.step)
  402. p <- factor(p,levels=1:3,labels=c('s','h','b'))
  403. eval.stats(form,train,test,p,policy.func=policy.func)
  404. }
  405. grow <- function(form,train,test,learner,relearn.step,policy.func,...) {
  406. real.learner <- learner(paste('MC',learner,sep='.'),pars=list(...))
  407. p <- growingWindowTest(real.learner,form,train,test,relearn.step)
  408. p <- factor(p,levels=1:3,labels=c('s','h','b'))
  409. eval.stats(form,train,test,p,policy.func=policy.func)
  410. }
  411.  
  412. eval.stats <- function(form,train,test,preds,b.t=0.1,s.t=-0.1,...) {
  413. # Signals evaluation
  414. tgtName <- all.vars(form)[1]
  415. test[,tgtName] <- trading.signals(test[,tgtName],b.t,s.t)
  416. st <- sigs.PR(preds,test[,tgtName])
  417. dim(st) <- NULL
  418. names(st) <- paste(rep(c('prec','rec'),each=3),
  419. c('s','b','sb'),sep='.')
  420.  
  421. # Trading evaluation
  422. date <- rownames(test)[1]
  423. market <- GSPC[paste(date,"/",sep='')][1:length(preds),]
  424. trade.res <- trading.simulator(market,preds,...)
  425.  
  426. c(st,tradingEvaluation(trade.res))
  427. }
  428.  
  429.  
  430. pol1 <- function(signals,market,op,money)
  431. policy.1(signals,market,op,money,
  432. bet=0.2,exp.prof=0.025,max.loss=0.05,hold.time=10)
  433.  
  434. pol2 <- function(signals,market,op,money)
  435. policy.1(signals,market,op,money,
  436. bet=0.2,exp.prof=0.05,max.loss=0.05,hold.time=20)
  437.  
  438. pol3 <- function(signals,market,op,money)
  439. policy.2(signals,market,op,money,
  440. bet=0.5,exp.prof=0.05,max.loss=0.05)
  441.  
  442.  
  443. # The list of learners we will use
  444. TODO <- c('svmR','svmC','earth','nnetR','nnetC')
  445.  
  446. # The data sets used in the comparison
  447. DSs <- list(dataset(Tform,Tdata.train,'SP500'))
  448.  
  449. # Monte Carlo (MC) settings used
  450. MCsetts <- mcSettings(20, # 20 repetitions of the MC exps
  451. 2540, # ~ 10 years for training
  452. 1270, # ~ 5 years for testing
  453. 1234) # random number generator seed
  454.  
  455. # Variants to try for all learners
  456. VARS <- list()
  457. VARS$svmR <- list(cost=c(10,150),gamma=c(0.01,0.001),
  458. policy.func=c('pol1','pol2','pol3'))
  459. VARS$svmC <- list(cost=c(10,150),gamma=c(0.01,0.001),
  460. policy.func=c('pol1','pol2','pol3'))
  461. VARS$earth <- list(nk=c(10,17),degree=c(1,2),thresh=c(0.01,0.001),
  462. policy.func=c('pol1','pol2','pol3'))
  463. VARS$nnetR <- list(linout=T,maxit=750,size=c(5,10),
  464. decay=c(0.001,0.01),
  465. policy.func=c('pol1','pol2','pol3'))
  466. VARS$nnetC <- list(maxit=750,size=c(5,10),decay=c(0.001,0.01),
  467. policy.func=c('pol1','pol2','pol3'))
  468.  
  469. # main loop
  470. for(td in TODO) {
  471. assign(td,
  472. experimentalComparison(
  473. DSs,
  474. c(
  475. do.call('variants',
  476. c(list('singleModel',learner=td),VARS[[td]],
  477. varsRootName=paste('single',td,sep='.'))),
  478. do.call('variants',
  479. c(list('slide',learner=td,
  480. relearn.step=c(60,120)),
  481. VARS[[td]],
  482. varsRootName=paste('slide',td,sep='.'))),
  483. do.call('variants',
  484. c(list('grow',learner=td,
  485. relearn.step=c(60,120)),
  486. VARS[[td]],
  487. varsRootName=paste('grow',td,sep='.')))
  488. ),
  489. MCsetts)
  490. )
  491.  
  492. # save the results
  493. save(list=td,file=paste(td,'Rdata',sep='.'))
  494. }
  495.  
  496. load('svmR.Rdata')
  497. load('svmC.Rdata')
  498. load('earth.Rdata')
  499. load('nnetR.Rdata')
  500. load('nnetC.Rdata')
  501.  
  502. tgtStats <- c('prec.sb','Ret','PercProf',
  503. 'MaxDD','SharpeRatio')
  504. allSysRes <- join(subset(svmR,stats=tgtStats),
  505. subset(svmC,stats=tgtStats),
  506. subset(nnetR,stats=tgtStats),
  507. subset(nnetC,stats=tgtStats),
  508. subset(earth,stats=tgtStats),
  509. by = 'variants')
  510. rankSystems(allSysRes,5,maxs=c(T,T,T,F,T))
  511.  
  512. summary(subset(svmC,
  513. stats=c('Ret','RetOverBH','PercProf','NTrades'),
  514. vars=c('slide.svmC.v5','slide.svmC.v6')))
  515.  
  516. fullResults <- join(svmR,svmC,earth,nnetC,nnetR,by='variants')
  517. nt <- statScores(fullResults,'NTrades')[[1]]
  518. rt <- statScores(fullResults,'Ret')[[1]]
  519. pp <- statScores(fullResults,'PercProf')[[1]]
  520. s1 <- names(nt)[which(nt > 20)]
  521. s2 <- names(rt)[which(rt > 0.5)]
  522. s3 <- names(pp)[which(pp > 40)]
  523. namesBest <- intersect(intersect(s1,s2),s3)
  524. compAnalysis(subset(fullResults,
  525. stats=tgtStats,
  526. vars=namesBest))
  527. plot(subset(fullResults,
  528. stats=c('Ret','PercProf','MaxDD'),
  529. vars=namesBest))
  530. getVariant('single.nnetR.v12',nnetR)
  531.  
  532. ###################################################
  533. ### The Trading System
  534. ###################################################
  535. data <- tail(Tdata.train,2540)
  536. results <- list()
  537. for(name in namesBest) {
  538. sys <- getVariant(name,fullResults)
  539. results[[name]] <- runLearner(sys,Tform,data,Tdata.eval)
  540. }
  541. results <- t(as.data.frame(results))
  542. results[,c('Ret','RetOverBH','MaxDD','SharpeRatio','NTrades','PercProf')]
  543. getVariant('grow.nnetR.v12',fullResults)
  544.  
  545. model <- learner('MC.nnetR',list(maxit=750,linout=T,trace=F,size=10,decay=0.001))
  546. preds <- growingWindowTest(model,Tform,data,Tdata.eval,relearn.step=120)
  547. signals <- factor(preds,levels=1:3,labels=c('s','h','b'))
  548. date <- rownames(Tdata.eval)[1]
  549. market <- GSPC[paste(date,"/",sep='')][1:length(signals),]
  550. trade.res <- trading.simulator(market,signals,policy.func='pol2')
  551. plot(trade.res,market,theme='white',name='SP500 - final test')
  552.  
  553. library(PerformanceAnalytics)
  554. rets <- Return.calculate(trade.res@trading$Equity)
  555. chart.CumReturns(rets,main='Cumulative returns of the strategy',ylab='returns')
  556. yearlyReturn(trade.res@trading$Equity)
  557.  
  558. plot(100*yearlyReturn(trade.res@trading$Equity),
  559. main='Yearly percentage returns of the trading system')
  560. abline(h=0,lty=2)
  561.  
  562. table.CalendarReturns(rets)
  563. table.DownsideRisk(rets)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement