Skip to content

RuntimeWarning: Degrees of freedom <= 0 for slice #1251

Closed
@Goon83

Description

@Goon83

Expected behavior

from multiprocessing import Process, freeze_support, set_start_method
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.test import SMA, GOOG

class SmaCross(Strategy):
    ma1_period = 10  # Default values
    ma2_period = 20

    def init(self):
        price = self.data.Close
        self.ma1 = self.I(SMA, price, self.ma1_period)
        self.ma2 = self.I(SMA, price, self.ma2_period)

    def next(self):
        if crossover(self.ma1, self.ma2):
            self.buy()
        elif crossover(self.ma2, self.ma1):
            self.position.close()

if __name__ == "__main__":
    freeze_support()
    bt = Backtest(GOOG, SmaCross, cash=10000000000000)

    # Optimize `ma1_period` and `ma2_period` in the range [5, 50] with step of 5
    stats = bt.optimize(
        ma1_period=range(5, 50, 5),
        ma2_period=range(5, 50, 5),  # Ensure ma2_period range makes sense in the context
        maximize='Sharpe Ratio',  # Optimize for best Sharpe ratio
    )

    bt.plot()
    print(stats)

Error happens at _stats.py:161:

if (len(equity_log_returns) == 0):
        print(len(equity_log_returns), len(market_log_returns))
        print(np.any(np.isnan(equity_log_returns)), np.any(np.isnan(market_log_returns)))
        print(np.any(np.isinf(equity_log_returns)), np.any(np.isinf(market_log_returns)))
        cov_matrix = np.cov(equity_log_returns, market_log_returns)

Errors info

0 0
False False
False False
.venv/lib/python3.13/site-packages/numpy/lib/_function_base_impl.py:552: RuntimeWarning: Mean of empty slice.
  avg = a.mean(axis, **keepdims_kw)
.venv/lib/python3.13/site-packages/numpy/_core/_methods.py:137: RuntimeWarning: invalid value encountered in divide
  ret = um.true_divide(
.venv/lib/python3.13/site-packages/backtesting/_stats.py:161: RuntimeWarning: Degrees of freedom <= 0 for slice
  cov_matrix = np.cov(equity_log_returns, market_log_returns)
.venv/lib/python3.13/site-packages/numpy/lib/_function_base_impl.py:2894: RuntimeWarning: divide by zero encountered in divide
  c *= np.true_divide(1, fact)
.venv/lib/python3.13/site-packages/numpy/lib/_function_base_impl.py:2894: RuntimeWarning: invalid value encountered in multiply
  c *= np.true_divide(1, fact)

Code sample

Actual behavior

eroor

Additional info, steps to reproduce, full crash traceback, screenshots

No response

Software versions

  • Backtesting version: 0.?.?
  • bokeh.__version__:
  • OS:

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions