Created
January 25, 2013 00:16
-
-
Save zachmayer/4630113 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Download S&P 500 data, adjust, and conver to monthly | |
| set.seed(42) | |
| library(quantmod) | |
| getSymbols('^GSPC', from='1990-01-01') | |
| GSPC <- adjustOHLC(GSPC, symbol.name='^GSPC') | |
| GSPC <- to.monthly(GSPC, indexAt='lastof') | |
| Target <- ClCl(GSPC) | |
| #Calculate some co-variates | |
| periods <- c(3, 6, 9, 12) | |
| Lags <- data.frame(lapply(c(1:2, periods), function(x) Lag(Target, x))) | |
| EMAs <- data.frame(lapply(periods, function(x) { | |
| out <- EMA(Target, x) | |
| names(out) <- paste('EMA', x, sep='.') | |
| return(out) | |
| })) | |
| RSIs <- data.frame(lapply(periods, function(x) { | |
| out <- RSI(Cl(GSPC), x) | |
| names(out) <- paste('RSI', x, sep='.') | |
| return(out) | |
| })) | |
| DVIs <- data.frame(lapply(periods, function(x) { | |
| out <- DVI(Cl(GSPC), x) | |
| out <- out$dvi | |
| names(out) <- paste('DVI', x, sep='.') | |
| return(out) | |
| })) | |
| dat <- data.frame(Next(Target), Lags, EMAs, RSIs, DVIs) | |
| dat <- na.omit(dat) | |
| #Custom Summary Function | |
| mySummary <- function (data, lev = NULL, model = NULL) { | |
| positions <- sign(data[, "pred"]) | |
| trades <- abs(c(1,diff(positions))) | |
| profits <- positions*data[, "obs"] + trades*0.01 | |
| profit <- prod(1+profits) | |
| names(profit) <- 'profit' | |
| return(profit) | |
| } | |
| #Fit a model | |
| library(caret) | |
| model <- train(dat[,-1], dat[,1], method='rpart', | |
| metric='profit', maximize=TRUE, | |
| trControl=trainControl( | |
| method='timeslice', | |
| initialWindow=12, fixedWindow=TRUE, | |
| horizon=12, summaryFunction=mySummary, | |
| verboseIter=TRUE)) | |
| model | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment