Last active
November 9, 2018 03:15
-
-
Save Beliavsky/82517a98753523ca20f1b529fe389f58 to your computer and use it in GitHub Desktop.
R script to test a MACD trading system
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
# 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