Python Backtrader RSI ZeroDivisionError: float division by zero

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import backtrader as bt
import pandas as pd
# Load data
file_path = r'C:forexpythondataEURUSD1min-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.")
</code>
<code>import backtrader as bt import pandas as pd # Load data file_path = r'C:forexpythondataEURUSD1min-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.") </code>
import backtrader as bt
import pandas as pd

# Load data
file_path = r'C:forexpythondataEURUSD1min-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.

New contributor

Puma U is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật