Skip to main content

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

Popular posts from this blog

Stock market: Game of Technicals

Author:-   Shailesh Bhardwaj                   ( Student at NIT Kurukshetra) It’s wisely said in the markets that “ What seems too high and risky to the majority generally goes higher and what seems low and cheap generally goes lower.”  – William O’Neil” I am writing this article, to explain   all my friends how Technical’s play a great role in equity markets, and how do a single candle can changes Trend .How do we all get fooled by behavior of stock. So, with my experience in equity market I have learned that we have to be extra-ordinary, fast and different from the investors/Traders to make big money in Stock Market which I will explain further Now first discuss about what is TECHNICAL ANALYSIS? At the most basic level, technical analysis refers to the use of price charts and other bits of market information to make investment decisions.  Technical analysts try t...

How to draw a trend line?

Trend Lines As technical analysis is built on the assumption that prices trend, the use of  trend lines  is important for both trend identification and confirmation. A trend line is a straight line that connects two or more price points and then extends into the future to act as a line of support or resistance Some Terminology: - Higher highs and  Higher lows:  -  When the peaks and troughs are ascending on a chart, and uptrend can be seen happening. In that uptrend, prices can be seen as higher highs and higher lows. As the uptrend is occurring, prices from the previous period that were seen as highs are even higher than they were before. Lower Highs and  Lower Lows : -  In contrast to overall increase in value that an uptrend indicates, downtrends can be seen with the descending peaks and troughs that a chart shows. Therefore, the change in prices show lower highs and lower lows.  Breakout: - A breakout is when prices pass thr...

How do i make money in Reliance Industry in BTST trade?

I am a very small retail investor.I usually don't take any kind of risk 300-400 rupees daily profit is enough for me rather than loosing thousands. Safe trading is the key to earn.For me,Its all about my strategy and how do I protect my stop loss. Generally I gave preference to fundamentally sound stocks to make their charts.Before making any chart i follow price action of that stock every day. My theory is " Keeping Things Simple ". Below  is the chart of reliance industries that i made before trade. Fig-1 So, How do I make it? I opened a Candlestick chart of Reliance industries and uses two hours candle for making my chart.Looking at the chart I found that From Feb 16,2020 to May 7 , 2020 stock is facing resistance at point A,B,C,D as shown in Fig-1.Then, I drew a resistance line by connecting all four point. I also drew a trend line by connecting Point-1 and Point-2 as shown in Fig-1.I traded on reliance on multiple supports and makes money ...