{ "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.63b0\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.63b0\n", "\n", "Indicators and Utilities [148]:\n", " aberration, accbands, ad, adosc, adx, alligator, alma, amat, ao, aobv, apo, aroon, atr, atrts, bbands, bias, bop, brar, cci, cdl_pattern, cdl_z, cfo, cg, chop, cksp, cmf, cmo, coppock, 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, mama, 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: 210\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: Union[int, numpy.integer] = None, talib: bool = None, presma: bool = None, offset: Union[int, numpy.integer] = None, **kwargs: Optional[dict]) -> pandas.core.series.Series\n", " Exponential Moving Average (EMA)\n", " \n", " The Exponential Moving Average is a more responsive moving average\n", " compared to the Simple Moving Average (SMA). The weights are determined\n", " by alpha which is proportional to it's length. There are several\n", " different methods of calculating EMA. One method uses just the standard\n", " definition of EMA and another uses the SMA to generate the initial value\n", " for the rest of the 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 is True, Returns\n", " the TA Lib version. Default: True\n", " presma (bool, optional): If True, uses SMA for initial value like\n", " TA Lib. 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 412.07 | 1.3000%\n", "\n", "\n", "\n", "==== Price Information =====================================================\n", "Open High Low | Close 423.5900 423.5900 411.2100 | 412.0000\n", "HL2 | HLC3 | OHLC4 | C - OHLC4 418.5400, 416.3600, 418.1675, -6.1675\n", "Change (%) -15.8100 (-3.6956%)\n", "Bid | Ask | Spread 413.35 x 1400 | 413.45 x 4000 | 0.1000\n", "Volume | Market | Avg Vol (10Day) \n", " 145,491,088 | 145,491,088 | 105,112,352 (102,313,060)\n", "\n", "52Wk Range (% from 52Wk Low) 404 - 479.98 : 75.9800 (1.9802%)\n", "SMA 50 | SMA 200 437.1890 | 448.1483\n", "Avg. Return 3Yr | 5Yr 15.2500% | 14.4100%\n", "\n", "==== Dividends / Splits =====================================================\n", "Trailing Annual Dividend Rate | Yield 5.662 | 1.3235%\n", "\n", "\n", "Stock Splits (Last 5 of 118):\n", "Date 2022-03-18 2021-12-17 2021-09-17 2021-06-18 2021-03-19\n", "Ratio 1.366 1.633 1.428 1.376 1.278\n", "[+] yf | SPY(7367, 7): 3189.1786 ms (3.1892 s)\n" ] } ], "source": [ "# Recent Data\n", "ticker = \"BTC-USD\"\n", "ticker = \"SPY\"\n", "df = e.ta.ticker(ticker, kind=\"info\", timed=True)\n", "recent_startdate = df.tail(recent_bars(df)).index[0]\n", "recent_enddate = df.tail(recent_bars(df)).index[-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "From 2021-05-03 00:00:00 to 2022-04-29 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-05-03 | \n", "413.982163 | \n", "414.386841 | \n", "412.245043 | \n", "412.768158 | \n", "68128300 | \n", "0.0 | \n", "0 | \n", "
| 2021-05-04 | \n", "410.665847 | \n", "411.188962 | \n", "406.323003 | \n", "410.221680 | \n", "101591200 | \n", "0.0 | \n", "0 | \n", "
| 2021-05-05 | \n", "411.958809 | \n", "412.205562 | \n", "409.757763 | \n", "410.349976 | \n", "60162200 | \n", "0.0 | \n", "0 | \n", "
| 2021-05-06 | \n", "410.428955 | \n", "413.765058 | \n", "408.306886 | \n", "413.626892 | \n", "74321400 | \n", "0.0 | \n", "0 | \n", "
| 2021-05-07 | \n", "414.436221 | \n", "417.328158 | \n", "413.715692 | \n", "416.637238 | \n", "67733800 | \n", "0.0 | \n", "0 | \n", "