[Python] Python Backtrader RSI ZeroDivisionError: float division by zero

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    import backtrader as bt
    import pandas as pd

    # Load data
    file_path = r'C:\forex\python\data\EURUSD1min-v2.xlsx'
    data = pd.read_excel(file_path)

    # Handle date and time in separate columns
    data['Datetime'] = pd.to_datetime(data['Datetime'], format='%Y.%m.%d. %H:%M')
    data.set_index('Datetime', inplace=True)

    print("Data loaded, total entries:", len(data))

    # Backtrader data format
    class PandasData(bt.feeds.PandasData):
    params = (
    ('datetime', None),
    ('open', '<OPEN>'),
    ('high', '<HIGH>'),
    ('low', '<LOW>'),
    ('close', '<CLOSE>'),
    ('volume', None),
    ('openinterest', None),
    )

    # RSI-based strategy
    class RSIStrategy(bt.Strategy):
    params = (
    ('rsi_period', 14),
    ('rsi_upper', 70),
    ('rsi_lower', 30),
    )

    def __init__(self):
    self.rsi = bt.indicators.RSI_SMA(self.data.close, period=self.params.rsi_period)
    print("RSI indicator initialized.")

    def next(self):
    if len(self.data.close) < self.params.rsi_period:
    print("Not enough data for RSI calculation.")
    return

    current_rsi = self.rsi[0]
    current_close = self.data.close[0]

    if pd.isna(current_rsi) or current_rsi == 0:
    print("Invalid or zero RSI:", current_rsi)
    return

    print(f"Close: {current_close}, RSI: {current_rsi}")

    # Load data into Backtrader
    data_feed = PandasData(dataname=data)
    print("Data converted to Backtrader format.")

    # Create Backtrader cerebro and add strategy
    cerebro = bt.Cerebro()
    cerebro.adddata(data_feed)
    cerebro.addstrategy(RSIStrategy)
    print("Strategy added to Cerebro.")

    # Run the strategy
    cerebro.run()
    print("Execution finished.")


    When the program runs, (AT RSI initialization) it encounters the error message ZeroDivisionError: float division by zero

    The data is correct, beginning with RSI. What can the problem be? I tried many things, debug, log. But the log inside RSI also didn't work, so the problem lies somewhere with RSI.

    Continue reading...

Compartilhe esta Página