{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Technical Analysis with Pandas ([pandas_ta](https://github.com/twopirllc/pandas-ta))\n", "* Below contains examples of simple charts that can be made from pandas_ta indicators\n", "* Examples below are for **educational purposes only**\n", "* **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." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Pandas TA v0.3.32b0\n", "To install the Latest Version:\n", "$ pip install -U git+https://github.com/twopirllc/pandas-ta\n", "\n", "Populating the interactive namespace from numpy and matplotlib\n" ] } ], "source": [ "%matplotlib inline\n", "import datetime as dt\n", "import random as rnd\n", "\n", "from tqdm import tqdm\n", "import numpy as np\n", "import pandas as pd\n", "import mplfinance as mpf\n", "\n", "from alphaVantageAPI.alphavantage import AlphaVantage\n", "import pandas_ta as ta\n", "\n", "from watchlist import colors # Is this failing? If so, copy it locally. See above.\n", "\n", "print(f\"\\nPandas TA v{ta.version}\\nTo install the Latest Version:\\n$ pip install -U git+https://github.com/twopirllc/pandas-ta\\n\")\n", "\n", "%pylab inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List of Indicators (post an [issue](https://github.com/twopirllc/pandas-ta/issues) if the indicator doc needs updating)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Pandas TA - Technical Analysis Indicators - v0.3.32b0\n", "\n", "Indicators and Utilities [152]:\n", " aberration, above, above_value, accbands, ad, adosc, adx, alligator, alma, amat, ao, aobv, apo, aroon, atr, bbands, below, below_value, bias, bop, brar, cci, cdl_pattern, cdl_z, cfo, cg, chop, cksp, cmf, cmo, coppock, cross, cross_value, cti, cube, decay, decreasing, dema, dm, donchian, dpo, ebsw, efi, ema, entropy, eom, er, eri, fisher, fwma, ha, hilo, hl2, hlc3, hma, hwc, hwma, ichimoku, ifisher, increasing, inertia, jma, kama, kc, kdj, kst, kurtosis, kvo, linreg, log_return, long_run, macd, mad, massi, mcgd, median, mfi, midpoint, midprice, mom, natr, nvi, obv, ohlc4, pdist, percent_return, pgo, ppo, psar, psl, pvi, pvo, pvol, pvr, pvt, pwma, qqe, qstick, quantile, reflex, remap, rma, roc, rsi, rsx, rvgi, rvi, short_run, sinwma, skew, slope, sma, smi, smma, squeeze, squeeze_pro, ssf, ssf3, stc, stdev, stoch, stochf, stochrsi, supertrend, swma, t3, td_seq, tema, thermo, tos_stdevall, trendflex, trima, trix, true_range, tsi, tsignals, ttm_trend, ui, uo, variance, vhf, vidya, vortex, vwap, vwma, wb_tsv, wcp, willr, wma, xsignals, zlma, zscore\n", "\n", "Candle Patterns [62]:\n", " 2crows, 3blackcrows, 3inside, 3linestrike, 3outside, 3starsinsouth, 3whitesoldiers, abandonedbaby, advanceblock, belthold, breakaway, closingmarubozu, concealbabyswall, counterattack, darkcloudcover, doji, dojistar, dragonflydoji, engulfing, eveningdojistar, eveningstar, gapsidesidewhite, gravestonedoji, hammer, hangingman, harami, haramicross, highwave, hikkake, hikkakemod, homingpigeon, identical3crows, inneck, inside, invertedhammer, kicking, kickingbylength, ladderbottom, longleggeddoji, longline, marubozu, matchinglow, mathold, morningdojistar, morningstar, onneck, piercing, rickshawman, risefall3methods, separatinglines, shootingstar, shortline, spinningtop, stalledpattern, sticksandwich, takuri, tasukigap, thrusting, tristar, unique3river, upsidegap2crows, xsidegap3methods\n", "\n", "Total Candles, Indicators and Utilities: 214\n" ] } ], "source": [ "e = pd.DataFrame()\n", "e.ta.indicators()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Individual Indicator help" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function ema in module pandas_ta.overlap.ema:\n", "\n", "ema(close: pandas.core.series.Series, length: int = None, talib: bool = None, presma: bool = None, offset: int = None, **kwargs) -> pandas.core.series.Series\n", " Exponential Moving Average (EMA)\n", " \n", " The Exponential Moving Average is a more responsive moving average compared\n", " to the Simple Moving Average (SMA). The weights are determined by alpha\n", " which is proportional to it's length. There are several different methods\n", " of calculating EMA. One method uses just the standard definition of EMA and\n", " another uses the SMA to generate the initial value for the rest of the\n", " calculation.\n", " \n", " Sources:\n", " https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_averages\n", " https://www.investopedia.com/ask/answers/122314/what-exponential-moving-average-ema-formula-and-how-ema-calculated.asp\n", " \n", " Args:\n", " close (pd.Series): Series of 'close's\n", " length (int): It's period. Default: 10\n", " talib (bool): If TA Lib is installed and talib=True, it returns the\n", " TA Lib values. Default: True\n", " presma (bool, optional): If True, uses SMA for initial value like TA Lib.\n", " Default: True\n", " offset (int): How many periods to offset the result. Default: 0\n", " \n", " Kwargs:\n", " adjust (bool, optional): Default: False\n", " fillna (value, optional): pd.DataFrame.fillna(value)\n", " fill_method (value, optional): Type of fill method\n", " \n", " Returns:\n", " pd.Series: New feature generated.\n", "\n" ] } ], "source": [ "help(ta.ema)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def ctitle(indicator_name, ticker=\"SPY\", length=100):\n", " return f\"{ticker}: {indicator_name} from {recent_startdate} to {recent_enddate} ({length})\"\n", "\n", "# # All Data: 0, Last Four Years: 0.25, Last Two Years: 0.5, This Year: 1, Last Half Year: 2, Last Quarter: 3\n", "# yearly_divisor = 1\n", "# recent = int(ta.RATE[\"TRADING_DAYS_PER_YEAR\"] / yearly_divisor) if yearly_divisor > 0 else df.shape[0]\n", "# print(recent)\n", "def recent_bars(df, tf: str = \"1y\"):\n", " # All Data: 0, Last Four Years: 0.25, Last Two Years: 0.5, This Year: 1, Last Half Year: 2, Last Quarter: 4\n", " 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}\n", " yd = yearly_divisor[tf] if tf in yearly_divisor.keys() else 0\n", " return int(ta.RATE[\"TRADING_DAYS_PER_YEAR\"] / yd) if yd > 0 else df.shape[0]\n", "\n", "def ta_ylim(series: pd.Series, percent: float = 0.1):\n", " smin, smax = series.min(), series.max()\n", " if isinstance(percent, float) and 0 <= float(percent) <= 1:\n", " y_min = (1 + percent) * smin if smin < 0 else (1 - percent) * smin\n", " y_max = (1 - percent) * smax if smax < 0 else (1 + percent) * smax\n", " return (y_min, y_max)\n", " return (smin, smax)\n", "\n", "price_size = (16, 8)\n", "ind_size = (16, 3.25)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Load Daily Ticker Data using yfinance and clean it" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# help(e.ta.ticker)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "==== Company Information =====================================================\n", "SPDR S&P 500 ETF Trust(SPDR S&P 500) [SPY]\n", "\n", "==== Market Information =====================================================\n", "Market | Exchange | Symbol | Category US | PCX | SPY | Large Blend\n", "\n", "NAV | Yield 477.53 | 1.3000%\n", "\n", "\n", "\n", "==== Price Information =====================================================\n", "Open High Low | Close 449.5100 449.5100 446.7700 | 448.6000\n", "HL2 | HLC3 | OHLC4 | C - OHLC4 448.8150, 448.7433, 448.9350, -0.3350\n", "Change (%) -0.1000 (-0.0223%)\n", "Bid | Ask | Spread 447.95 x 1200 | 447.97 x 900 | 0.0200\n", "Volume | Market | Avg Vol (10Day) \n", " 44,165,850 | 44,165,850 | 96,052,166 (154,963,580)\n", "\n", "52Wk Range (% from 52Wk Low) 371.88 - 479.98 : 108.1000 (20.6303%)\n", "SMA 50 | SMA 200 460.6408 | 443.3322\n", "Avg. Return 3Yr | 5Yr 24.8800% | 17.5900%\n", "\n", "==== Dividends / Splits =====================================================\n", "Trailing Annual Dividend Rate | Yield 5.563 | 1.2398%\n", "\n", "\n", "Stock Splits (Last 5 of 117):\n", "Date 2021-12-17 2021-09-17 2021-06-18 2021-03-19 2020-12-18\n", "Ratio 1.633 1.428 1.376 1.278 1.58\n", "[+] yf | SPY(7310, 7): 4253.9211 ms (4.2539 s)\n", "SPY(252, 7) from 2021-02-09 00:00:00 to 2022-02-07 00:00:00\n" ] }, { "data": { "text/html": [ "
| \n", " | Open | \n", "High | \n", "Low | \n", "Close | \n", "Volume | \n", "Dividends | \n", "Stock Splits | \n", "
|---|---|---|---|---|---|---|---|
| Date | \n", "\n", " | \n", " | \n", " | \n", " | \n", " | \n", " | \n", " |
| 2021-02-09 | \n", "384.484860 | \n", "385.748051 | \n", "384.050675 | \n", "385.116455 | \n", "35551100 | \n", "0.0 | \n", "0 | \n", "
| 2021-02-10 | \n", "386.961873 | \n", "387.119772 | \n", "382.402652 | \n", "384.948700 | \n", "59154400 | \n", "0.0 | \n", "0 | \n", "
| 2021-02-11 | \n", "386.093431 | \n", "386.537524 | \n", "382.994752 | \n", "385.570404 | \n", "42913300 | \n", "0.0 | \n", "0 | \n", "
| 2021-02-12 | \n", "384.721760 | \n", "387.731627 | \n", "384.642795 | \n", "387.475067 | \n", "50593300 | \n", "0.0 | \n", "0 | \n", "
| 2021-02-16 | \n", "388.777663 | \n", "388.984922 | \n", "386.379636 | \n", "387.139496 | \n", "50972400 | \n", "0.0 | \n", "0 | \n", "