Last active
February 13, 2019 13:49
-
-
Save StuartGordonReid/a556266b995ad971ee37f3987c5ef64a to your computer and use it in GitHub Desktop.
This file contains 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
bettingStrategyProof <- function(t = (252 * 7), w = 5, sd = 0.02, sims = 30) { | |
# Store market and strategy returns. | |
markets <- NULL | |
strats <- NULL | |
for (i in 1:sims) { | |
# Generate an underlying signal. | |
signal <- sin(seq(1, t)) / 50 | |
signal <- signal - mean(signal) | |
# Add some noise to get a return series. | |
returns <- signal + rnorm(t, mean = 0.0, sd = sd) | |
# Keep track of our weights. | |
weights <- rep(0.0, w) | |
for (t in (w + 1):length(returns)) { | |
# Calculate the cumulative return to yesterday. | |
cumret <- mean(1 + returns[(t-w):(t-1)]) - 1 | |
# Determine if we are risk-on or risk-off: | |
if (cumret < 0) weights <- c(weights, 1.0) | |
else weights <- c(weights, -1.0) | |
} | |
# Turn our hypothetical returns into time series. | |
returns.weighted <- returns * weights | |
dates <- dates <- seq.Date(Sys.Date(), Sys.Date() + | |
length(returns) - 1, 1) | |
# Keep track of each of the market returns. | |
if (is.null(markets)) markets <- xts(returns, order.by = dates) | |
else markets <- merge.xts(markets, xts(returns, order.by = dates)) | |
# Keep track of each of the strategy returns. | |
if (is.null(strats)) strats <- xts(returns.weighted, order.by = dates) | |
else strats <- merge.xts(strats, xts(returns.weighted, order.by = dates)) | |
} | |
# Plot the returns generated by our toy markets. | |
charts.PerformanceSummary(xts(markets, order.by = dates), | |
colorset = (1:ncol(markets)), | |
legend.loc = NULL) | |
# Plot the returns generated by out strategy. | |
charts.PerformanceSummary(xts(strats, order.by = dates), | |
colorset = (1:ncol(strats)), | |
legend.loc = NULL) | |
# Plot the averages over the simulations to make the picture clearer. | |
mean.markets <- xts(rowSums(markets) / sims, order.by = index(markets)) | |
mean.strats <- xts(rowSums(strats) / sims, order.by = index(markets)) | |
charts.PerformanceSummary(merge.xts(mean.markets, mean.strats), | |
legend.loc = NULL) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment