Files
pandas-ta/examples/PandasTA_Strategy_Examples.ipynb
T

87 KiB
Raw Blame History

Pandas TA (pandas_ta) Strategies for Custom Technical Analysis

Topics

  • What is a Pandas TA Strategy?
    • Builtin Strategies: AllStrategy and CommonStrategy
    • Creating Strategies
  • Watchlist Class
    • Strategy Management and Execution
    • NOTE: The watchlist module is independent of Pandas TA. To easily use it, copy it from your local pandas_ta installation directory into your project directory.
  • Indicator Composition/Chaining for more Complex Strategies
    • Comprehensive Example: MACD and RSI Momo with BBANDS and SMAs 50 & 200 and Cumulative Log Returns
In [1]:
%matplotlib inline
import datetime as dt

import pandas as pd
import pandas_ta as ta
from alphaVantageAPI.alphavantage import AlphaVantage  # pip install alphaVantage-api

from watchlist import Watchlist # Is this failing? If so, copy it locally. See above.
%pylab inline
Populating the interactive namespace from numpy and matplotlib

What is a Pandas TA Strategy?

A Strategy is a simple way to name and group your favorite TA indicators. Technically, a Strategy is a simple Data Class to contain list of indicators and their parameters. Note: Strategy is experimental and subject to change. Pandas TA comes with two basic Strategies: AllStrategy and CommonStrategy.

Strategy Requirements:

  • name: Some short memorable string. Note: Case-insensitive "All" is reserved.
  • ta: A list of dicts containing keyword arguments to identify the indicator and the indicator's arguments

Optional Requirements:

  • description: A more detailed description of what the Strategy tries to capture. Default: None
  • created: At datetime string of when it was created. Default: Automatically generated.

Things to note:

  • A Strategy will fail when consumed by Pandas TA if there is no {"kind": "indicator name"} attribute.

Builtin Examples

All

In [2]:
AllStrategy = ta.AllStrategy
print("name =", AllStrategy.name)
print("description =", AllStrategy.description)
print("created =", AllStrategy.created)
print("ta =", AllStrategy.ta)
name = All
description = All the indicators with their default settings. Pandas TA default.
created = 01/23/2021, 12:36:24
ta = None

Common

In [3]:
CommonStrategy = ta.CommonStrategy
print("name =", CommonStrategy.name)
print("description =", CommonStrategy.description)
print("created =", CommonStrategy.created)
print("ta =", CommonStrategy.ta)
name = Common Price and Volume SMAs
description = Common Price SMAs: 10, 20, 50, 200 and Volume SMA: 20.
created = 01/23/2021, 12:36:24
ta = [{'kind': 'sma', 'length': 10}, {'kind': 'sma', 'length': 20}, {'kind': 'sma', 'length': 50}, {'kind': 'sma', 'length': 200}, {'kind': 'sma', 'close': 'volume', 'length': 20, 'prefix': 'VOL'}]
In [ ]:

Creating Strategies

Simple Strategy A

In [4]:
custom_a = ta.Strategy(name="A", ta=[{"kind": "sma", "length": 50}, {"kind": "sma", "length": 200}])
custom_a
Out [4]:
Strategy(name='A', ta=[{'kind': 'sma', 'length': 50}, {'kind': 'sma', 'length': 200}], description='TA Description', created='01/23/2021, 12:36:24')

Simple Strategy B

In [5]:
custom_b = ta.Strategy(name="B", ta=[{"kind": "ema", "length": 8}, {"kind": "ema", "length": 21}, {"kind": "log_return", "cumulative": True}, {"kind": "rsi"}, {"kind": "supertrend"}])
custom_b
Out [5]:
Strategy(name='B', ta=[{'kind': 'ema', 'length': 8}, {'kind': 'ema', 'length': 21}, {'kind': 'log_return', 'cumulative': True}, {'kind': 'rsi'}, {'kind': 'supertrend'}], description='TA Description', created='01/23/2021, 12:36:24')

Bad Strategy. (Misspelled Indicator)

In [6]:
# Misspelled indicator, will fail later when ran with Pandas TA
custom_run_failure = ta.Strategy(name="Runtime Failure", ta=[{"kind": "percet_return"}])
custom_run_failure
Out [6]:
Strategy(name='Runtime Failure', ta=[{'kind': 'percet_return'}], description='TA Description', created='01/23/2021, 12:36:24')
In [ ]:

Strategy Management and Execution with Watchlist

Initialize AlphaVantage Data Source

In [7]:
AV = AlphaVantage(
    api_key="YOUR API KEY", premium=False,
    output_size='full', clean=True,
    export_path=".", export=True
)
AV
Out [7]:
AlphaVantage(
  end_point:str = https://www.alphavantage.co/query,
  api_key:str = YOUR API KEY,
  export:bool = True,
  export_path:str = .,
  output_size:str = full,
  output:str = csv,
  datatype:str = json,
  clean:bool = True,
  proxy:dict = {}
)

Create Watchlist and set it's 'ds' to AlphaVantage

In [8]:
watch = Watchlist(["SPY", "IWM"], timed=False)

Info about the Watchlist. Note, the default Strategy is "All"

In [9]:
watch
Out [9]:
Watch(name='Watch: SPY, IWM', tickers[2]='SPY, IWM', tf='D', strategy[5]='Common Price and Volume SMAs')

Help about Watchlist

In [10]:
help(Watchlist)
Help on class Watchlist in module watchlist:

class Watchlist(builtins.object)
 |  Watchlist(tickers: list, tf: str = None, name: str = None, strategy: pandas_ta.core.Strategy = None, ds: object = None, **kwargs)
 |  
 |  # Watchlist Class (** This is subject to change! **)
 |  A simple Class to load/download financial market data and automatically
 |  apply Technical Analysis indicators with a Pandas TA Strategy.
 |  
 |  Default Strategy: pandas_ta.CommonStrategy
 |  
 |  ## Package Support:
 |  ### Data Source (Default: AlphaVantage)
 |  - AlphaVantage (pip install alphaVantage-api).
 |  - Python Binance (pip install python-binance). # Future Support
 |  - Yahoo Finance (pip install yfinance). # Almost Supported
 |  
 |  # Technical Analysis:
 |  - Pandas TA (pip install pandas_ta)
 |  
 |  ## Required Arguments:
 |  - tickers: A list of strings containing tickers. Example: ["SPY", "AAPL"]
 |  
 |  Methods defined here:
 |  
 |  __init__(self, tickers: list, tf: str = None, name: str = None, strategy: pandas_ta.core.Strategy = None, ds: object = None, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __repr__(self) -> str
 |      Return repr(self).
 |  
 |  indicators(self, *args, **kwargs) -> <built-in function any>
 |      Returns the list of indicators that are available with Pandas Ta.
 |  
 |  load(self, ticker: str = None, tf: str = None, index: str = 'date', drop: list = [], plot: bool = False, **kwargs) -> pandas.core.frame.DataFrame
 |      Loads or Downloads (if a local csv does not exist) the data from the
 |      Data Source. When successful, it returns a Data Frame for the requested
 |      ticker. If no tickers are given, it loads all the tickers.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  data
 |      When not None, it contains a dictionary of DataFrames keyed by ticker. data = {"SPY": pd.DataFrame, ...}
 |  
 |  name
 |      The name of the Watchlist. Default: "Watchlist: {Watchlist.tickers}".
 |  
 |  strategy
 |      Sets a valid Strategy. Default: pandas_ta.CommonStrategy
 |  
 |  tf
 |      Alias for timeframe. Default: 'D'
 |  
 |  tickers
 |      tickers
 |      
 |      If a string, it it converted to a list. Example: "AAPL" -> ["AAPL"]
 |          * Does not accept, comma seperated strings.
 |      If a list, checks if it is a list of strings.
 |  
 |  verbose
 |      Toggle the verbose property. Default: False

Default Strategy is "Common"

In [11]:
# No arguments loads all the tickers and applies the Strategy to each ticker.
# The result can be accessed with Watchlist's 'data' property which returns a 
# dictionary keyed by ticker and DataFrames as values 
watch.load(verbose=True)
[!] Loading All: SPY, IWM
[i] Loaded['D']: SPY_D.csv
[+] Strategy: Common Price and Volume SMAs
[i] Indicator arguments: {'timed': False, 'append': True}
[i] Multiprocessing: 8 of 8 cores.
[i] Total indicators: 5
[i] Columns added: 5
[i] Loaded['D']: IWM_D.csv
[+] Strategy: Common Price and Volume SMAs
[i] Indicator arguments: {'timed': False, 'append': True}
[i] Multiprocessing: 8 of 8 cores.
[i] Total indicators: 5
[i] Columns added: 5
In [12]:
watch.data
Out [12]:
{'SPY':                 open      high       low     close       volume   SMA_10  \
 date                                                                       
 1999-11-01  136.5000  137.0000  135.5625  135.5625    4006500.0      NaN   
 1999-11-02  135.9687  137.2500  134.5937  134.5937    6516900.0      NaN   
 1999-11-03  136.0000  136.3750  135.1250  135.5000    7222300.0      NaN   
 1999-11-04  136.7500  137.3593  135.7656  136.5312    7907500.0      NaN   
 1999-11-05  138.6250  139.1093  136.7812  137.8750    7431500.0      NaN   
 ...              ...       ...       ...       ...          ...      ...   
 2020-09-28  333.2200  334.9600  332.1500  334.1900   64584614.0  331.181   
 2020-09-29  333.9700  334.7700  331.6209  332.3700   51531594.0  330.401   
 2020-09-30  333.0900  338.2900  332.8800  334.8900  104081136.0  330.008   
 2020-10-01  337.6900  338.7400  335.0100  337.0400   88698745.0  330.128   
 2020-10-02  331.7000  337.0126  331.1900  333.8400   89431112.0  330.447   
 
               SMA_20    SMA_50    SMA_200   VOL_SMA_20  
 date                                                    
 1999-11-01       NaN       NaN        NaN          NaN  
 1999-11-02       NaN       NaN        NaN          NaN  
 1999-11-03       NaN       NaN        NaN          NaN  
 1999-11-04       NaN       NaN        NaN          NaN  
 1999-11-05       NaN       NaN        NaN          NaN  
 ...              ...       ...        ...          ...  
 2020-09-28  336.9395  334.8642  310.30500  86281647.00  
 2020-09-29  336.0925  335.0252  310.38120  85553267.55  
 2020-09-30  335.2070  335.2228  310.46905  88007358.10  
 2020-10-01  334.1740  335.4264  310.55675  88965293.60  
 2020-10-02  333.5965  335.6440  310.62810  86036292.75  
 
 [5265 rows x 10 columns],
 'IWM':               open    high      low   close      volume   SMA_10    SMA_20  \
 date                                                                         
 2000-05-26   91.06   91.44   90.630   91.44     37400.0      NaN       NaN   
 2000-05-30   92.75   94.81   92.750   94.81     28800.0      NaN       NaN   
 2000-05-31   95.13   96.38   95.130   95.75     18000.0      NaN       NaN   
 2000-06-01   97.11   97.31   97.110   97.31      3500.0      NaN       NaN   
 2000-06-02  101.70  102.40  101.700  102.40     14700.0      NaN       NaN   
 ...            ...     ...      ...     ...         ...      ...       ...   
 2020-09-28  148.37  150.44  146.404  150.02  17600904.0  149.672  151.4385   
 2020-09-29  149.85  150.28  148.000  149.34  18703037.0  149.269  151.1340   
 2020-09-30  149.90  151.97  148.490  149.79  29073746.0  148.766  150.7630   
 2020-10-01  150.81  152.20  149.490  152.18  25871962.0  148.615  150.4490   
 2020-10-02  149.41  153.58  148.990  152.85  29451992.0  148.571  150.4025   
 
               SMA_50    SMA_200   VOL_SMA_20  
 date                                          
 2000-05-26       NaN        NaN          NaN  
 2000-05-30       NaN        NaN          NaN  
 2000-05-31       NaN        NaN          NaN  
 2000-06-01       NaN        NaN          NaN  
 2000-06-02       NaN        NaN          NaN  
 ...              ...        ...          ...  
 2020-09-28  152.3430  144.94380  24197653.10  
 2020-09-29  152.4106  144.87070  24280229.40  
 2020-09-30  152.4458  144.80300  24951209.50  
 2020-10-01  152.5272  144.74450  25406635.15  
 2020-10-02  152.6190  144.68525  25273355.50  
 
 [5121 rows x 10 columns]}

In [13]:
watch.data["SPY"]
Out [13]:
open high low close volume SMA_10 SMA_20 SMA_50 SMA_200 VOL_SMA_20
date
1999-11-01 136.5000 137.0000 135.5625 135.5625 4006500.0 NaN NaN NaN NaN NaN
1999-11-02 135.9687 137.2500 134.5937 134.5937 6516900.0 NaN NaN NaN NaN NaN
1999-11-03 136.0000 136.3750 135.1250 135.5000 7222300.0 NaN NaN NaN NaN NaN
1999-11-04 136.7500 137.3593 135.7656 136.5312 7907500.0 NaN NaN NaN NaN NaN
1999-11-05 138.6250 139.1093 136.7812 137.8750 7431500.0 NaN NaN NaN NaN NaN
... ... ... ... ... ... ... ... ... ... ...
2020-09-28 333.2200 334.9600 332.1500 334.1900 64584614.0 331.181 336.9395 334.8642 310.30500 86281647.00
2020-09-29 333.9700 334.7700 331.6209 332.3700 51531594.0 330.401 336.0925 335.0252 310.38120 85553267.55
2020-09-30 333.0900 338.2900 332.8800 334.8900 104081136.0 330.008 335.2070 335.2228 310.46905 88007358.10
2020-10-01 337.6900 338.7400 335.0100 337.0400 88698745.0 330.128 334.1740 335.4264 310.55675 88965293.60
2020-10-02 331.7000 337.0126 331.1900 333.8400 89431112.0 330.447 333.5965 335.6440 310.62810 86036292.75

5265 rows × 10 columns

In [ ]:

Easy to swap Strategies and run them

Running Simple Strategy A

In [14]:
# Load custom_a into Watchlist and verify
watch.strategy = custom_a
# watch.debug = True
watch.strategy
Out [14]:
Strategy(name='A', ta=[{'kind': 'sma', 'length': 50}, {'kind': 'sma', 'length': 200}], description='TA Description', created='01/23/2021, 12:36:24')
In [15]:
watch.load("IWM")
Out [15]:
[i] Loaded['D']: IWM_D.csv
open high low close volume SMA_50 SMA_200
date
2000-05-26 91.06 91.44 90.630 91.44 37400.0 NaN NaN
2000-05-30 92.75 94.81 92.750 94.81 28800.0 NaN NaN
2000-05-31 95.13 96.38 95.130 95.75 18000.0 NaN NaN
2000-06-01 97.11 97.31 97.110 97.31 3500.0 NaN NaN
2000-06-02 101.70 102.40 101.700 102.40 14700.0 NaN NaN
... ... ... ... ... ... ... ...
2020-09-28 148.37 150.44 146.404 150.02 17600904.0 152.3430 144.94380
2020-09-29 149.85 150.28 148.000 149.34 18703037.0 152.4106 144.87070
2020-09-30 149.90 151.97 148.490 149.79 29073746.0 152.4458 144.80300
2020-10-01 150.81 152.20 149.490 152.18 25871962.0 152.5272 144.74450
2020-10-02 149.41 153.58 148.990 152.85 29451992.0 152.6190 144.68525

5121 rows × 7 columns

Running Simple Strategy B

In [16]:
# Load custom_b into Watchlist and verify
watch.strategy = custom_b
watch.strategy
Out [16]:
Strategy(name='B', ta=[{'kind': 'ema', 'length': 8}, {'kind': 'ema', 'length': 21}, {'kind': 'log_return', 'cumulative': True}, {'kind': 'rsi'}, {'kind': 'supertrend'}], description='TA Description', created='01/23/2021, 12:36:24')
In [17]:
watch.load("SPY")
Out [17]:
[i] Loaded['D']: SPY_D.csv
open high low close volume EMA_8 EMA_21 CUMLOGRET_1 RSI_14 SUPERT_7_3.0 SUPERTd_7_3.0 SUPERTl_7_3.0 SUPERTs_7_3.0
date
1999-11-01 136.5000 137.0000 135.5625 135.5625 4006500.0 NaN NaN NaN NaN 0.000000 1 NaN NaN
1999-11-02 135.9687 137.2500 134.5937 134.5937 6516900.0 NaN NaN -0.007172 NaN NaN 1 NaN NaN
1999-11-03 136.0000 136.3750 135.1250 135.5000 7222300.0 NaN NaN -0.000461 NaN NaN 1 NaN NaN
1999-11-04 136.7500 137.3593 135.7656 136.5312 7907500.0 NaN NaN 0.007120 NaN NaN 1 NaN NaN
1999-11-05 138.6250 139.1093 136.7812 137.8750 7431500.0 NaN NaN 0.016915 NaN NaN 1 NaN NaN
... ... ... ... ... ... ... ... ... ... ... ... ... ...
2020-09-28 333.2200 334.9600 332.1500 334.1900 64584614.0 330.408828 334.010756 0.902277 49.833349 344.119874 -1 NaN 344.119874
2020-09-29 333.9700 334.7700 331.6209 332.3700 51531594.0 330.844644 333.861596 0.896816 48.051629 344.119874 -1 NaN 344.119874
2020-09-30 333.0900 338.2900 332.8800 334.8900 104081136.0 331.743612 333.955087 0.904369 50.680975 344.119874 -1 NaN 344.119874
2020-10-01 337.6900 338.7400 335.0100 337.0400 88698745.0 332.920587 334.235534 0.910769 52.872627 344.119874 -1 NaN 344.119874
2020-10-02 331.7000 337.0126 331.1900 333.8400 89431112.0 333.124901 334.199576 0.901229 49.357005 344.119874 -1 NaN 344.119874

5265 rows × 13 columns

Running Bad Strategy. (Misspelled indicator)

In [18]:
# Load custom_run_failure into Watchlist and verify
watch.strategy = custom_run_failure
watch.strategy
Out [18]:
Strategy(name='Runtime Failure', ta=[{'kind': 'percet_return'}], description='TA Description', created='01/23/2021, 12:36:24')
In [19]:
try:
    iwm = watch.load("IWM")
except AttributeError as error:
    print(f"[X] Oops! {error}")
[i] Loaded['D']: IWM_D.csv
[X] Oops! 'AnalysisIndicators' object has no attribute 'percet_return'
In [ ]:

Indicator Composition/Chaining

  • When you need an indicator to depend on the value of a prior indicator
  • Utilitze prefix or suffix to help identify unique columns or avoid column name clashes.

Volume MAs and MA chains

In [20]:
# Set EMA's and SMA's 'close' to 'volume' to create Volume MAs, prefix 'volume' MAs with 'VOLUME' so easy to identify the column
# Take a price EMA and apply LINREG from EMA's output
volmas_price_ma_chain = [
    {"kind":"ema", "close": "volume", "length": 10, "prefix": "VOLUME"},
    {"kind":"sma", "close": "volume", "length": 20, "prefix": "VOLUME"},
    {"kind":"ema", "length": 5},
    {"kind":"linreg", "close": "EMA_5", "length": 8, "prefix": "EMA_5"},
]
vp_ma_chain_ta = ta.Strategy("Volume MAs and Price MA chain", volmas_price_ma_chain)
vp_ma_chain_ta
Out [20]:
Strategy(name='Volume MAs and Price MA chain', ta=[{'kind': 'ema', 'close': 'volume', 'length': 10, 'prefix': 'VOLUME'}, {'kind': 'sma', 'close': 'volume', 'length': 20, 'prefix': 'VOLUME'}, {'kind': 'ema', 'length': 5}, {'kind': 'linreg', 'close': 'EMA_5', 'length': 8, 'prefix': 'EMA_5'}], description='TA Description', created='01/23/2021, 12:36:24')
In [21]:
# Update the Watchlist
watch.strategy = vp_ma_chain_ta
watch.strategy.name
Out [21]:
'Volume MAs and Price MA chain'
In [22]:
spy = watch.load("SPY")
spy
Out [22]:
[i] Loaded['D']: SPY_D.csv
open high low close volume VOLUME_EMA_10 VOLUME_SMA_20 EMA_5 EMA_5_LR_8
date
1999-11-01 136.5000 137.0000 135.5625 135.5625 4006500.0 NaN NaN NaN NaN
1999-11-02 135.9687 137.2500 134.5937 134.5937 6516900.0 NaN NaN NaN NaN
1999-11-03 136.0000 136.3750 135.1250 135.5000 7222300.0 NaN NaN NaN NaN
1999-11-04 136.7500 137.3593 135.7656 136.5312 7907500.0 NaN NaN NaN NaN
1999-11-05 138.6250 139.1093 136.7812 137.8750 7431500.0 NaN NaN 136.012480 NaN
... ... ... ... ... ... ... ... ... ...
2020-09-28 333.2200 334.9600 332.1500 334.1900 64584614.0 7.861837e+07 86281647.00 329.781966 327.921896
2020-09-29 333.9700 334.7700 331.6209 332.3700 51531594.0 7.369350e+07 85553267.55 330.644644 328.610232
2020-09-30 333.0900 338.2900 332.8800 334.8900 104081136.0 7.921853e+07 88007358.10 332.059763 329.854718
2020-10-01 337.6900 338.7400 335.0100 337.0400 88698745.0 8.094220e+07 88965293.60 333.719842 331.449495
2020-10-02 331.7000 337.0126 331.1900 333.8400 89431112.0 8.248564e+07 86036292.75 333.759895 332.881012

5265 rows × 9 columns

In [ ]:

MACD BBANDS

In [23]:
# MACD is the initial indicator that BBANDS depends on.
# Set BBANDS's 'close' to MACD's main signal, in this case 'MACD_12_26_9' and add a prefix (or suffix) so it's easier to identify
macd_bands_ta = [
    {"kind":"macd"},
    {"kind":"bbands", "close": "MACD_12_26_9", "length": 20, "prefix": "MACD"}
]
macd_bands_ta = ta.Strategy("MACD BBands", macd_bands_ta, f"BBANDS_{macd_bands_ta[1]['length']} applied to MACD")
macd_bands_ta
Out [23]:
Strategy(name='MACD BBands', ta=[{'kind': 'macd'}, {'kind': 'bbands', 'close': 'MACD_12_26_9', 'length': 20, 'prefix': 'MACD'}], description='BBANDS_20 applied to MACD', created='01/23/2021, 12:36:24')
In [24]:
# Update the Watchlist
watch.strategy = macd_bands_ta
watch.strategy.name
Out [24]:
'MACD BBands'
In [25]:
spy = watch.load("SPY")
spy
Out [25]:
[i] Loaded['D']: SPY_D.csv
open high low close volume MACD_12_26_9 MACDh_12_26_9 MACDs_12_26_9 MACD_BBL_20_2.0 MACD_BBM_20_2.0 MACD_BBU_20_2.0 MACD_BBB_20_2.0
date
1999-11-01 136.5000 137.0000 135.5625 135.5625 4006500.0 NaN NaN NaN NaN NaN NaN NaN
1999-11-02 135.9687 137.2500 134.5937 134.5937 6516900.0 NaN NaN NaN NaN NaN NaN NaN
1999-11-03 136.0000 136.3750 135.1250 135.5000 7222300.0 NaN NaN NaN NaN NaN NaN NaN
1999-11-04 136.7500 137.3593 135.7656 136.5312 7907500.0 NaN NaN NaN NaN NaN NaN NaN
1999-11-05 138.6250 139.1093 136.7812 137.8750 7431500.0 NaN NaN NaN NaN NaN NaN NaN
... ... ... ... ... ... ... ... ... ... ... ... ...
2020-09-28 333.2200 334.9600 332.1500 334.1900 64584614.0 -2.475445 -1.262367 -1.213078 -5.034888 1.888513 8.811913 733.211957
2020-09-29 333.9700 334.7700 331.6209 332.3700 51531594.0 -2.252083 -0.831203 -1.420879 -5.348731 1.450066 8.248862 937.722469
2020-09-30 333.0900 338.2900 332.8800 334.8900 104081136.0 -1.850393 -0.343611 -1.506782 -5.445367 1.019390 7.484147 1268.357614
2020-10-01 337.6900 338.7400 335.0100 337.0400 88698745.0 -1.343082 0.130960 -1.474042 -5.235913 0.587945 6.411803 1981.090096
2020-10-02 331.7000 337.0126 331.1900 333.8400 89431112.0 -1.185581 0.230769 -1.416350 -4.926333 0.197149 5.320631 5197.569576

5265 rows × 12 columns

In [ ]:

Comprehensive Strategy

MACD and RSI Momentum with BBANDS and SMAs and Cumulative Log Returns

In [26]:
momo_bands_sma_ta = [
    {"kind":"sma", "length": 50},
    {"kind":"sma", "length": 200},
    {"kind":"bbands", "length": 20},
    {"kind":"macd"},
    {"kind":"rsi"},
    {"kind":"log_return", "cumulative": True},
    {"kind":"sma", "close": "CUMLOGRET_1", "length": 5, "suffix": "CUMLOGRET"},
]
momo_bands_sma_strategy = ta.Strategy(
    "Momo, Bands and SMAs and Cumulative Log Returns", # name
    momo_bands_sma_ta, # ta
    "MACD and RSI Momo with BBANDS and SMAs 50 & 200 and Cumulative Log Returns" # description
)
momo_bands_sma_strategy
Out [26]:
Strategy(name='Momo, Bands and SMAs and Cumulative Log Returns', ta=[{'kind': 'sma', 'length': 50}, {'kind': 'sma', 'length': 200}, {'kind': 'bbands', 'length': 20}, {'kind': 'macd'}, {'kind': 'rsi'}, {'kind': 'log_return', 'cumulative': True}, {'kind': 'sma', 'close': 'CUMLOGRET_1', 'length': 5, 'suffix': 'CUMLOGRET'}], description='MACD and RSI Momo with BBANDS and SMAs 50 & 200 and Cumulative Log Returns', created='01/23/2021, 12:36:24')
In [27]:
# Update the Watchlist
watch.strategy = momo_bands_sma_strategy
watch.strategy.name
Out [27]:
'Momo, Bands and SMAs and Cumulative Log Returns'
In [28]:
spy = watch.load("SPY")
# Apply constants to the DataFrame for indicators
spy.ta.constants(True, [0, 30, 70])
spy.head()
Out [28]:
[i] Loaded['D']: SPY_D.csv
open high low close volume SMA_50 SMA_200 BBL_20_2.0 BBM_20_2.0 BBU_20_2.0 BBB_20_2.0 MACD_12_26_9 MACDh_12_26_9 MACDs_12_26_9 RSI_14 CUMLOGRET_1 SMA_5_CUMLOGRET 0 30 70
date
1999-11-01 136.5000 137.0000 135.5625 135.5625 4006500.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0 30 70
1999-11-02 135.9687 137.2500 134.5937 134.5937 6516900.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN -0.007172 NaN 0 30 70
1999-11-03 136.0000 136.3750 135.1250 135.5000 7222300.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN -0.000461 NaN 0 30 70
1999-11-04 136.7500 137.3593 135.7656 136.5312 7907500.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.007120 NaN 0 30 70
1999-11-05 138.6250 139.1093 136.7812 137.8750 7431500.0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.016915 NaN 0 30 70
In [ ]:

Additional Strategy Options

The params keyword takes a tuple as a shorthand to the parameter arguments in order.

  • Note: If the indicator arguments change, so will results. Breaking Changes will always be posted on the README.

The col_numbers keyword takes a tuple specifying which column to return if the result is a DataFrame.

In [29]:
params_ta = [
    {"kind":"ema", "params": (10,)},
    # params sets MACD's keyword arguments: fast=9, slow=19, signal=10
    # and returning the 2nd column: histogram
    {"kind":"macd", "params": (9, 19, 10), "col_numbers": (1,)},
    # Selects the Lower and Upper Bands and renames them LB and UB, ignoring the MB
    {"kind":"bbands", "col_numbers": (0,2), "col_names": ("LB", "UB")},
    {"kind":"log_return", "params": (5, False)},
]
params_ta_strategy = ta.Strategy(
    "EMA, MACD History, Outter BBands, Log Returns", # name
    params_ta, # ta
    "EMA, MACD History, BBands(LB, UB), and Log Returns Strategy" # description
)
params_ta_strategy
Out [29]:
Strategy(name='EMA, MACD History, Outter BBands, Log Returns', ta=[{'kind': 'ema', 'params': (10,)}, {'kind': 'macd', 'params': (9, 19, 10), 'col_numbers': (1,)}, {'kind': 'bbands', 'col_numbers': (0, 2), 'col_names': ('LB', 'UB')}, {'kind': 'log_return', 'params': (5, False)}], description='EMA, MACD History, BBands(LB, UB), and Log Returns Strategy', created='01/23/2021, 12:36:24')
In [30]:
# Update the Watchlist
watch.strategy = params_ta_strategy
watch.strategy.name
Out [30]:
'EMA, MACD History, Outter BBands, Log Returns'
In [31]:
spy = watch.load("SPY")
spy.tail()
Out [31]:
[i] Loaded['D']: SPY_D.csv
open high low close volume EMA_10 MACDh_9_19_10 LB UB LOGRET_5
date
2020-09-28 333.22 334.9600 332.1500 334.19 64584614.0 331.135274 -0.761769 318.226448 337.517552 0.021841
2020-09-29 333.97 334.7700 331.6209 332.37 51531594.0 331.359770 -0.249828 317.965316 338.606684 0.006247
2020-09-30 333.09 338.2900 332.8800 334.89 104081136.0 332.001630 0.311580 321.342411 340.129589 0.037265
2020-10-01 337.69 338.7400 335.0100 337.04 88698745.0 332.917697 0.832955 327.202692 339.685308 0.041003
2020-10-02 331.70 337.0126 331.1900 333.84 89431112.0 333.085389 0.854917 331.050371 337.881629 0.015425