Created
April 7, 2023 18:54
-
-
Save 18182324/e357b1db81c20108ef80c2c4606c7c58 to your computer and use it in GitHub Desktop.
Momentum Trading in R
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
library(quantmod) | |
# Download SPY data from Yahoo Finance | |
getSymbols("SPY", src = "yahoo", from = "2007-01-01", to = "2022-04-07") | |
# Calculate moving average | |
ma_length <- 38 | |
ma <- SMA(Cl(SPY), n = ma_length) | |
# Calculate OBV | |
obv <- OBV(SPY) | |
# Define entry signals | |
entry_signal <- ifelse( | |
Cl(SPY) > ma & (Op(SPY) > lag(Low(SPY), default = na.locf(Low(SPY))) | lag(Op(SPY), default = na.locf(Op(SPY))) > ma & lag(Low(SPY), default = na.locf(Low(SPY))) > ma) & | |
Cl(SPY) > ma & (weekdays(index(SPY)) %in% c("Monday", "Wednesday", "Thursday", "Friday")) & | |
obv > SMA(obv, n = 200, na.rm = TRUE), 1, 0) | |
# Define exit signals | |
exit_signal <- SigCrossover(Cl(SPY), ma, cross = 1, saturate = FALSE) | |
# Combine signals | |
signal <- entry_signal * 1 - exit_signal * 1 | |
# Calculate returns and equity curve | |
returns <- ROC(Cl(SPY)) * signal | |
equity_curve <- cumprod(1 + returns) | |
# Display performance metrics | |
library(PerformanceAnalytics) | |
charts.PerformanceSummary(returns) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment