Tantalum-Lib

Even if backtrader offers an already high number of inbuilt indicators and developing an indicator is mostly a topic of defining the inputs, outputs and writing the formula in a intelligent manner, some mass privation to use TA-LIB. Some of the reasons:

  • Indicator X is in the library and not in backtrader (the author would gladly accept a quest)

  • TA-LIB behavior is well known and citizenry trust good old things

In order to satisfy each and every gustatory perceptio, Ta-LIB integration is offered.

Requirements

  • Python wrapper for TA-Lib

  • Whatsoever dependencies needed by it (for example numpy)

The instalmen details are on the GitHub secretary

Using ta-lib

As easy as using any of the indicators already collective-in in backtrader. Example of a Simple Moving Average. First the backtrader one:

                            significance              backtrader              as              bt              class              MyStrategy              (              bt              .              Strategy              ):              params              =              ((              'period'              ,              20              ),)              def              __init__              (              self              ):              somebody              .              sma              =              bt              .              indicators              .              SMA              (              person              .              data              ,              period              =              soul              .              p              .              period              )              ...              ...            

Now the ta-lib example:

                            significance              backtrader              as              bt              assort              MyStrategy              (              bt              .              Scheme              ):              params              =              ((              'period'              ,              20              ),)              def              __init__              (              self              ):              self              .              sma              =              bt              .              talib              .              SMA              (              person              .              information              ,              timeperiod              =              person              .              p              .              period of time              )              ...              ...            

Et voilá! Of course the params for the Ta-lib indicators are defined past the library itself and not by backtrader. In this case the SMA in ta-lib takes a parametric quantity onymous timeperiod to defined the size of the operating windowpane.

For indicators that deman much peerless input, for example the Stochastic:

                            signification              backtrader              as              bt              class              MyStrategy              (              bt              .              Scheme              ):              params              =              ((              'period'              ,              20              ),)              def              __init__              (              somebody              ):              self              .              stoc              =              bt              .              talib              .              STOCH              (              self              .              data              .              high              ,              self              .              data              .              crushed              ,              someone              .              data              .              close              ,              fastk_period              =              14              ,              slowk_period              =              3              ,              slowd_period              =              3              )              ...              ...            

Point out how countertenor, low and close have been severally passed. One could forever pass open instead of low (Oregon whatever some other data series) and experiment.

The ta-lib indicator documentation is automatically parsed and added to the backtrader docs. You may also deterrent the ta-lib source code/docs. Or adittionally do:

                            print              (              bt              .              talib              .              SMA              .              __doc__              )            

Which in this case outputs:

                            SMA              ([              input_arrays              ],              [              timeperiod              =              30              ])              Simple              Moving              Moderate              (              Overlap              Studies              )              Inputs              :              price              :              (              any              ndarray              )              Parameters              :              timeperiod              :              30              Outputs              :              real            

Which offers some selective information:

  • Which Input is to be expected (DISREGARD the ``ndarray`` comment because backtrader manages the conversions in the background)

  • Which parameters and which default values

  • Which output lines the indicator in reality offers

Moving Averages and MA_Type

To choose a specific moving average for indicators like bt.talib.STOCH, the canonic ta-lib MA_Type is accesible with backtrader.talib.MA_Type. For example:

                            importation              backtrader              atomic number 3              bt              print              (              'SMA:'              ,              bt              .              talib              .              MA_Type              .              SMA              )              print              (              'T3:'              ,              bt              .              talib              .              MA_Type              .              T3              )            

Plotting ta-lib indicators

Even as with regular usage, there is goose egg special to serve to plot the ta-lib indicators.

Note

Indicators which output a Taper (all those looking for a candlestick pattern) deliver a binary output: either 0 or 100. In order to avoid adding a subplot to the chart, there is an automatic plotting translation to plot them over the data at the point yet in which the pattern was acknowledged.

Examples and comparisons

The following are plots comparing the outputs of some ta-lib indicators against the equivalent built-in indicators in backtrader. To consider:

  • The ta-lib indicators produce a TA_ prefix on the plot. This is specifically through with aside the taste to help the user place which is which

  • Moving Averages (if some deliver the indistinguishable result) will make up plotted ON top of the former existing Moving Average. The 2 indicators cannot be seen singly and the exam is a pass if that's the case.

  • All samples include a CDLDOJI index as a reference

KAMA (Kaufman Moving Medium)

This is the 1st example because IT is the only (from each indicators which the sample directly compare) that has a remainder:

  • The first values of the the samples are not the indistinguishable

  • At some point in time, the values converge and both KAMA implementations have the same behavior.

After having analyzed the ta-lib source code:

  • The implementation in Ta-lib makes a non-industry canonical choice for the 1st values of the KAMA.

    The choice can be seen in the source code quoting from the source code): The yesterday Leontyne Price is used here as the previous KAMA.

backtrader does the usual alternative which is the duplicate as for example the peerless from Stockcharts:

  • KAMA at StockCharts

    Since we pauperism an initial value to start the calculation, the number one KAMA is just a simple moving average

Hence the remainder. Furthermore:

  • The Ta-lib KAMA effectuation doesn't take into account specifying the swift and slow periods for the adjustment of the scalable constant defined by Kaufman.

Sample execution:

              $ ./talibtest.py --plot --ind kama            

Outturn

!image

SMA

              $ ./talibtest.py --plot --ind sma            

Outturn

!image

EMA

              $ ./talibtest.py --plot --ind ema            

Output

!image

Stochastic

              $ ./talibtest.py --plot --ind stoc            

Output

!image

RSI

              $ ./talibtest.py --plot --ind rsi            

Output

!image

MACD

              $ ./talibtest.py --plot --ind macd            

Output

!image

Bollinger Bands

              $ ./talibtest.py --plot --ind bollinger            

Output

!image

AROON

Note that atomic number 73-lib chooses to put the down line first and the colours are inverted when compared with the backtrader built-in indicator.

              $ ./talibtest.py --plot --ind aroon            

Output

!image

Ultimate Oscillator

              $ ./talibtest.py --game --ind crowning            

Output

!image

Trix

              $ ./talibtest.py --plot --ind trix            

Output

!image

ADXR

Here backtrader offers both the ADX and ADXR lines.

              $ ./talibtest.py --plot --ind adxr            

End product

!image

DEMA

              $ ./talibtest.py --plot --ind dema            

Outturn

!image

TEMA

              $ ./talibtest.py --plot --ind tema            

Output signal

!image

PPO

Here backtrader offers not only the ppo seam, but a more traditional macd border on.

              $ ./talibtest.py --plot --ind ppo            

Production

!image

WilliamsR

              $ ./talibtest.py --plot --ind williamsr            

Output

!image

ROC

All indicators show have on the button the indistinguishable shape, simply how to track momentum or rate of change has several definitions

              $ ./talibtest.py --plot --ind roc            

Turnout

!image

Sample Usage

              $ ./talibtest.py --assist usage: talibtest.py [-h] [--data0 DATA0] [--fromdate FROMDATE]                     [--todate TODATE]                     [--ind {sma,ema,stoc,rsi,macd,bollinger,aroon,ultimate,trix,kama,adxr,dema,tema,ppo,williamsr,roc}]                     [--no-doji] [--use-adjacent] [--plot [kwargs]]  Sample for tantalum-lib  optional arguments:   -h, --help            show this assistant message and exit   --data0 DATA0         Data to be read in (default:                         ../../datas/yhoo-1996-2015.txt)   --fromdate FROMDATE   Starting date in YYYY-MM-DD format (default on:                         2005-01-01)   --todate TODATE       Ending go steady in YYYY-Millimeter-Doctor of Divinity arrange (default: 2006-12-31)   --ind {sma,ema,stoc,rsi,macd,bollinger,aroon,ultimate,trix,kama,adxr,dema,tema,ppo,williamsr,roc}                         Which indicator mate to exhibit together (default: sma)   --no-doji             Remove Doji Candle holder convention checker (default on:                         False)   --use-succeeding            Practice next (step aside step) instead of once (spate)                         (default: Fictive)   --plot [kwargs], -p [kwargs]                         Plot the show data applying whatever kwargs passed For                         example (escape the quotes if needed): --plot                         style="taper" (to game candles) (nonremittal: No)            

Sample Cypher

                            from              __future__              import              (              absolute_import              ,              division              ,              print_function              ,              unicode_literals              )              import              argparse              import              datetime              import              backtrader              as              bt              class              TALibStrategy              (              bt              .              Scheme              ):              params              =              ((              'ind'              ,              'sma'              ),              (              'doji'              ,              True              ),)              INDS              =              [              'sma'              ,              'ema'              ,              'stoc'              ,              'rsi'              ,              'macd'              ,              'bollinger'              ,              'aroon'              ,              'ultimate'              ,              'trix'              ,              'Kama'              ,              'adxr'              ,              'dema'              ,              'ppo'              ,              'tema'              ,              'roc'              ,              'williamsr'              ]              def              __init__              (              self              ):              if              self              .              p              .              doji              :              bt              .              talib              .              CDLDOJI              (              self              .              data              .              nonunion              ,              self              .              information              .              high              ,              self              .              information              .              low              ,              ego              .              data              .              close              )              if              someone              .              p              .              ind              ==              'sma'              :              bt              .              talib              .              SMA              (              self              .              data              .              buddy-buddy              ,              timeperiod              =              25              ,              plotname              =              'TA_SMA'              )              bt              .              indicators              .              SMA              (              self              .              data              ,              period              =              25              )              elif              self              .              p              .              ind              ==              'ema'              :              bt              .              talib              .              EMA              (              timeperiod              =              25              ,              plotname              =              'TA_SMA'              )              bt              .              indicators              .              EMA              (              period              =              25              )              elif              someone              .              p              .              ind              ==              'stoc'              :              bt              .              talib              .              STOCH              (              self              .              data              .              high              ,              soul              .              information              .              low              ,              self              .              information              .              close              ,              fastk_period              =              14              ,              slowk_period              =              3              ,              slowd_period              =              3              ,              plotname              =              'TA_STOCH'              )              bt              .              indicators              .              Stochastic              (              self              .              data              )              elif              self              .              p              .              ind              ==              'macd'              :              bt              .              talib              .              MACD              (              self              .              data              ,              plotname              =              'TA_MACD'              )              bt              .              indicators              .              MACD              (              self              .              data              )              bt              .              indicators              .              MACDHisto              (              self              .              information              )              elif              self              .              p              .              ind              ==              'bollinger'              :              bt              .              talib              .              BBANDS              (              individual              .              data              ,              timeperiod              =              25              ,              plotname              =              'TA_BBANDS'              )              bt              .              indicators              .              BollingerBands              (              self              .              information              ,              period              =              25              )              elif              mortal              .              p              .              ind              ==              'rsi'              :              bt              .              talib              .              RSI              (              self              .              data              ,              plotname              =              'TA_RSI'              )              bt              .              indicators              .              RSI              (              individual              .              data              )              elif              self              .              p              .              ind              ==              'aroon'              :              bt              .              talib              .              AROON              (              self              .              information              .              high              ,              self              .              data              .              low              ,              plotname              =              'TA_AROON'              )              bt              .              indicators              .              AroonIndicator              (              someone              .              information              )              elif              self              .              p              .              ind              ==              'ultimate'              :              bt              .              talib              .              ULTOSC              (              mortal              .              data              .              high-stepping              ,              self              .              information              .              low              ,              self              .              information              .              close              ,              plotname              =              'TA_ULTOSC'              )              bt              .              indicators              .              UltimateOscillator              (              self              .              information              )              elif              self              .              p              .              ind              ==              'trix'              :              bt              .              talib              .              TRIX              (              self              .              data              ,              timeperiod              =              25              ,              plotname              =              'TA_TRIX'              )              bt              .              indicators              .              Trix              (              self              .              information              ,              period              =              25              )              elif              individual              .              p              .              ind              ==              'adxr'              :              bt              .              talib              .              ADXR              (              soul              .              data              .              high              ,              soul              .              data              .              low              ,              self              .              information              .              unventilated              ,              plotname              =              'TA_ADXR'              )              bt              .              indicators              .              ADXR              (              self              .              data              )              elif              self              .              p              .              ind              ==              'Kama'              :              bt              .              talib              .              KAMA              (              self              .              information              ,              timeperiod              =              25              ,              plotname              =              'TA_KAMA'              )              bt              .              indicators              .              KAMA              (              self              .              data              ,              period of time              =              25              )              elif              somebody              .              p              .              ind              ==              'dema'              :              bt              .              talib              .              DEMA              (              self              .              data              ,              timeperiod              =              25              ,              plotname              =              'TA_DEMA'              )              bt              .              indicators              .              DEMA              (              self              .              information              ,              period              =              25              )              elif              self              .              p              .              ind              ==              'ppo'              :              bt              .              talib              .              PPO              (              mortal              .              data              ,              plotname              =              'TA_PPO'              )              bt              .              indicators              .              PPO              (              self              .              information              ,              _movav              =              bt              .              indicators              .              SMA              )              elif              soul              .              p              .              ind              ==              'tema'              :              bt              .              talib              .              TEMA              (              someone              .              information              ,              timeperiod              =              25              ,              plotname              =              'TA_TEMA'              )              bt              .              indicators              .              TEMA              (              soul              .              data              ,              menstruum              =              25              )              elif              self              .              p              .              ind              ==              'roc'              :              bt              .              talib              .              ROC              (              self              .              data              ,              timeperiod              =              12              ,              plotname              =              'TA_ROC'              )              bt              .              talib              .              ROCP              (              self              .              data              ,              timeperiod              =              12              ,              plotname              =              'TA_ROCP'              )              bt              .              talib              .              ROCR              (              someone              .              data              ,              timeperiod              =              12              ,              plotname              =              'TA_ROCR'              )              bt              .              talib              .              ROCR100              (              self              .              data              ,              timeperiod              =              12              ,              plotname              =              'TA_ROCR100'              )              bt              .              indicators              .              ROC              (              self              .              data              ,              period              =              12              )              bt              .              indicators              .              Momentum              (              self              .              information              ,              period              =              12              )              bt              .              indicators              .              MomentumOscillator              (              self              .              data              ,              period              =              12              )              elif              self              .              p              .              ind              ==              'williamsr'              :              bt              .              talib              .              WILLR              (              self              .              data              .              high              ,              self              .              data              .              low              ,              somebody              .              information              .              close              ,              plotname              =              'TA_WILLR'              )              bt              .              indicators              .              WilliamsR              (              soul              .              information              )              def              runstrat              (              args              =              None              ):              args              =              parse_args              (              args              )              cerebro              =              bt              .              Cerebro              ()              dkwargs              =              dict              ()              if              args              .              fromdate              :              fromdate              =              datetime              .              datetime              .              strptime              (              args              .              fromdate              ,              '%Y-%m-              %d              '              )              dkwargs              [              'fromdate'              ]              =              fromdate              if              args              .              todate              :              todate              =              datetime              .              datetime              .              strptime              (              args              .              todate              ,              '%Y-%m-              %d              '              )              dkwargs              [              'todate'              ]              =              todate              data0              =              bt              .              feeds              .              YahooFinanceCSVData              (              dataname              =              args              .              data0              ,              **              dkwargs              )              cerebro              .              adddata              (              data0              )              cerebro              .              addstrategy              (              TALibStrategy              ,              ind              =              args              .              ind              ,              doji              =              not              args              .              no_doji              )              cerebro              .              run              (              runcone              =              not              args              .              use_next              ,              stdstats              =              False              )              if              args              .              plot              :              pkwargs              =              dict              (              style              =              'standard candle'              )              if              args              .              plot              is              not              True              :              # evals to Truthful but is not True              npkwargs              =              eval              (              'dict('              +              args              .              plot              +              ')'              )              # args were passed              pkwargs              .              update              (              npkwargs              )              cerebro              .              plot              (              **              pkwargs              )              def              parse_args              (              pargs              =              None              ):              parser              =              argparse              .              ArgumentParser              (              formatter_class              =              argparse              .              ArgumentDefaultsHelpFormatter              ,              verbal description              =              'Sampling for sizer'              )              parser              .              add_argument              (              '--data0'              ,              compulsory              =              False              ,              default              =              '../../datas/yhoo-1996-2015.txt'              ,              help              =              'Information to be read in'              )              parser              .              add_argument              (              '--fromdate'              ,              required              =              False              ,              default              =              '2005-01-01'              ,              help              =              'Starting date in YYYY-MM-DD data format'              )              parser              .              add_argument              (              '--todate'              ,              needed              =              False              ,              default              =              '2006-12-31'              ,              help              =              'Closing date in YYYY-MM-DD format'              )              parser              .              add_argument              (              '--ind'              ,              required              =              False              ,              action              =              'hive away'              ,              default              =              TALibStrategy              .              INDS              [              0              ],              choices              =              TALibStrategy              .              INDS              ,              assist              =              (              'Which indicant pair to show in collaboration'              ))              parser              .              add_argument              (              '--atomic number 102-doji'              ,              required              =              False              ,              process              =              'store_true'              ,              helper              =              (              'Remove Doji CandleStick pattern chequer'              ))              parser              .              add_argument              (              '--wont-next'              ,              required              =              Counterfeit              ,              action              =              'store_true'              ,              help              =              (              'Use next (tread by step) '              'instead of once (batch)'              ))              # Plot options              parser              .              add_argument              (              '--plot'              ,              '-p'              ,              nargs              =              '?'              ,              required              =              False              ,              metavar              =              'kwargs'              ,              const              =              True              ,              service              =              (              'Plot the study information applying any kwargs passed              \n              '              '              \n              '              'For instance (escape the quotes if needed):              \n              '              '              \n              '              '  --game manner="candle" (to plot candles)              \n              '              ))              if              pargs              is              not              No              :              return              parser              .              parse_args              (              pargs              )              return              parser              .              parse_args              ()              if              __name__              ==              '__main__'              :              runstrat              ()