DEV Community

Prakhar Mishra
Prakhar Mishra

Posted on

Exploring Nifty 50 Stocks: Analyzing Historical Data and Developing a Trading Strategy with Python

In this blog, we will explore how to analyze the stock prices of five Nifty 50 companies using Python and the yfinance library. We’ll cover how to fetch historical stock data, calculate daily percentage changes, and plot moving averages. Finally, we’ll develop a simple trading strategy using moving average crossover and backtest its performance. This post is ideal for beginners in financial analysis and Python enthusiasts.

The Nifty 50 index represents the top 50 companies listed on India's National Stock Exchange (NSE). To conduct our analysis, we used the yfinance Python library to fetch six months' worth of stock data for five major companies: RELIANCE, TCS, INFY, ICICI BANK, and HDFC BANK. Here's how we downloaded the stock data:

import yfinance as yf
stocks = ['RELIANCE.NS', 'TCS.NS', 'INFY.NS', 'ICICIBANK.NS', 'HDFCBANK.NS']
data = {stock: yf.download(stock, period='6mo') for stock in stocks}

Enter fullscreen mode Exit fullscreen mode

The yfinance library allows us to easily access stock market data and extract key metrics such as the closing price, volume, and percentage changes.
We calculated the daily percentage change to observe each stock's daily movements. This gives insight into the stock's volatility over time:

data['Daily_Return'] = data['Close'].pct_change() * 100

Enter fullscreen mode Exit fullscreen mode

Plotting these daily percentage changes provides a visual representation of how each stock fluctuated during the six months.
Moving averages smooth out price data to help identify trends. We calculated the 20-day moving average and compared it with the stock’s closing prices to spot trends.
Below is a plot comparing the moving average with the actual stock prices for each company:

Image description

The moving average crossover strategy is a common method used by traders. It involves comparing a short-term moving average (50-day) with a long-term moving average (200-day). A buy signal is generated when the short-term average crosses above the long-term average, and a sell signal when it crosses below.

Here's how we implemented the strategy in Python:

signals['Short_MA'] = data['Close'].rolling(window=50).mean()
signals['Long_MA'] = data['Close'].rolling(window=200).mean()
signals['Signal'] = np.where(signals['Short_MA'] > signals['Long_MA'], 1, 0)

Enter fullscreen mode Exit fullscreen mode

We backtested this strategy to see how it would perform on historical data.
To assess the performance of our strategy, we backtested it against the historical stock data. We compared the strategy’s returns with a simple buy-and-hold strategy.

signals['Strategy_Return'] = signals['Position'].shift(1) * data['Daily_Return']
cumulative_strategy_return = (1 + signals['Strategy_Return']/100).cumprod()[-1] - 1

Enter fullscreen mode Exit fullscreen mode

The backtest revealed that the moving average crossover strategy outperformed the buy-and-hold approach in this particular case.

Maximum Drawdown measures the largest percentage drop from a stock’s peak to its lowest point. Here’s how we calculated it:


def calculate_max_drawdown(stock_data):
    rolling_max = stock_data.cummax()
    drawdown = (stock_data - rolling_max) / rolling_max
    return drawdown.min()

Enter fullscreen mode Exit fullscreen mode

To further manage risk, we implemented a stop-loss mechanism, exiting the position if the stock price drops by 5%.

Through this analysis, we explored the benefits of using Python for stock market analysis. Our moving average crossover strategy showed promising results, outperforming the buy-and-hold approach for some stocks. Implementing a stop-loss helped reduce potential losses during volatile periods. This analysis highlights the importance of both technical analysis and risk management in trading.

Top comments (0)