Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

### Activate the libraries required

library(quantmod)
library(tidyverse)
library(TTR)

### Obtaining stock prices for the stock AAP


AAP <- getSymbols("AAP", source = "yahoo",
auto.assign = FALSE,
return.class = "xts")[,6]
View(AAP)

### Calculate Returns


AAPret <- diff(log(AAP))
colnames(AAPret) <- "AAP"

### Trim the dataset


AAPret <- AAPret["2017/"]
AAP <- AAP["2017/"]

plot(AAP)

### Generate Simple Moving Averages


sma26 <- SMA(AAP, 26)
sma12 <- SMA(AAP, 12)

data <- na.omit(as.data.frame(cbind(AAP, AAPret, sma12, sma26)))


colnames(data) <- c("AAPPrices", "AAPret", "SMA12", "SMA26")

### Condition for Trend Following Strategy


### If short term MA is more than long term MA, buy
data$UD <- ifelse(data$SMA12 >= data$SMA26, 1, 0)
class(data$UD)
data

### Devise a trading strategy and backtest


data$Trade <- ifelse(data$UD == 1, "BUY", "SELL")
data$Position <- ifelse(data$Trade == "BUY", 1, -1)
data$AlgoRet <- data$AAPret * data$Position
AnnualizedReturn <- ((mean(data$AlgoRet)+1)^252 - 1)
plot(AAPret)
StanDev <- sd(data$AlgoRet)
rf <- 0.02
SharpeRatio <- (AnnualizedReturn - rf)/StanDev

print(paste("The trend-following algorithm was applied to the AAP stock prices and
was able to achieve an annualized return of", AnnualizedReturn,"%"))

plot(data$AAPPrices, type = "l", col = "red", xlab = "prices")


par(new = TRUE)
plot(data$SMA12, type = "l", col = "green")
par(new = TRUE)
plot(data$SMA26, type = "l", col = "blue")

You might also like