kernc / backtesting.py

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.
https://kernc.github.io/backtesting.py/
GNU Affero General Public License v3.0
5.04k stars 987 forks source link

Code handling when some of the OHLC value is empty #1080

Open chancsc opened 8 months ago

chancsc commented 8 months ago

Current behaviour, it will throw error (Some OHLC values are missing (NaN)) and program will quit. After modify: The missing OHLC values (NaN) are filled forward using the .fillna(method='ffill') method for 'Open', 'High', 'Low', and 'Close' columns. For the 'Volume' column, missing values are filled with 0. You can adjust this logic based on your specific requirements.

File: kernc/backtesting.py/backtesting/backtesting.py Line no: 1110 - 1113

    # if data[['Open', 'High', 'Low', 'Close']].isnull().values.any():
    #     raise ValueError('Some OHLC values are missing (NaN). '
    #                      'Please strip those lines with `df.dropna()` or '
    #                      'fill them in with `df.interpolate()` or whatever.')

suggest to replace with:

    # Handle missing OHLC values (NaN)
    data[['Open', 'Hight', 'Low', 'Close']] = data[['Open', 'High', 'Low', 'Close']].fillna(method='ffill')
    data['Volume'] = data['Volume'].fillna(0) #Or handle missing vol data appropriately