Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix for NaN values in bbroker data.close[0] #469

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

1D0BE
Copy link

@1D0BE 1D0BE commented Apr 27, 2022

,This fixes the backtest broker displaying NaN for the portfolio value returned by get_value/getvalue, even if there are no positions in the data feeds where the data.close[0] value is NaN.

Practical Example:
One wants to backtest multiple data feeds of different assets over various times.
Backtrader is prefilled with all assets, but cannot invest in stocks that haven't IPOed yet, for example. Nevertheless, the data feed is already loaded.
This problem was also discussed here

Fix:

  • add python standard math dependency for isnan()
  • check for NaN when computing the portfolio value.
  • continue the value calculation loop if the closing price of the asset is NaN, no matter the position. If there is one, its worthless anyways.

Potential loopholes of fix:

  • None is not yet checked for
  • Infinity is not yet checked for.

@1D0BE
Copy link
Author

1D0BE commented Apr 27, 2022

Actually, that was a bit too quick of a fix.
With this fix, NaN is not allowed within the line of values plotted at the end.
This creates then a defaulting to 0 when markets are closed. Leading to the plot to look like this:
image

Not desirable.
I have now fixed it locally by introducing the exception to the exception case, but there has to be a more elegant solution this monstrosity.

Any ideas?

if` math.isnan(data.close[0]) and not all([math.isnan(data.close[0]) for data in datas or self.positions]):
        # position inherently has no value.
        continue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant