Skip to content

Instantly share code, notes, and snippets.

@Beliavsky
Last active November 9, 2018 03:15
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 Beliavsky/82517a98753523ca20f1b529fe389f58 to your computer and use it in GitHub Desktop.
Save Beliavsky/82517a98753523ca20f1b529fe389f58 to your computer and use it in GitHub Desktop.
R script to test a MACD trading system
# adapted from https://www.quantinsti.com/blog/an-example-of-a-trading-strategy-coded-in-r
# issue the commands install.packages("quantmod") and install.packages("PerformanceAnalytics")
# before running this script
library("quantmod")
library("PerformanceAnalytics")
plot.macd = TRUE
ndrawdowns = 3
short.pos = 0 # size of short position. Set to 0 to disallow shorting
sym = "PCI" # symbol to be tested -- can be changed
all.data = getSymbols(sym,auto.assign=FALSE)
data=all.data[,6] # column 6 to use distribution-adjusted closing prices
macd = MACD(data, nFast=12, nSlow=26,nSig=9,maType=SMA,percent = FALSE)
if (plot.macd) {
chartSeries(all.data, TA=NULL)
chartSeries(data, TA="addMACD()")
}
signal = Lag(ifelse(macd$macd < macd$signal, short.pos, 1))
returns = ROC(data)*signal
portfolio = exp(cumsum(returns))
table.Drawdowns(returns, top=ndrawdowns)
table.DownsideRisk(returns)
charts.PerformanceSummary(returns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment