this is a code for ema 20-50 crossover strategy i can chart the strategy and generate buy and sell signals but unable to figure how to plot them. This code plots ema for 20days and 50 days when the cross signals are generated i.e. buy and sell signals. in this code it generated numerically but i would like to plot those points
library(quantmod)
library(TTR)
library(PerformanceAnalytics)
{
getSymbols('^NSEI', src = 'yahoo', from = '2016-01-01')
na.omit(NSEI)
NSEI <- nsei <-na.approx(NSEI)
}
{
EMA_NSEI_ret <- ret_NSEI*EMA_NSEI_strat
EMA_NSEI_ret_commission_adj <- ifelse((EMA_NSEI_ts == 1|EMA_NSEI_ts == -1) & EMA_NSEI_strat != Lag(EMA_NSEI_ts), (ret_NSEI-0.05)*EMA_NSEI_strat, ret_NSEI*EMA_NSEI_strat)
EMA_NSEI_comp <- cbind(EMA_NSEI_ret, EMA_NSEI_ret_commission_adj, benchmark_NSEI)
colnames(EMA_NSEI_comp) <- c('EMA','EMA Commission Adj','NSEI Benchmark')
charts.PerformanceSummary(EMA_NSEI_comp, main = 'NSEI EMA Performance')
EMA_NSEI_comp_table <- table.AnnualizedReturns(EMA_NSEI_comp)
}
{
EMA_NSEI_strat <- ifelse(EMA_NSEI_ts > 1,0,1)
for (i in 1 : length(Cl(NSEI))) {
EMA_NSEI_strat[i] <- ifelse(EMA_NSEI_ts[i] == 1,1,ifelse(EMA_NSEI_ts[i] == -1,0,EMA_NSEI_strat[i-1]))
}
EMA_NSEI_strat[is.na(EMA_NSEI_strat)] <- 1
EMA_NSEI_stratcomp <- cbind(EMA20_NSEI, EMA50_NSEI, EMA_NSEI_ts, EMA_NSEI_strat)
colnames(EMA_NSEI_stratcomp) <- c('EMA(20)','EMA(50)','EMA SIGNAL','EMA POSITION')
}
EMA20_NSEI <- EMA(NSEI$NSEI.Close, n = 20)
EMA50_NSEI <- EMA(NSEI$NSEI.Close, n = 50)
lineChart(NSEI, theme = chartTheme('black'))
addEMA(n = 20, col = 'blue')
addEMA(n = 50, col = 'orange')
legend('left', col = c('green','blue','orange'),
legend = c('NSEI','EMA20','EMA50'), lty = 1, bty = 'n',
text.col = 'white', cex = 0.8)
# EMA 20 Crossover Signal
EMA20_NSEI_ts <- Lag(
ifelse(Lag(Cl(NSEI)) < Lag(EMA20_NSEI) & Cl(NSEI) > EMA20_NSEI,1,
ifelse(Lag(Cl(NSEI)) > Lag(EMA20_NSEI) & Cl(NSEI) < EMA20_NSEI,-1,0)))
EMA20_NSEI_ts[is.na(EMA20_NSEI_ts)] <- 0
# EMA 50 Crossover Signal
EMA50_NSEI_ts <- Lag(
ifelse(Lag(Cl(NSEI)) < Lag(EMA50_NSEI) & Cl(NSEI) > EMA50_NSEI,1,
ifelse(Lag(Cl(NSEI)) > Lag(EMA50_NSEI) & Cl(NSEI) < EMA50_NSEI,-1,0)))
EMA50_NSEI_ts[is.na(EMA50_NSEI_ts)] <- 0
# EMA 20 and EMA 50 Crossover Signal
EMA_NSEI_ts <- Lag(
ifelse(Lag(EMA20_NSEI) < Lag(EMA50_NSEI) & EMA20_NSEI > EMA50_NSEI,1,
ifelse(Lag(EMA20_NSEI) > Lag(EMA50_NSEI) & EMA20_NSEI < EMA50_NSEI,-1,0)))
{
EMA_NSEI_ts[is.na(EMA_NSEI_ts)] <- 0
EMA_NSEI_ret <- ret_NSEI*EMA_NSEI_strat
EMA_NSEI_ret_commission_adj <- ifelse((EMA_NSEI_ts == 1|EMA_NSEI_ts == -1) & EMA_NSEI_strat != Lag(EMA_NSEI_ts), (ret_NSEI-0.05)*EMA_NSEI_strat, ret_NSEI*EMA_NSEI_strat)
EMA_NSEI_comp <- cbind(EMA_NSEI_ret, EMA_NSEI_ret_commission_adj, benchmark_NSEI)
colnames(EMA_NSEI_comp) <- c('EMA','EMA Commission Adj','NSEI Benchmark')
charts.PerformanceSummary(EMA_NSEI_comp, main = 'NSEI EMA Performance')
EMA_NSEI_comp_table <- table.AnnualizedReturns(EMA_NSEI_comp)
}
{
ret_NSEI <- diff(log(Cl(NSEI)))
benchmark_NSEI <- ret_NSEI
}