Exploring a Simple Yet Effective Trading Strategy: EMA Crossover Strategy Backtesting with NSE: Reliance
In the dynamic world of financial markets, traders constantly seek strategies that can provide them with an edge in making profitable decisions. One such strategy that has gained popularity among traders is the Exponential Moving Average (EMA) crossover strategy. In this blog post, we will delve into the intricacies of this strategy and conduct a backtest to evaluate its effectiveness, this time focusing on Reliance Industries Limited (RELIANCE) stock.
Understanding the EMA Crossover Strategy:
The EMA crossover strategy is a technical analysis technique that leverages two Exponential Moving Averages with different time periods. The strategy generates buy and sell signals based on the crossover of these EMAs. Specifically, when the shorter EMA crosses above the longer EMA, it signals a potential buying opportunity, and conversely, when the shorter EMA crosses below the longer EMA, it signals a potential selling opportunity.
Fetching Historical Data and Plotting Candlestick Charts:
To begin our exploration, we utilize the `yfinance` library to fetch historical stock data from Yahoo Finance, focusing this time on Reliance Industries Limited (RELIANCE) stock. We then employ `mplfinance` to plot candlestick charts, providing a visual representation of the stock's price movements over time.
Implementing the Strategy and Backtesting:
With our historical data in hand, we calculate the EMAs for RELIANCE stock with time periods of 10 and 30. Next, we implement the EMA crossover strategy by generating buy and sell signals based on the crossover of these EMAs. These signals are then used to simulate trading decisions in a backtesting environment.
During the backtest, we start with an initial capital of $100,000 and execute trades according to the generated signals. We keep track of the total number of trades, winning trades, and calculate the resulting profit. Additionally, we assess the strategy's performance by calculating the win ratio and drawdown ratio.
Evaluating Performance Metrics:
Upon completing the backtest, we evaluate the performance of the EMA crossover strategy with RELIANCE stock. By analyzing metrics such as total trades, winning trades, profit, win ratio, and drawdown ratio, we gain insights into the effectiveness of the strategy in generating returns and managing risk.
Conclusion:
In conclusion, the EMA crossover strategy offers a straightforward yet powerful approach to trading in financial markets, even with RELIANCE stock. By leveraging the crossover of Exponential Moving Averages, traders can identify potential entry and exit points with relative ease. However, it is important to note that no trading strategy is foolproof, and thorough backtesting and risk management are essential for success in the markets. As always, traders should conduct their own research and consider multiple factors before implementing any strategy in their trading endeavors.
Sample Code:
import talib
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import mplfinance as mpf
import warnings
# Suppressing warnings
warnings.filterwarnings("ignore")
# Fetching data from Yahoo Finance
ticker = "RELIANCE.NS"
start_date = "2014-01-01"
end_date = "2024-01-01"
data = yf.download(ticker, start=start_date, end=end_date)
# Plotting candlestick chart using mplfinance
mpf.plot(data, type='candle', style='yahoo', volume=True, ylabel='Price', ylabel_lower='Volume')
plt.show()
# Calculating Exponential Moving Averages (EMAs)
ema_10 = talib.EMA(data['Close'], timeperiod=10)
ema_30 = talib.EMA(data['Close'], timeperiod=30)
# Implementing EMA crossover strategy
data['EMA_10'] = ema_10
data['EMA_30'] = ema_30
data['Signal'] = 0
for i in range(1, len(data)):
if data['EMA_10'][i] > data['EMA_30'][i] and data['EMA_10'][i-1] <= data['EMA_30'][i-1]:
data['Signal'][i] = 1 # Buy signal
elif data['EMA_10'][i] < data['EMA_30'][i] and data['EMA_10'][i-1] >= data['EMA_30'][i-1]:
data['Signal'][i] = -1 # Sell signal
# Backtesting the strategy
capital = 100000
shares = 0
buy_price = 0
total_trades = 0
win_trades = 0
portfolio_value = []
for i in range(len(data)):
if i == len(data) - 1: # Last day
capital += shares * data['Close'][i]
shares = 0
elif data['Signal'][i] == 1 and capital > 0:
shares = capital / data['Close'][i]
buy_price = data['Close'][i]
capital = 0
total_trades += 1
elif data['Signal'][i] == -1 and shares > 0:
capital = shares * data['Close'][i]
if data['Close'][i] > buy_price:
win_trades += 1
shares = 0
portfolio_value.append(capital if capital > 0 else shares * data['Close'][i])
# Calculate drawdown ratio
peak_value = max(portfolio_value)
trough_value = min(portfolio_value)
drawdown = peak_value - trough_value
drawdown_ratio = drawdown / peak_value
# Printing results
print("Total Trades:", total_trades)
print("Winning Trades:", win_trades)
print("Profit:", capital - 100000)
print("Win Ratio:", win_trades / total_trades if total_trades > 0 else 0)
print("Drawdown Ratio:", drawdown_ratio)
# Plotting capital value over time
plt.figure(figsize=(12, 6))
plt.plot(data.index, portfolio_value, color='blue')
plt.title('Portfolio Value Over Time')
plt.xlabel('Date')
plt.ylabel('Portfolio Value')
plt.grid(True)
plt.show()
Comments
Post a Comment