library(xts)
library(zoo)
library(quantmod) # data, plotting, quant modelling
library(PerformanceAnalytics) # performance and risk management
library(TTR)
library(knitr) # formatting tables
library(data.table)
library(magrittr)
Taiex <- fread("C:/Users/hiits/Downloads/DATA.TAIEX.2012.2022.txt",
select = c("CO_ID", "CoName", "Date", "Open","Close", "High", "Low", "Volume"), nrows = 1095)
date <- as.Date(as.character(Taiex$Date), format = '%Y%m%d')
Taiex.xts <- xts(Taiex[, -1], order.by = date)
#EXtract the closing price
data <- Taiex.xts$Close
#data <- transform( data,Close = as.numeric(Close))
data <- data %>% na.omit() %>% transform(Close = as.numeric(Close))
# Calculate the SMA
# Set "n=" to the SMA period
sma <- SMA(Cl(data), n=50)
# Calculate MACD
# Set "nsig=" to the SMA period
macd <- MACD(data, nFast=12, nSlow=26, nSig=50, maType=SMA, percent = FALSE)
# Calculate the buy/sell signals
signal <- Lag(ifelse(macd$macd < macd$signal, -1, 1))
# Calculate the returns from the Trading Strategy
returns <- ROC(data)*signal
# Remove not available values from the returns
returns <- na.omit(returns)
# Calculate the Portfolio
portfolio <- exp(cumsum(returns))
plotSMA <- plot(data, main="Returns with SMA Trend Line"); lines(sma, col="red")
#Plot of Buy/Sell/Hold signals
# Select next two lines of code, and run
plotBuySell <- plot(macd$signal, main="Buy/Sell/Hold Signal
Plot");lines(signal,col="red")
# Performance Summary Chart
charts.PerformanceSummary(returns, main = "Performance Summary Chart")
# Create Chart Series with MACD
# Set "signal=" to SMA period
chartSeries(data, name = "Strategy Chart Series", theme = chartTheme('white'),
TA=c(addVo(), addBBands(), addMACD(signal=50)))
Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.