Python To Backtest The Custom Trading Strategy

How can I utilize Python to backtest my custom trading strategy with Indian stock data? Can you illustrate with a simple moving average strategy on Nifty50?

1 Like

Certainly! Backtesting trading strategies with Python is quite popular among Indian traders, especially with the availability of historical stock data. Let’s take the simple moving average crossover strategy for Nifty50 as an example.

  1. Set Up & Libraries:

First, install necessary libraries:

Use code

pip install pandas numpy matplotlib

We’ll be using Python’s pandas library for data manipulation and matplotlib for plotting.

  1. Get Historical Data:

You can obtain Nifty50 historical data from NSE’s official site or other stock data providers.

  1. Strategy:

We’ll use a simple crossover strategy: Buy when a short-term moving average (e.g., 50-day) crosses above a long-term moving average (e.g., 200-day) and sell when the opposite happens.

  1. Backtest in Python:

Use code

import pandas as pd

import matplotlib.pyplot as plt

Load data

nifty_data = pd.read_csv(“path_to_your_Nifty50_data.csv”)

nifty_data[‘Date’] = pd.to_datetime(nifty_data[‘Date’])

nifty_data.set_index(‘Date’, inplace=True)

Compute moving averages

nifty_data[‘50_Day_MA’] = nifty_data[‘Close’].rolling(window=50).mean()

nifty_data[‘200_Day_MA’] = nifty_data[‘Close’].rolling(window=200).mean()

Signal generation

nifty_data[‘Signal’] = 0.0

nifty_data.loc[nifty_data[‘50_Day_MA’] > nifty_data[‘200_Day_MA’], ‘Signal’] = 1.0

Calculate returns

nifty_data[‘Log_Return’] = np.log(nifty_data[‘Close’] / nifty_data[‘Close’].shift(1))

nifty_data[‘Strategy_Return’] = nifty_data[‘Signal’].shift(1) * nifty_data[‘Log_Return’]

Plot

plt.figure(figsize=(10,5))

plt.plot(nifty_data[‘Close’], label=‘Nifty50 Close Price’)

plt.plot(nifty_data[‘50_Day_MA’], label=‘50 Day MA’, alpha=0.8)

plt.plot(nifty_data[‘200_Day_MA’], label=‘200 Day MA’, alpha=0.8)

plt.legend()

plt.title(‘Nifty50 Simple Moving Average Strategy’)

plt.show()

Key Takeaways

  1. This code provides a visual representation of the strategy on Nifty50 data.
  2. For more advanced analysis, consider calculating metrics like Sharpe Ratio, Max Drawdown, etc.
  3. Remember, past performance doesn’t guarantee future results. Always be cautious!

You can further optimize this strategy using different window sizes for moving averages.

Consider integrating real-time data APIs for live testing once you’re confident with your backtested results.

Hope this gives you a good starting point. Happy trading (but always with caution)!

(Note: This information is purely for educational purposes. Always consult with a financial advisor before making investment decisions.)

1 Like