Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Created February 10, 2012 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timelyportfolio/1793607 to your computer and use it in GitHub Desktop.
Save timelyportfolio/1793607 to your computer and use it in GitHub Desktop.
use of systematic investor part 1
#highlight the very fine work of http://systematicinvestor.wordpress.com/
#adapted some of his code to provide an addtional example for
#those that might be interested
###############################################################################
# Load Systematic Investor Toolbox (SIT)
# http://systematicinvestor.wordpress.com/systematic-investor-toolbox/
###############################################################################
con = gzcon(url('http://www.systematicportfolio.com/sit.gz', 'rb'))
    source(con)
close(con)
###############################################################################
require(quantmod)
#*****************************************************************
# Load historical data
#******************************************************************
tickers = spl('^GSPC')
data <- new.env()
getSymbols(tickers, src = 'yahoo', from = '1896-01-01', env = data, auto.assign = T)
bt.prep(data, align='keep.all', dates='1896::2011')
#*****************************************************************
# Code Strategies
#******************************************************************
prices = data$prices
# Buy & Hold
data$weight[] = 1
buy.hold = bt.run(data)
# MA Cross
#Meban Faber 10 month or approximately 200 day moving average entry
sma = bt.apply(data, function(x) { SMA(Cl(x), 200) } )
data$weight[] = NA
#when price crosses 200 day moving average enter
data$weight[] = iif(prices >= sma, 1, 0)
sma.cross = bt.run(data, trade.summary=T)
# just do the cud function with ttrTests optimized value of 110 days
cud = bt.apply(data, function(x) {runSum(ifelse(ROC(x,1,type="discrete") > 0,1,-1),n=110)})
data$weight[] = NA
# buy an 100% if cud greater than 10
# buy 50% if cud between 0 and 10
# exit below 0
# this is not advice and is a bad system
# please do not use for real money
data$weight[] = iif(cud >= 10, 1, iif(cud >= 0 & cud <10, 0.5, 0))
cud.plus = bt.run(data, trade.summary=T)
#*****************************************************************
# Create Report
#******************************************************************
plotbt.custom.report(cud.plus, sma.cross)
#to compare to buy hold then
plotbt.custom.report(cud.plus, buy.hold)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment