mirror of
https://github.com/wassname/pandas-ta.git
synced 2026-07-17 11:31:03 +08:00
325 KiB
325 KiB
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 WatchlistIn [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 inlinePopulating the interactive namespace from numpy and matplotlib Numpy v1.19.2 Pandas v1.1.0 mplfinance v0.12.7a0 Pandas TA v0.2.28b0
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]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['D']: SPY_D.csv [i] Runtime: 845.8352 ms (0.8458 s) [i] Loaded['D']: QQQ_D.csv [i] Runtime: 882.0416 ms (0.8820 s) [i] Loaded['D']: AAPL_D.csv [i] Runtime: 1685.3232 ms (1.6853 s) [i] Loaded['D']: TSLA_D.csv [i] Runtime: 1306.2404 ms (1.3062 s)
In [5]:
ticker = tickers[0]
print(f"{ticker} {watch.data[ticker].shape}\nColumns: {', '.join(list(watch.data[ticker].columns))}")SPY (5265, 10) Columns: open, high, low, close, volume, SMA_10, SMA_20, SMA_50, SMA_200, VOL_SMA_20
In [6]:
duration = "1y"
recent = recent_bars(watch.data[ticker], duration)
asset = watch.data[ticker].copy().tail(recent)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 | ||||||||
| 2020-09-28 | 331.181 | 336.9395 | 334.8642 | 310.30500 | 86281647.00 | 330.408828 | 334.010756 | 331.721246 |
| 2020-09-29 | 330.401 | 336.0925 | 335.0252 | 310.38120 | 85553267.55 | 330.844644 | 333.861596 | 331.746687 |
| 2020-09-30 | 330.008 | 335.2070 | 335.2228 | 310.46905 | 88007358.10 | 331.743612 | 333.955087 | 331.869955 |
| 2020-10-01 | 330.128 | 334.1740 | 335.4264 | 310.55675 | 88965293.60 | 332.920587 | 334.235534 | 332.072702 |
| 2020-10-02 | 330.447 | 333.5965 | 335.6440 | 310.62810 | 86036292.75 | 333.124901 | 334.199576 | 332.142007 |
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 sequencesOut [8]:
| CLTR | TR_LOGRET | CLTR_Trends | CLTR_Trades | |
|---|---|---|---|---|
| date | ||||
| 2020-09-28 | 0.0 | 0.0 | 0 | 0 |
| 2020-09-29 | 0.0 | 0.0 | 0 | 0 |
| 2020-09-30 | 0.0 | 0.0 | 0 | 0 |
| 2020-10-01 | 0.0 | 0.0 | 0 | 0 |
| 2020-10-02 | 0.0 | 0.0 | 0 | 0 |
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 Wednesday December 23, 2020, NYSE: 8:37:29, Local: 12:37:29 PST, Day 358/365 (98.0%)'}, xlabel='date'>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'>
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'>
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()})
tradesOut [13]:
Total Trades: 6
| Signal | Entry | Exit | |
|---|---|---|---|
| date | |||
| 2019-10-31 | 1 | 303.33 | NaN |
| 2020-02-24 | -1 | NaN | 322.42 |
| 2020-04-08 | 1 | 274.03 | NaN |
| 2020-06-26 | -1 | NaN | 300.05 |
| 2020-06-29 | 1 | 304.46 | NaN |
| 2020-09-10 | -1 | NaN | 333.89 |
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}"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 Friday 10-4-2019 to Friday 10-2-2020\nLast OHLCV: (331.7, 337.0126, 331.19, 333.84, 89431112)\nWednesday December 23, 2020, NYSE: 8:37:29, Local: 12:37:29 PST, Day 358/365 (98.0%)'}, xlabel='date'>In [ ]: