Indian Stocks Forum - Share Market Discussions
Example using the Backtrader library in Python for backtesting purpose - Printable Version

+- Indian Stocks Forum - Share Market Discussions (https://www.indianstocksforum.com)
+-- Forum: ISF Discussions (https://www.indianstocksforum.com/forum-8.html)
+--- Forum: Strategies and Indicators (https://www.indianstocksforum.com/forum-13.html)
+--- Thread: Example using the Backtrader library in Python for backtesting purpose (/thread-501.html)



Example using the Backtrader library in Python for backtesting purpose - Sapna Mukherjee - 12-11-2023

Code:
import backtrader as bt

class VolatilityBreakoutStrategy(bt.Strategy):
    params = (
        ("volatility_threshold", 1.5),  # Adjust based on historical volatility
        ("stop_loss", 0.02),
        ("take_profit", 0.04),
    )

    def __init__(self):
        self.volatility_threshold = self.params.volatility_threshold
        self.stop_loss = self.params.stop_loss
        self.take_profit = self.params.take_profit

        self.atr = bt.indicators.AverageTrueRange(self.data, period=14)

    def next(self):
        if self.atr[-1] < self.volatility_threshold * self.atr[-14]:
            # Volatility is low, potential breakout
            if self.data.close > self.data.close[-1]:
                # Buy signal (long)
                self.buy()
        elif self.position:
            # Check for stop-loss or take-profit conditions
            self.sell()

if __name__ == "__main__":
    cerebro = bt.Cerebro()

    data = bt.feeds.YahooFinanceData(dataname="AAPL", fromdate=datetime(2022, 1, 1), todate=datetime(2023, 1, 1))
    cerebro.adddata(data)

    cerebro.addstrategy(VolatilityBreakoutStrategy)
    cerebro.run()
    cerebro.plot(style="candlestick")
volatility breakout strategy simplified example using the Backtrader library in Python for backtesting purposes