Explore how we might use (abuse) pipes from pipeR
+ the htmlwidgets version of dygraphs
to explore a simple moving average strategy on the S&P 500.
# calculate moving average system in R with pipes
#devtools::install_github("renkun-ken/pipeR")
library(pipeR) # feel free to library(magrittr)
library(quantmod)
#devtools::install_github("rstudio/dygraphs")
library(dygraphs)
#devtools::install_github("ramnathv/htmlwidgets)
library(htmlwidgets)
"^GSPC" %>>%
getSymbols( from = "1900-01-01", auto.assign=F ) %>>%
( ~ sp500 ) %>>% # save so reduce traffic on yahoo! finance
( prices ~
runMean( prices[,6], n = 250 ) %>>%
( merge( prices[,6], .) ) %>>%
(
stats::lag( ifelse( .[,1] > .[,2], 1, 0 ), k = 1 ) *
(.[,1] / stats::lag(.[,1]) - 1)
) %>>%
na.fill(0) %>>%
(cumprod(1+.)) %>>%
'*'(as.numeric(prices[1,6])) %>>%
structure(dimnames = list(NULL,"MovAvgStrat")) %>>%
(merge(prices[,6], .))
) %>>%
dygraph (
main = " Piped Moving Average Strategy on S&P 500"
,height = 400
,width = 600
) %>>% (~ dG )
#dG %>>% saveWidget("temp.html",selfcontained=T) %>>% (~rCharts:::publish_.gist(files="temp.html",description="Simple Moving Average Strategy in R with pipes and widgets",id=NULL))