library(quantmod)
BTC <- quantmod::getSymbols("BTC-USD", auto.assign = FALSE)
colnames(BTC) <- stringr::str_replace_all(colnames(BTC), ".USD", "")
BTC.Cl <- Cl(BTC)
BTC.Cl$SMA <- SMACpp(BTC.Cl, 200)
BTC.Cl$SMAwei <- ifelse(BTC.Cl$BTC.Close > BTC.Cl$SMA, 1, 0)
BTC.Cl$diff <- diff(BTC.Cl$BTC.Close)
BTC.Cl$SMAre <- BTC.Cl$diff * lag(BTC.Cl$SMAwe)
model <- xts(order.by = index(BTC.Cl[200:nrow(BTC.Cl),]))
model$SMA <- cumsum(na.omit(BTC.Cl$SMAre))
plot(model$SMA)
## Transaction cost
InitialValue <- 0
TransCost <- 30
BTC.Cl$change <- ifelse(BTC.Cl$SMAwei != lag(BTC.Cl$SMAwei), 1, 0)
BTC.Cl$TransCost <- BTC.Cl$change * TransCost
BTC.Cl$SMAreTC <- BTC.Cl$SMAre - BTC.Cl$TransCost
foo <- BTC.Cl$SMAre - BTC.Cl$TransCost
foo[1,] <- InitialValue - BTC.Cl$BTC.Close[1,]
batman <- cumsum(na.omit(foo))
if(any(batman$SMAre < 0)) {stop("Bankrupt")}
model$SMA.TC <- cumsum(na.omit(BTC.Cl$SMAreTC))
plot(model$SMA.TC)
####################
##### Plotting #####
####################
fooA <- quantmod::getSymbols("BTC-USD", auto.assign = FALSE, from = "2018-01-01")
SMAstrate <- SimpleMovingAverage(quantmod::Cl(fooA["2018-01-21/"]), k = 6, Initpocket = 25000, TransCost = 10)
ROCstrate <- ROCmoving(quantmod::Cl(fooA["2018-01-20/"]), k = 6, Initpocket = 25000, TransCost = 10)
Errstrate <- ErrMoving(quantmod::Cl(fooA), k = 6, Initpocket = 25000, TransCost = 10)
Propstrate <- PropMoving(quantmod::Cl(fooA["2018-01-20/"]), k = 6, Initpocket = 25000, TransCost = 10, confidence.level = 0.55)
library(tidyr)
library(tibble)
library(ggplot2)
SMAdata <- do.call(cbind, SMAstrate$return)
SMAdata.tidy <- data.frame(Date = zoo::index(SMAdata), zoo::coredata(SMAdata)) %>%
gather(-Date, key = "Strategy", value = "Value")
ggplot(data = SMAdata.tidy, aes(x = Date, y = Value, color = Strategy)) +
geom_line()
### Transform data
data <- do.call(cbind, purrr::map(list(SMAstrate$return,
ROCstrate$return,
Errstrate$return,
Propstrate$return),
do.call, what = cbind))
data.tidy <- data.frame(Date = zoo::index(data), zoo::coredata(data)) %>%
gather(-Date, key = "Strategy", value = "value")
### Plot data
ggplot(data = dplyr::filter(data.tidy, Strategy %in% c("SMA.TCPocket","ROC.TCPocket",
"Err.TCPocket","Prop.TCPocket")),
aes(x = Date, y = value, color = Strategy)) +
geom_line()
### Table
do.call(cbind, list(ROCstrate$table,
SMAstrate$table,
Errstrate$table,
Propstrate$table))
### Weight plot
weight.tidy <- cbind(SMAstrate$SMA.weights,
ROCstrate$ROC.weights,
Errstrate$Err.weights,
Propstrate$Prop.weights)
colnames(weight.tidy) <- c("SMA.w", "ROC.w", "Err.w", "Prop.w")
weight.tidy <- data.frame(Date = zoo::index(weight.tidy), zoo::coredata(weight.tidy)) %>%
gather(-Date, key = "Strategy", value = "Position")
### Plot weight data
ggplot(weight.tidy,
aes(x = Date, y = Position, color = Strategy)) +
geom_line()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.