Files
pandas-ta/examples/AIExample.ipynb
T

320 KiB

Strategy Analysis with Pandas TA and AI/ML

  • This is a Work in Progress and subject to change!
  • Contributions are welcome and accepted!
  • Examples below are for educational purposes only.
  • 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.

Required Packages

Uncomment the packages you need to install or are missing
In [1]:
#!pip install numpy
#!pip install pandas
#!pip install mplfinance
#!pip install pandas-datareader
#!pip install requests_cache
#!pip install alphaVantage-api # Required for Watchlist
In [2]:
%pylab inline
import datetime as dt
import random as rnd
from sys import float_info as sflt

import numpy as np
import pandas as pd
pd.set_option('max_rows', 100)
pd.set_option('max_columns', 20)

import mplfinance as mpf
import pandas_ta as ta

from watchlist import colors, Watchlist # Is this failing? If so, copy it locally. See above.

print(f"Numpy v{np.__version__}")
print(f"Pandas v{pd.__version__}")
print(f"mplfinance v{mpf.__version__}")
print(f"Pandas TA v{ta.version}")
%matplotlib inline
Populating the interactive namespace from numpy and matplotlib
Numpy v1.19.5
Pandas v1.2.0
mplfinance v0.12.7a4
Pandas TA v0.2.42b0

MISC Functions

In [3]:
def recent_bars(df, tf: str = "1y"):
    # All Data: 0, Last Four Years: 0.25, Last Two Years: 0.5, This Year: 1, Last Half Year: 2, Last Quarter: 4
    yearly_divisor = {"all": 0, "10y": 0.1, "5y": 0.2, "4y": 0.25, "3y": 1./3, "2y": 0.5, "1y": 1, "6mo": 2, "3mo": 4}
    yd = yearly_divisor[tf] if tf in yearly_divisor.keys() else 0
    return int(ta.RATE["TRADING_DAYS_PER_YEAR"] / yd) if yd > 0 else df.shape[0]

Collect some Data

In [4]:
tf = "D"
tickers = ["SPY", "QQQ", "AAPL", "TSLA"]
watch = Watchlist(tickers, tf=tf, timed=True)
watch.strategy = ta.CommonStrategy
watch.load(tickers, analyze=True, verbose=False)
[!] Loading All: SPY, QQQ, AAPL, TSLA
[i] Loaded SPY[D]: SPY_D.csv
[i] Runtime: 464.3660 ms (0.4644 s)
[+] Downloading[av]: QQQ[D]
[i] Runtime: 426.7452 ms (0.4267 s)
[+] Downloading[av]: AAPL[D]
[i] Runtime: 419.3628 ms (0.4194 s)
[+] Downloading[av]: TSLA[D]
[i] Runtime: 419.8107 ms (0.4198 s)

Select an Asset

In [5]:
ticker = tickers[0]
print(f"{ticker} {watch.data[ticker].shape}\nColumns: {', '.join(list(watch.data[ticker].columns))}")
SPY (5358, 10)
Columns: open, high, low, close, volume, SMA_10, SMA_20, SMA_50, SMA_200, VOL_SMA_20

Trim it

In [6]:
duration = "1y"
recent = recent_bars(watch.data[ticker], duration)
asset = watch.data[ticker].copy().tail(recent)

Create a Trend

In [7]:
# Example Long Trends
# long = ta.sma(asset.close, 10) < ta.sma(asset.close, 20) # SMA(10) > SMA(20)
long = ta.ema(asset.close, 8) > ta.ema(asset.close, 21) # EMA(8) > EMA(21)
# long = ta.increasing(ta.ema(asset.close, 50))
# long = ta.macd(asset.close).iloc[:,1] > 0 # MACD Histogram is positive

asset.ta.ema(length=8, append=True)
asset.ta.ema(length=21, append=True)
asset.ta.ema(length=50, append=True)
asset[asset.columns[5:]].tail()
Out [7]:
SMA_10 SMA_20 SMA_50 SMA_200 VOL_SMA_20 EMA_8 EMA_21 EMA_50
date
2021-02-10 383.207 381.9135 374.9464 338.55695 64542395.00 386.458726 381.977892 374.293842
2021-02-11 384.515 382.4595 375.5194 339.08185 64422878.45 387.403454 382.771720 374.937613
2021-02-12 386.772 383.1685 376.0518 339.57900 64453086.30 388.567131 383.668836 375.631824
2021-02-16 388.379 383.9985 376.5620 340.08810 61643706.50 389.396657 384.453487 376.285478
2021-02-17 389.463 384.6855 377.0760 340.63610 61669385.40 390.061845 385.174988 376.917028

Calculate Trend Returns from the long trend

In [8]:
trendy = asset.ta.trend_return(trend=long, cumulative=True, trade_offset=-1, append=True)
trendy.tail() # Third Column is the long trend; binary sequences
Out [8]:
CLTR TR_LOGRET CLTR_Trends CLTR_Trades
date
2021-02-10 0.127048 -0.000436 1 0
2021-02-11 0.128662 0.001614 1 0
2021-02-12 0.133590 0.004928 1 0
2021-02-16 0.132723 -0.000866 1 0
2021-02-17 0.132953 0.000229 1 0

Simple Price Chart

In [9]:
extime = ta.get_time(to_string=True)
chart_ = asset[["close", "EMA_8", "EMA_21", "EMA_50"]]
chart_.plot(figsize=(16, 10), color=colors("BkGrOrRd"), title=f"{ticker} {extime}", grid=True)
Out [9]:
<AxesSubplot:title={'center':'SPY Thursday February 18, 2021, NYSE: 8:49:46, Local: 12:49:46 PST, Day 49/365 (13.0%)'}, xlabel='date'>

Trend Returns and Cumulative Trend Returns

In [10]:
cltr = trendy.iloc[:,0]
tr = trendy.iloc[:,1]

trendy.iloc[:,:2].plot(figsize=(16, 3), color=colors("BkBl"))
cltr.plot(figsize=(16, 3), kind="area", stacked=False, color=colors("SvGy")[0], alpha=0.25, grid=True)
Out [10]:
<AxesSubplot:xlabel='date'>

Total Return

In [11]:
capital = 10000

total_return = cltr.cumsum() * capital
positive_return = total_return[total_return > 0]
negative_return = total_return[total_return <= 0]
trdf = pd.DataFrame({"tr+": positive_return, "tr-": negative_return})
trdf.plot(figsize=(16, 5), color=colors(), kind="area", stacked=False, alpha=0.25, grid=True)
Out [11]:
<AxesSubplot:xlabel='date'>
In [12]:
long_trend = (trendy.iloc[:,-2] > 0).astype(int)
short_trend = (1 - long_trend).astype(int)

long_trend.plot(figsize=(16, 0.85), kind="area", stacked=True, color=colors()[0], alpha=0.25)
short_trend.plot(figsize=(16, 0.85), kind="area", stacked=True, color=colors()[1], alpha=0.25)
Out [12]:
<AxesSubplot:xlabel='date'>

Entries & Exits

In [13]:
entries = (trendy.iloc[:,-1] > 0).astype(int) * asset.close
entries[entries < 0.0001] = np.nan
entries.name = "Entry"


exits = (trendy.iloc[:,-1] < 0).astype(int) * asset.close
exits[exits < 0.0001] = np.nan
exits.name = "Exit"

total_trades = trendy.iloc[:,-1].abs().sum()
print(f"Total Trades: {total_trades}")

all_trades = trendy.iloc[:,-1].copy().fillna(0)
all_trades = all_trades[all_trades != 0]

trades = pd.DataFrame({"Signal": all_trades, entries.name: entries.dropna(), exits.name: exits.dropna()})
trades
Out [13]:
Total Trades: 7
Signal Entry Exit
date
2020-04-09 1 278.20 NaN
2020-06-26 -1 NaN 300.05
2020-06-29 1 304.46 NaN
2020-09-10 -1 NaN 333.89
2020-10-06 1 334.93 NaN
2020-10-27 -1 NaN 338.22
2020-11-04 1 343.54 NaN

Chart Display Strings

In [14]:
first_date, last_date = asset.index[0], asset.index[-1]
f_date = f"{first_date.day_name()} {first_date.month}-{first_date.day}-{first_date.year}"
l_date = f"{last_date.day_name()} {last_date.month}-{last_date.day}-{last_date.year}"
last_ohlcv = f"Last OHLCV: ({asset.iloc[-1].open}, {asset.iloc[-1].high}, {asset.iloc[-1].low}, {asset.iloc[-1].close}, {int(asset.iloc[-1].volume)})"
ptitle = f"\n{ticker} [{tf} for {duration}({recent} bars)] from {f_date} to {l_date}\n{last_ohlcv}\n{extime}"

Trade Chart

In [15]:
# chart = asset["close"] #asset[["close", "SMA_10", "SMA_20", "SMA_50", "SMA_200"]]
# chart = asset[["close", "SMA_10", "SMA_20"]]
chart = asset[["close", "EMA_8", "EMA_21", "EMA_50"]]
chart.plot(figsize=(16, 10), color=colors("BkGrOrRd"), title=ptitle, grid=True)
entries.plot(figsize=(16, 10), color=colors("FcLi")[1], marker="^", markersize=12, alpha=0.8)
exits.plot(figsize=(16, 10), color=colors("FcLi")[0], marker="v", markersize=12, alpha=0.8, grid=True)
Out [15]:
<AxesSubplot:title={'center':'\nSPY [D for 1y(252 bars)] from Wednesday 2-19-2020 to Wednesday 2-17-2021\nLast OHLCV: (390.42, 392.66, 389.33, 392.39, 51746878)\nThursday February 18, 2021, NYSE: 8:49:46, Local: 12:49:46 PST, Day 49/365 (13.0%)'}, xlabel='date'>

AI Analysis

In [ ]: