<jupyter_start><jupyter_text>Pandas TA ([pandas_ta](https://github.com/twopirllc/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_<jupyter_code>%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.

print(f"\nPandas TA v{ta.version}\nTo install the Latest Version:\n$ pip install -U git+https://github.com/twopirllc/pandas-ta\n")
%pylab inline<jupyter_output>Pandas TA v0.2.64b0
To install the Latest Version:
$ pip install -U git+https://github.com/twopirllc/pandas-ta

Populating the interactive namespace from numpy and matplotlib<jupyter_text>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<jupyter_code>AllStrategy = ta.AllStrategy
print("name =", AllStrategy.name)
print("description =", AllStrategy.description)
print("created =", AllStrategy.created)
print("ta =", AllStrategy.ta)<jupyter_output>name = All
description = All the indicators with their default settings. Pandas TA default.
created = Saturday April 10, 2021, NYSE: 5:39:01, Local: 9:39:01 PDT, Day 100/365 (27.0%)
ta = None<jupyter_text>Common<jupyter_code>CommonStrategy = ta.CommonStrategy
print("name =", CommonStrategy.name)
print("description =", CommonStrategy.description)
print("created =", CommonStrategy.created)
print("ta =", CommonStrategy.ta)<jupyter_output>name = Common Price and Volume SMAs
description = Common Price SMAs: 10, 20, 50, 200 and Volume SMA: 20.
created = Saturday April 10, 2021, NYSE: 5:39:01, Local: 9:39:01 PDT, Day 100/365 (27.0%)
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'}]<jupyter_text>Creating Strategies  Simple Strategy A<jupyter_code>custom_a = ta.Strategy(name="A", ta=[{"kind": "sma", "length": 50}, {"kind": "sma", "length": 200}])
custom_a<jupyter_output><empty_output><jupyter_text>Simple Strategy B<jupyter_code>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<jupyter_output><empty_output><jupyter_text>Bad Strategy. (Misspelled Indicator)<jupyter_code># 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<jupyter_output><empty_output><jupyter_text>Strategy Management and Execution with _Watchlist_  Initialize AlphaVantage Data Source<jupyter_code>AV = AlphaVantage(
    api_key="YOUR API KEY", premium=False,
    output_size='full', clean=True,
    export_path=".", export=True
)
AV<jupyter_output><empty_output><jupyter_text>Create Watchlist and set it's 'ds' to AlphaVantage<jupyter_code>data_source = "av" # Default
# data_source = "yahoo"
watch = Watchlist(["SPY", "IWM"], ds_name=data_source, timed=False)<jupyter_output><empty_output><jupyter_text>Info about the Watchlist. Note, the default Strategy is "All"<jupyter_code>watch<jupyter_output><empty_output><jupyter_text>Help about Watchlist<jupyter_code>help(Watchlist)<jupyter_output>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_name: str = 'av', **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: [...]<jupyter_text>Default Strategy is "Common"<jupyter_code># 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)
watch.data
watch.data["SPY"]
watch.load("SPY", plot=True, mas=True)<jupyter_output>[i] Loaded SPY[D]: SPY_D.csv<jupyter_text>Easy to swap Strategies and run them  Running Simple Strategy A<jupyter_code># Load custom_a into Watchlist and verify
watch.strategy = custom_a
# watch.debug = True
watch.strategy
watch.load("IWM")<jupyter_output>[i] Loaded IWM[D]: IWM_D.csv<jupyter_text>Running Simple Strategy B<jupyter_code># Load custom_b into Watchlist and verify
watch.strategy = custom_b
watch.strategy
watch.load("SPY")<jupyter_output>[i] Loaded SPY[D]: SPY_D.csv<jupyter_text>Running Bad Strategy. (Misspelled indicator)<jupyter_code># Load custom_run_failure into Watchlist and verify
watch.strategy = custom_run_failure
watch.strategy
try:
    iwm = watch.load("IWM")
except AttributeError as error:
    print(f"[X] Oops! {error}")<jupyter_output>[i] Loaded IWM[D]: IWM_D.csv
[X] Oops! 'AnalysisIndicators' object has no attribute 'percet_return'<jupyter_text>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<jupyter_code># 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
# Update the Watchlist
watch.strategy = vp_ma_chain_ta
watch.strategy.name
spy = watch.load("SPY")
spy<jupyter_output>[i] Loaded SPY[D]: SPY_D.csv<jupyter_text>MACD BBANDS<jupyter_code># 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
# Update the Watchlist
watch.strategy = macd_bands_ta
watch.strategy.name
spy = watch.load("SPY")
spy<jupyter_output>[i] Loaded SPY[D]: SPY_D.csv<jupyter_text>Comprehensive Strategy  MACD and RSI Momentum with BBANDS and SMAs and Cumulative Log Returns<jupyter_code>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
# Update the Watchlist
watch.strategy = momo_bands_sma_strategy
watch.strategy.name
spy = watch.load("SPY")
# Apply constants to the DataFrame for indicators
spy.ta.constants(True, [0, 30, 70])
spy.tail()<jupyter_output>[i] Loaded SPY[D]: SPY_D.csv<jupyter_text>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.<jupyter_code>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
# Update the Watchlist
watch.strategy = params_ta_strategy
watch.strategy.name
spy = watch.load("SPY")
spy.tail()<jupyter_output>[i] Loaded SPY[D]: SPY_D.csv
{'fraction_non_alphanumeric': 0.1251531429648478, 'fraction_numerical': 0.013853548204693244, 'mean_word_length': 5.682619647355164, 'pattern_counts': {'":': 57, '<': 61, '<?xml version=': 0, '>': 61, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '73683', 'license': 'MIT', 'n_tokens_mistral': 3713, 'n_tokens_neox': 3477, 'n_words': 1092, 'path': 'examples/PandasTA_Strategy_Examples.ipynb', 'repo_name': 'ktaranov/pandas-ta', 'size': '10611'}