Harsh Gupta

I am a Quant Trader

Harsh Gupta

A strong academic background in Engineering, Science, Statistics, and Mathematics with 4+ years of experience as a Full-Time Trader and Investor in equity, commodity, currency, and derivative markets and having a great understanding of technical and fundamental analysis.

Also having a good understanding of quantitative and predictive analysis using Statistics and Machine Learning techniques.

Me

My Professional Skills

Quantitative Analysis 55%
Multi-Asset Trading 75%
Algorithmic Trading 60%
Predictive Analysis 50%

Quantitative Analysis

How to use Quantitative Analysis techniques such as Option Pricing and Portfolio Optimization to assess the market's behaviour, price the instruments, and maximize the returns.

Multi-Asset Trading

How to trade in Equity, Commodity, Crypto, and Derivative markets using Technical and Fundamental Analysis tools such as charts, candles, indicators, oscillators, PE, ROE, etc.

Algo Trading

How to create and backtest Algorithmic Trading Strategies such as trend-following, crossover, arbitrage, etc. using Python and its libraries to generate alpha from the markets.

Predictive Analysis

How to use Predictive Analysis techniques such as Machine Learning, Time Series, and Natural Language Processing to make future predictions about the price and direction of the instruments.

Free Support

Free support to ensure your ongoing success in quantitative trading by providing Email Support, Follow-Up Sessions, Resourse Sharing, etc.

Disclaimer

I am neither a SEBI-registered advisor nor an expert, and this is for educational purposes only. This field is dynamic, evolving, and needs continuous learning.

Search This Blog

  • Which is better Intraday Trading or Swing Trading?

                

    Which is better Intraday Trading or Swing Trading?

     

    It's like asking which is better, T20 cricket or ODI cricket.

     

    It depends on an individual's personality and temperament.

     

    If you can take decisions fast enough to deal with market fluctuations during the day, then go for intraday trading.

     

    If you don't want that kind of pressure and want to play a slow game, then go for swing trading.




    Thank You

    Copyright (c) 2023 Harsh Gupta All Rights Reserved




  • Which indicator works most of the time?

               

    Which indicator works most of the time?



    I have tried almost every indicator in the market, whether it is MACD, RSI, Fibonacci, ATR, ORB, Bollinger Bands, Pivot Points, or anything else.

     

    For me, Price Action works best with the VWAP indicator.

     

    Buy above VWAP, sell below VWAP, and take into consideration the price action.

     

    No recommendation; just sharing personal experience.




    Thank You

    Copyright (c) 2023 Harsh Gupta All Rights Reserved




  • How much capital do I need to start Trading?

               

    How much capital do I need to start Trading?


    There is no exact answer to this question. It depends on the individual and his or her needs.

     

    Let's say you expect 50k monthly from trading markets. Now you can ask, "How much capital do I need to deploy in order to make about 50k from the markets?"

     

    Let's say you can generate 3–4% a month on average. Now you can calculate the required amount of capital.

     

    I hope that would help.




    Thank You

    Copyright (c) 2023 Harsh Gupta All Rights Reserved




  • Real-time RSI Trading Bot of Bitcoin using Talib Library and Binance WebSocket Client

    Real-time RSI Trading Bot of Bitcoin using Talib Library and Binance WebSocket Client


    Automated trading has become increasingly popular in recent years, thanks to advancements in technology and the accessibility of financial markets. A trading bot is an automated trading system that is programmed to execute trades based on a set of predefined rules. In this article, we will build a real-time trading bot using the Binance WebSocket client and the RSI (Relative Strength Index) strategy using Talib in Python.


    Binance is a cryptocurrency exchange that provides a WebSocket API for real-time data streaming. The WebSocket client allows us to subscribe to real-time price and volume data for any cryptocurrency listed on Binance. The RSI strategy is a popular technical analysis tool used by traders to identify overbought and oversold conditions in the market.




    We will follow these steps to build the trading bot:


    Install and Import Talib

    Install and Import Websocket Client

    Import other Libraries

    Connect to Binance Websocket

    Trading Strategy Parameters

    Paper Trading Simulation Function

    Fetch Live Data using Websocket Client

    RSI Strategy Using Ta-lib

    Generate Signal

    Start Trading




    Let's get started.


    Step 1: Install and Import Talib


    Talib (Technical Analysis Library) is a popular library for technical analysis. It provides a wide range of technical indicators, including the RSI (Relative Strength Index). To use Talib, we need to install it using pip and import it in our Python code:


    # Install and Import Talib

    !wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz

    !tar -xzvf ta-lib-0.4.0-src.tar.gz

    %cd ta-lib

    !./configure --prefix=/usr

    !make

    !make install

    !pip install Ta-Lib

    import talib

         



    Step 2: Install and Import WebSocket Client


    The WebSocket protocol allows for real-time communication between a client and a server. In our case, we will use the Binance WebSocket client to fetch real-time price data. We can install the WebSocket client using pip and import it in our Python code:


    # Install and Import Websocket Client

    pip install websocket-client

    import websocket




    Step 3: Import other Libraries


    Next, we will import other libraries that we will use in our trading bot. We will use the time module to introduce delays in our code, and the json module to parse the JSON data received from the WebSocket API.


    # Import other Libraries

    import talib

    import requests

    import pandas as pd

    import numpy as np

    import json

    import ssl

         



    Step 4: Connect to Binance Websocket


    In this step, we will connect to the Binance WebSocket API using the WebSocket client library. We will subscribe to the kline_1m endpoint, which provides 1-minute candlestick data for the Bitcoin/USDT trading pair.


    # Connect to Binance Websocket

    cc= 'btcusd'

    interval = "1m" 

    socket = f"wss://stream.binance.com:9443/ws/{cc}t@kline_{interval}"

         



    Step 5: Trading Strategy Parameters


    In this step, we will define the trading strategy parameters. 


    # Trading Strategy Parameters

    amount=1000000

    money_remaining = 1000000

    portfolio = 0

    investment, closes, highs, lows = [], [], [], []

    buy_price = []

    sell_price = []

    rsi_signal = []

    signal = 0

         



    Step 6: Paper Trading Simulation Function


    Before we start trading with real money, we will first simulate trading using a paper trading function. 


    # Paper Trading Simulation Function

    def buy(allocated_money, price):

        global closes,highs,lows, money_remaining, portfolio, investment, signal

        quantity = allocated_money  / price

        money_remaining -= quantity*price

        portfolio += quantity 

        if investment == []:

          investment.append(allocated_money)

        else:

          investment.append(allocated_money)

          investment[-1] += investment[-2]


    def sell(allocated_money, price):

        global closes,highs,lows, money_remaining, portfolio, investment, signal

        quantity = allocated_money  / price

        money_remaining += quantity*price

        portfolio -= quantity 

        investment.append(-allocated_money)

        investment[-1] += investment[-2]

          

        


    Step 7: Fetch Live Data using Websocket Client


    Next, we will modify the on_message callback function to receive live price data from the WebSocket API and store it in a variable closes. 


    # Fetch Live Data using Websocket Client

    def on_close(ws):

      print("Close")


    def on_message(ws, message):

      global closes,highs,lows, money_remaining, portfolio, investment, signal, position

      json_message = json.loads(message)

      cs = json_message["k"]

      candle_closed, close, high, low = cs["x"], cs["c"],cs["h"],cs["l"]



      if candle_closed:

        closes.append(float(close))

        highs.append(float(high))

        lows.append(float(low))

        last_price = closes[-1]

        print(f'Closes : {closes[-5:]}')




    Step 8: RSI Strategy Using Ta-lib


    We will define our RSI trading strategy using the RSI values that we will generate using Talib.


    # RSI Strategy Using Ta-lib

        rsi = talib.RSI(np.array(closes), timeperiod=3)

        last_rsi=round(rsi[-1],2)

        print(last_rsi)

     

        if (rsi[-1] > 40 and rsi < 40).any():

                  if signal != 1:

                    buy_price.append(closes)

                    sell_price.append(np.nan)

                    signal = 1

                    rsi_signal.append(signal)

                  else:

                    buy_price.append(np.nan)

                    sell_price.append(np.nan)

                    rsi_signal.append(0)

        elif (rsi[-1] < 60 and rsi > 60).any():

                  if signal != -1:

                    buy_price.append(np.nan)

                    sell_price.append(closes)

                    signal = -1

                    rsi_signal.append(signal)

                  else:

                    buy_price.append(np.nan)

                    sell_price.append(np.nan)

                    rsi_signal.append(0)

        else:

                    buy_price.append(np.nan)

                    sell_price.append(np.nan)

                    rsi_signal.append(0)


        print(rsi_signal[-5:])




    Step 9: Generate Signal


    We will generate Trading Signal here.


    # Generate Signal and Trade

        if rsi_signal[-1] == 1:

               buy(250000, last_price)

               print(f'(Bitcoin Bought ="{portfolio}")')

        elif rsi_signal[-1] == -1:

               sell(250000, last_price)

               print(f'(Bitcoin Sold ="{portfolio}")')

        else:

               print("No Trade")



    wsapp = websocket.WebSocketApp(socket, on_message = on_message, on_close = on_close)

         



    Step 10: Start Trading


    Finally, our Real-Time Trading Bot is ready


    # Real Time Trading Bot

    wsapp.run_forever()




    Conclusion


    Here we built a real-time trading bot using the Binance WebSocket client and the RSI strategy using Talib in Python. The trading bot monitors the price of Bitcoin in real-time and executes trades based on the RSI value.


    There are several ways to improve this trading bot. For example, we can add more technical indicators, such as moving averages or MACD, to improve the trading signals. We can also implement a stop-loss and take-profit feature to manage the risk of the trades.





  • Real-Time Trading Bot

                

    Real-Time Trading Bot


    Real-time trading bots are a type of algorithmic trading software that automate trading decisions based on predefined rules or strategies. These bots use advanced mathematical models and artificial intelligence techniques to analyze market data and execute trades in real-time. Real-time trading bots have become increasingly popular among traders and investors, as they offer several advantages such as faster decision-making, reduced emotion-based trading, and the ability to trade around the clock.


    In this article, we will discuss the features and advantages of real-time trading bots and explore the process of developing a real-time trading bot.




    Features of Real-time Trading Bots:


    Real-time trading bots come with several features that enable traders to automate their trading strategies and make real-time decisions. Some of the key features of real-time trading bots are:


    Automated Trading: Real-time trading bots enable traders to automate their trading strategies by executing trades based on predefined rules or strategies.


    Real-time Market Data: Real-time trading bots are equipped with real-time market data feeds that enable traders to make informed trading decisions based on up-to-date market data.


    Backtesting: Real-time trading bots offer backtesting functionality, which enables traders to test their strategies against historical market data and make adjustments as necessary.


    Risk Management: Real-time trading bots come with built-in risk management features that help traders minimize their exposure to market risks.


    Customization: Real-time trading bots can be customized to suit the trader's individual trading style and preferences.





    Advantages of Real-time Trading Bots:


    Real-time trading bots offer several advantages to traders and investors, some of which are:


    Speed: Real-time trading bots can execute trades in milliseconds, making them much faster than human traders.


    Accuracy: Real-time trading bots use advanced mathematical models and artificial intelligence techniques to analyze market data and make trading decisions, which can result in more accurate trading decisions.


    24/7 Trading: Real-time trading bots can trade around the clock, enabling traders to take advantage of opportunities that arise in different time zones.


    Emotion-Free Trading: Real-time trading bots make trading decisions based on predefined rules or strategies, eliminating the impact of emotions on trading decisions.


    Scalability: Real-time trading bots can be scaled to handle large volumes of trades, making them suitable for traders with large portfolios.




    Development of Real-time Trading Bots:


    To develop a real-time trading bot, there are several key steps that need to be taken:


    Define the trading strategy: The first step is to define the trading strategy that the bot will use. This involves identifying the market conditions that the bot will trade in, the types of trades it will make, and the risk management rules it will follow.


    Choose a programming language: The next step is to choose a programming language that is suitable for building a real-time trading bot. Commonly used programming languages for this purpose include Python, Java, and C++.


    Select a trading platform: The trading platform is the software interface that the bot will use to access market data and execute trades. There are many different trading platforms available, and the choice will depend on the specific requirements of the trading bot.


    Connect to the API: Once the trading platform has been chosen, the bot will need to connect to its API (Application Programming Interface) in order to access real-time market data and execute trades.


    Build the trading algorithm: The trading algorithm is the heart of the trading bot. It is the set of rules and conditions that the bot will use to make trading decisions. The algorithm should be carefully designed and tested to ensure that it is effective and profitable.


    Implement risk management rules: Risk management is a critical component of any trading strategy. The bot should be programmed with risk management rules to limit losses and protect capital.


    Backtest the strategy: Before deploying the bot in real-time trading, it is important to backtest the trading strategy using historical market data. This will help to identify any weaknesses in the strategy and fine-tune it for optimal performance.


    Deploy the bot: Once the trading bot has been built and tested, it can be deployed for real-time trading. The bot should be monitored closely to ensure that it is functioning correctly and making profitable trades.


    Overall, developing a real-time trading bot can be a complex and challenging process. However, with the right approach and tools, it is possible to create a highly effective trading bot that can generate consistent profits in the markets.




    Conclusion:


    A real-time trading bot can provide traders with a multitude of benefits, including increased efficiency, accuracy, and speed. By leveraging cutting-edge technologies like artificial intelligence, machine learning, and natural language processing, trading bots can analyze vast amounts of market data and execute trades automatically based on pre-determined rules and strategies. However, it is important to note that building and deploying a trading bot requires significant technical expertise and resources. Traders should carefully evaluate their goals, risk tolerance, and budget before deciding to invest in a trading bot. 


    Additionally, it is crucial to continually monitor and evaluate the bot's performance, and make adjustments as needed to ensure optimal results. With the right approach and tools, a real-time trading bot can be a valuable asset for any trader looking to stay ahead of the curve in today's fast-paced and competitive financial markets.




  • Evaluating Risk And Performance Of Algorithmic Trading Strategy Using Python

                    

    Evaluating Risk And Performance Of Algorithmic Trading Strategy Using Python


    Evaluating Crossover Strategy


    Crossover trading strategies are one of the most commonly used strategies in technical analysis. The basic idea behind these strategies is to identify when a short-term moving average crosses over a long-term moving average, indicating a potential change in trend. This type of trading strategy can be applied to any financial instrument, including stocks, currencies, and commodities.


    In this article, we will explore how to evaluate the risk and performance of a crossover trading strategy using Python. We will start by discussing the basics of crossover strategies, followed by an explanation of how to implement them using Python. Finally, we will explore methods for evaluating the risk and performance of a crossover strategy.




    Crossover Trading Strategies


    Crossover trading strategies involve the use of two or more moving averages, where the shorter-term moving average (MA) crosses over the longer-term MA. The two most common moving averages used in crossover strategies are the 50-day and 200-day moving averages.


    The basic idea behind the strategy is that when the short-term MA crosses above the long-term MA, it is a buy signal, indicating a potential uptrend. Conversely, when the short-term MA crosses below the long-term MA, it is a sell signal, indicating a potential downtrend.




    Implementing Crossover Strategies in Python


    We will use the Python programming language to implement the crossover strategy. We will use the Pandas library to load and manipulate the data and the Matplotlib library to plot the data and results.


    First, we need to load the historical data of the instrument we want to trade. We will use the Yahoo Finance API to load the data.


    import pandas as pd

    import yfinance as yf

    import numpy as np


    symbol = "AAPL"

    start_date = "2010-01-01"

    end_date = "2021-12-31"


    data = yf.download(symbol, start_date, end_date)




    Next, we will create the two moving averages, which will be used to generate the buy and sell signals. We will use the Pandas rolling function to calculate the moving averages.


    data["short_ma"] = data["Close"].rolling(window=50).mean()

    data["long_ma"] = data["Close"].rolling(window=200).mean()




    Once we have the two moving averages, we can generate the buy and sell signals. We will create a new column in the data frame called "signal" and set it to 1 when the short-term MA is above the long-term MA and -1 when the short-term MA is below the long-term MA.


    data["signal"] = 0

    data.loc[data["short_ma"] > data["long_ma"], "signal"] = 1

    data.loc[data["short_ma"] < data["long_ma"], "signal"] = -1




    Finally, we will calculate the returns of the strategy using the signal column we created. We will assume that we buy the instrument when the signal is 1 and sell when the signal is -1.


    data["returns"] = data["signal"].shift(1) * data["Close"].pct_change()

    data["cumulative_returns"] = (1 + data["returns"]).cumprod()




    We can now plot the data and the results using Matplotlib.


    import matplotlib.pyplot as plt


    plt.plot(data["Close"])

    plt.plot(data["short_ma"])

    plt.plot(data["long_ma"])

    plt.legend(["Price", "Short MA", "Long MA"])

    plt.show()


    plt.plot(data["cumulative_returns"])

    plt.show()




    Evaluating Risk and Performance


    There are several metrics we can use to evaluate the risk and performance of a trading strategy. We will use the following metrics:


    Sharpe Ratio: measures the risk-adjusted return of the strategy.

    Maximum Drawdown: measures the largest loss from the highest point in the cumulative returns.

    Win Ratio: measures the percentage of winning trades.

    Average Win and Loss: measures the average gain and loss of each trade.




    To calculate the Sharpe Ratio, we first need to calculate the daily returns of the strategy. We will use the Pandas rolling function to calculate the rolling annualized returns and volatility. We will assume a risk-free rate of 0.


    annualized_returns = data["returns"].mean() * 252

    annualized_volatility = data["returns"].std() * np.sqrt(252)

    sharpe_ratio = (annualized_returns - 0) / annualized_volatility




    To calculate the maximum drawdown, we will use the following function:


    def max_drawdown(returns):

        cum_returns = (1 + returns).cumprod()

        high_water_mark = cum_returns.cummax()

        drawdown = (cum_returns - high_water_mark) / high_water_mark

        max_drawdown = drawdown.min()

        return max_drawdown




    To calculate the win ratio, average win, and average loss, we will use the following functions:


    def win_ratio(returns):

        wins = returns[returns > 0].count()

        losses = returns[returns < 0].count()

        win_ratio = wins / (wins + losses)

        return win_ratio


    def average_win_loss(returns):

        wins = returns[returns > 0]

        losses = returns[returns < 0]

        average_win = wins.mean()

        average_loss = losses.mean()

        return average_win, average_loss




    We can now use these functions to evaluate the risk and performance of the strategy.


    print("Sharpe Ratio:", sharpe_ratio)

    print("Maximum Drawdown:", max_drawdown(data["returns"]))

    print("Win Ratio:", win_ratio(data["returns"]))

    print("Average Win and Loss:", average_win_loss(data["returns"]))




    Complete Code


    import pandas as pd

    import yfinance as yf

    import numpy as np


    symbol = "AAPL"

    start_date = "2010-01-01"

    end_date = "2021-12-31"


    data = yf.download(symbol, start_date, end_date)


    data["short_ma"] = data["Close"].rolling(window=50).mean()

    data["long_ma"] = data["Close"].rolling(window=200).mean()


    data["signal"] = 0

    data.loc[data["short_ma"] > data["long_ma"], "signal"] = 1

    data.loc[data["short_ma"] < data["long_ma"], "signal"] = -1


    data["returns"] = data["signal"].shift(1) * data["Close"].pct_change()

    data["cumulative_returns"] = (1 + data["returns"]).cumprod()


    import matplotlib.pyplot as plt


    plt.plot(data["Close"])

    plt.plot(data["short_ma"])

    plt.plot(data["long_ma"])

    plt.legend(["Price", "Short MA", "Long MA"])

    plt.show()


    plt.plot(data["cumulative_returns"])

    plt.show()


    annualized_returns = data["returns"].mean() * 252

    annualized_volatility = data["returns"].std() * np.sqrt(252)

    sharpe_ratio = (annualized_returns - 0) / annualized_volatility


    def max_drawdown(returns):

        cum_returns = (1 + returns).cumprod()

        high_water_mark = cum_returns.cummax()

        drawdown = (cum_returns - high_water_mark) / high_water_mark

        max_drawdown = drawdown.min()

        return max_drawdown


    def win_ratio(returns):

        wins = returns[returns > 0].count()

        losses = returns[returns < 0].count()

        win_ratio = wins / (wins + losses)

        return win_ratio


    def average_win_loss(returns):

        wins = returns[returns > 0]

        losses = returns[returns < 0]

        average_win = wins.mean()

        average_loss = losses.mean()

        return average_win, average_loss



    print("Sharpe Ratio:", sharpe_ratio)

    print("Maximum Drawdown:", max_drawdown(data["returns"]))

    print("Win Ratio:", win_ratio(data["returns"]))

    print("Average Win and Loss:", average_win_loss(data["returns"]))




    Conclusion


    In this article, we explored how to evaluate the risk and performance of a crossover trading strategy using Python. We started by discussing the basics of crossover strategies, followed by an explanation of how to implement them using Python. Finally, we explored methods for evaluating the risk and performance of a crossover strategy.


    It is important to note that while these metrics are useful for evaluating a trading strategy, they do not guarantee future performance. It is always important to thoroughly backtest and analyze a trading strategy before implementing it with real money.




  • Backtesting Algorithmic Trading Strategy Using Python And Backtrader

                    

    Backtesting Algorithmic Trading Strategy Using Python


    Backtesting Crossover Strategy


    Backtesting is the process of evaluating a trading strategy using historical data to simulate the performance of the strategy in the past. In this article, we will discuss how to backtest a crossover strategy using Python.




    Step 1: Importing Libraries and Loading the Data


    Before we can backtest the crossover strategy, we need to import the necessary libraries and load the data. We will use the pandas library to load the historical data and the backtrader library to create and run the backtest.


    # Import necessary Libraries

    import pandas as pd

    import backtrader as bt


    # Load the data

    data = bt.feeds.YahooFinanceData(dataname='AAPL',

                                     fromdate=datetime(2019, 1, 1),

                                     todate=datetime(2021, 1, 1))


    # Create an instance of the CrossoverStrategy

    crossover_strategy = CrossoverStrategy()


    # Create an instance of the cerebro engine

    cerebro = bt.Cerebro()


    # Add the data to cerebro

    cerebro.adddata(data)


    # Add the strategy to cerebro

    cerebro.addstrategy(crossover_strategy)


    The YahooFinanceData class in backtrader is used to load historical data from Yahoo Finance. We pass the ticker symbol, the start date, and the end date of the data that we want to load. We then create an instance of the CrossoverStrategy class that we defined in the previous article. We also create an instance of the cerebro engine and add the data and the strategy to it.




    Step 2: Defining the Strategy Performance Metrics


    Before we run the backtest, we need to define the performance metrics that we want to track. We can define the performance metrics using the cerebro.addanalyzer() method. In this example, we will track the total return, the Sharpe ratio, and the maximum drawdown.


    # Add the performance metrics

    cerebro.addanalyzer(bt.analyzers.Returns)

    cerebro.addanalyzer(bt.analyzers.SharpeRatio)

    cerebro.addanalyzer(bt.analyzers.DrawDown)




    Step 3: Running the Backtest


    Next, we need to run the backtest using the run() method of the cerebro engine. This will generate the results of the backtest that we can evaluate.


    # Run the backtest

    backtest_results = cerebro.run()




    Step 4: Retrieving the Strategy Performance Metrics


    After running the backtest, we can retrieve the performance metrics using the get_analysis() method of the cerebro engine. We can then print the performance metrics to the console.


    # Retrieve the performance metrics

    total_return = backtest_results[0].analyzers.returns.get_analysis()['rtot']

    sharpe_ratio = backtest_results[0].analyzers.sharperatio.get_analysis()['sharperatio']

    max_drawdown = backtest_results[0].analyzers.drawdown.get_analysis()['max']['drawdown']


    # Print the performance metrics

    print(f"Total return: {total_return:.2%}")

    print(f"Sharpe ratio: {sharpe_ratio:.2f}")

    print(f"Maximum drawdown: {max_drawdown:.2%}")




    Step 5: Visualizing the Backtest Results


    Finally, we can visualize the backtest results using the backtrader.plot module. We can use the plot() function to generate a chart that shows the performance of the strategy over time.


    # Visualize the backtest results

    bt.plot.plot(backtest_results, include_title=False)


    The `plot()` function takes the backtest results and generates a chart that shows the performance of the strategy over time. We can use the `include_title` parameter to hide the title of the chart.




    Complete Code


    Here is the complete code for backtesting a crossover strategy using Python and `backtrader`:


    import pandas as pd

    import backtrader as bt

    from datetime import datetime


    class CrossoverStrategy(bt.Strategy):


        def __init__(self):

            self.sma50 = bt.indicators.SimpleMovingAverage(

                self.data.close, period=50)

            self.sma200 = bt.indicators.SimpleMovingAverage(

                self.data.close, period=200)

            self.crossover = bt.indicators.CrossOver(

                self.sma50, self.sma200)


        def next(self):

            if self.crossover > 0:

                self.buy()

            elif self.crossover < 0:

                self.sell()


    data = bt.feeds.YahooFinanceData(dataname='AAPL',

                                     fromdate=datetime(2019, 1, 1),

                                     todate=datetime(2021, 1, 1))


    crossover_strategy = CrossoverStrategy()


    cerebro = bt.Cerebro()


    cerebro.adddata(data)


    cerebro.addstrategy(crossover_strategy)


    cerebro.addanalyzer(bt.analyzers.Returns)

    cerebro.addanalyzer(bt.analyzers.SharpeRatio)

    cerebro.addanalyzer(bt.analyzers.DrawDown)


    backtest_results = cerebro.run()


    total_return = backtest_results[0].analyzers.returns.get_analysis()['rtot']

    sharpe_ratio = backtest_results[0].analyzers.sharperatio.get_analysis()['sharperatio']

    max_drawdown = backtest_results[0].analyzers.drawdown.get_analysis()['max']['drawdown']


    print(f"Total return: {total_return:.2%}")

    print(f"Sharpe ratio: {sharpe_ratio:.2f}")

    print(f"Maximum drawdown: {max_drawdown:.2%}")


    bt.plot.plot(backtest_results, include_title=False)




    Conclusion


    In this article, we discussed how to backtest a crossover strategy using Python and backtrader. We covered how to import the necessary libraries and load the data, how to define the performance metrics, how to run the backtest, how to retrieve the performance metrics, and how to visualize the backtest results. Backtesting is an essential part of developing and evaluating trading strategies, and Python makes it easy to implement and test different strategies.




  • DO YOU WANT MENTORSHIP?

    ADDRESS

    Delhi, India

    EMAIL

    admin@guptaharsh.in