Skip to content

Use of talib indicators not producing the expected result. #109

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

Closed
selvanponraj opened this issue Jul 17, 2020 · 5 comments
Closed

Use of talib indicators not producing the expected result. #109

selvanponraj opened this issue Jul 17, 2020 · 5 comments
Labels
duplicate This issue or pull request already exists invalid This is not a (valid) bug report

Comments

@selvanponraj
Copy link

selvanponraj commented Jul 17, 2020

TA lib indicators not producing expected results. Any help on this would be great.

self.ma1 = self.I(SMA, Close, 10)  # Return type is _indicator

self.ma1 = ta.SMA(self.data.Close, timeperiod=10)  # Return type is ndarray.

And also I am using this function and getting the error

        if qtpylib.crossed_above(self.ma1,self.ma2):
            self.buy()
        elif qtpylib.crossed_above(self.ma2,self.ma1):
            self.sell()
File "/Users/vt_qtpylib/lib/python3.7/site-packages/pandas/core/generic.py", line 1479, in __nonzero__
    f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Expected Behavior

self.ma1 = self.I(SMA, Close, 10)
self.ma2 = self.I(SMA, Close, 20)

if crossover(self.ma11,self.ma22):
        self.buy()
elif crossover(self.ma22,self.ma11):
        self.sell()
Start                     2020-04-01 23:00:00
End                       2020-04-30 23:59:00
Duration                     29 days 00:59:00
Exposure [%]                          99.8733
Equity Final [$]                      744.094
Equity Peak [$]                         10000
Return [%]                           -92.5591
Buy & Hold Return [%]                 15.9654
Max. Drawdown [%]                    -92.5934
Avg. Drawdown [%]                    -92.5934
Max. Drawdown Duration       29 days 00:24:00
Avg. Drawdown Duration       29 days 00:24:00
# Trades                                 1155
Win Rate [%]                          13.2468
Best Trade [%]                        2.14186
Worst Trade [%]                      -1.69105
Avg. Trade [%]                      -0.224556
Max. Trade Duration           3 days 01:17:00
Avg. Trade Duration           0 days 00:37:00
Expectancy [%]                       0.305656
SQN                                  -17.5662
Sharpe Ratio                        -0.776904
Sortino Ratio                        -1.29619
Calmar Ratio                      -0.00242518
_strategy                            SmaCross

Actual Behavior

Use of TALib

self.ma1 = ta.SMA(self.data.Close, timeperiod=10)
self.ma2 = ta.SMA(self.data.Close, timeperiod=20)

if crossover(self.ma11,self.ma22):
        self.buy()
elif crossover(self.ma22,self.ma11):
        self.sell()

TALib Produces NAN values.

Start                     2020-04-01 23:00:00
End                       2020-04-30 23:59:00
Duration                     29 days 00:59:00
Exposure [%]                                0
Equity Final [$]                        10000
Equity Peak [$]                         10000
Return [%]                                  0
Buy & Hold Return [%]                 15.9654
Max. Drawdown [%]                          -0
Avg. Drawdown [%]                         NaN
Max. Drawdown Duration                    NaN
Avg. Drawdown Duration                    NaN
# Trades                                    0
Win Rate [%]                              NaN
Best Trade [%]                            NaN
Worst Trade [%]                           NaN
Avg. Trade [%]                            NaN
Max. Trade Duration                       NaT
Avg. Trade Duration                       NaT
Expectancy [%]                            NaN
SQN                                       NaN
Sharpe Ratio                              NaN
Sortino Ratio                             NaN
Calmar Ratio                              NaN
_strategy                            SmaCross
@kernc
Copy link
Owner

kernc commented Jul 17, 2020

File "/Users/vt_qtpylib/lib/python3.7/site-packages/pandas/core/generic.py", line 1479, in __nonzero__
    f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Can you provide a full traceback?

Can you actually provide a full MWE to reproduce the issue?

Strategy.I returning _Indicator instead of np.ndarray should not be an issue as the former is a subtype of the latter:

class _Array(np.ndarray):

class _Indicator(_Array):

@kernc
Copy link
Owner

kernc commented Jul 17, 2020

Actual Behavior

Use of TALib

self.ma1 = ta.SMA(self.data.Close, timeperiod=10)

The only proper way to use talib (or any indicator functions, really) is:

self.ma1 = self.I(ta.SMA, self.data.Close, timeperiod=10)

I.e. lazy evaluation. Just pass the function reference (ta.SMA) to Strategy.I and let it call it.

@selvanponraj
Copy link
Author

selvanponraj commented Jul 18, 2020

Thanks for your help.

Please find the MWE.

from backtesting import Backtest, Strategy
from backtesting.lib import *
from backtesting.test import *
from talib import abstract as ta

class SmaCross(Strategy):

    def init(self):
        # Precompute the two moving averages
        self.sma1 = self.I(SMA, self.data.Close, 10)
        self.sma2 = self.I(SMA, self.data.Close, 20)

        # self.sma1 = self.I(ta.SMA, self.data.Close, timeperiod=10)
        # self.sma2 = self.I(ta.SMA, self.data.Close, timeperiod=20)

    def next(self):
        # If sma1 crosses above sma2, close any existing
        # short trades, and buy the asset
        if crossover(self.sma1, self.sma2):
            self.position.close()
            self.buy()

        # Else, if sma1 crosses below sma2, close any existing
        # long trades, and sell the asset
        elif crossover(self.sma2, self.sma1):
            self.position.close()
            self.sell()

bt = Backtest(GOOG, SmaCross,
              cash=10000, commission=.002)

print(bt.run())
# bt.plot()

Same code using TA Lib throws exception

self.sma1 = self.I(ta.SMA, self.data.Close, timeperiod=10)
self.sma2 = self.I(ta.SMA, self.data.Close, timeperiod=20)
Traceback (most recent call last):
  File "/local/backtesting.py/doc/examples/SmaCross.py", line 33, in <module>
    print(bt.run())
  File "/local/backtesting.py/backtesting/backtesting.py", line 1073, in run
    strategy.init()
  File "/local/backtesting.py/doc/examples/SmaCross.py", line 14, in init
    self.sma1 = self.I(ta.SMA, self.data.Close, timeperiod=10)
  File "/local/backtesting.py/backtesting/backtesting.py", line 122, in I
    func_name = _as_str(func)
  File "/local/backtesting.py/backtesting/_util.py", line 25, in _as_str
    name = value.__name__.replace('<lambda>', 'λ')
AttributeError: 'Function' object has no attribute '__name__'

@kernc
Copy link
Owner

kernc commented Jul 18, 2020

  File "/local/backtesting.py/doc/examples/SmaCross.py", line 14, in init
    self.sma1 = self.I(ta.SMA, self.data.Close, timeperiod=10)
  File "/local/backtesting.py/backtesting/backtesting.py", line 122, in I
    func_name = _as_str(func)
  File "/local/backtesting.py/backtesting/_util.py", line 25, in _as_str
    name = value.__name__.replace('<lambda>', 'λ')
AttributeError: 'Function' object has no attribute '__name__'

This is now a duplicate of issue #93, and a different error from the one quoted in original post? 😕

File "/Users/vt_qtpylib/lib/python3.7/site-packages/pandas/core/generic.py", line 1479, in __nonzero__
    f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

The workaround, besides using yet-unreleased git master, is to instead:

import talib as ta

@selvanponraj
Copy link
Author

Many thanks and workaround works.

@kernc kernc added duplicate This issue or pull request already exists invalid This is not a (valid) bug report labels Jul 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate This issue or pull request already exists invalid This is not a (valid) bug report
Projects
None yet
Development

No branches or pull requests

2 participants