{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Strategy Analysis with **Pandas TA** and AI/ML\n", "* This is a **Work in Progress** and subject to change!\n", "* Contributions are welcome and accepted!\n", "* Examples below are for **educational purposes only**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Required Packages\n", "##### Uncomment the packages you need to install or are missing" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "#!pip install numpy\n", "#!pip install pandas\n", "#!pip install mplfinance\n", "#!pip install pandas-datareader\n", "#!pip install requests_cache\n", "#!pip install alphaVantage-api" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Populating the interactive namespace from numpy and matplotlib\n", "Numpy v1.18.3\n", "Pandas v1.1.0\n", "mplfinance v0.12.6a3\n", "Pandas TA v0.2.12b\n" ] } ], "source": [ "%pylab inline\n", "import datetime as dt\n", "import random as rnd\n", "from sys import float_info as sflt\n", "\n", "import numpy as np\n", "import pandas as pd\n", "pd.set_option('max_rows', 100)\n", "pd.set_option('max_columns', 20)\n", "\n", "import mplfinance as mpf\n", "\n", "from alphaVantageAPI.alphavantage import AlphaVantage\n", "import pandas_ta as ta\n", "\n", "from watchlist import colors, Watchlist\n", "\n", "print(f\"Numpy v{np.__version__}\")\n", "print(f\"Pandas v{pd.__version__}\")\n", "print(f\"mplfinance v{mpf.__version__}\")\n", "print(f\"Pandas TA v{ta.version}\")\n", "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## MISC Functions" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "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]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Collect some Data" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[!] Loading All: SPY, QQQ, AAPL, TSLA\n", "[i] Loaded['D']: SPY_D.csv\n", "[i] Runtime: 1812.7836 ms (1.8128 s)\n", "[i] Loaded['D']: QQQ_D.csv\n", "[i] Runtime: 1747.0058 ms (1.7470 s)\n", "[i] Loaded['D']: AAPL_D.csv\n", "[i] Runtime: 1105.7967 ms (1.1058 s)\n", "[i] Loaded['D']: TSLA_D.csv\n", "[i] Runtime: 906.7782 ms (0.9068 s)\n" ] } ], "source": [ "tf = \"D\"\n", "tickers = [\"SPY\", \"QQQ\", \"AAPL\", \"TSLA\"]\n", "watch = Watchlist(tickers, tf=tf)\n", "watch.strategy = ta.CommonStrategy\n", "watch.load(tickers, timed=True, analyze=True, verbose=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Select an Asset" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AAPL (5241, 10)\n", "Columns: open, high, low, close, volume, SMA_10, SMA_20, SMA_50, SMA_200, VOL_SMA_20\n" ] } ], "source": [ "ticker = tickers[2]\n", "# watch.data[ticker].ta.constants(True, [0, 0, 0])\n", "print(f\"{ticker} {watch.data[ticker].shape}\\nColumns: {', '.join(list(watch.data[ticker].columns))}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Trim it" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "AAPL (252, 10)\n", "Columns: open, high, low, close, volume, SMA_10, SMA_20, SMA_50, SMA_200, VOL_SMA_20\n" ] } ], "source": [ "duration = \"1y\"\n", "recent = recent_bars(watch.data[ticker], duration)\n", "asset = watch.data[ticker].copy().tail(recent)\n", "print(f\"{ticker} {asset.shape}\\nColumns: {', '.join(list(asset.columns))}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Create a Trend" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "date\n", "2019-08-30 NaN\n", "2019-09-03 NaN\n", "2019-09-04 NaN\n", "2019-09-05 NaN\n", "2019-09-06 NaN\n", " ... \n", "2020-08-24 407.982918\n", "2020-08-25 411.563980\n", "2020-08-26 415.270883\n", "2020-08-27 418.595162\n", "2020-08-28 421.757313\n", "Name: EMA_50, Length: 252, dtype: float64" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Example Long Trends\n", "# long = ta.sma(asset.close, 10) < ta.sma(asset.close, 20) # SMA(10) > SMA(20)\n", "# long = ta.ema(asset.close, 8) > ta.ema(asset.close, 21) # EMA(8) > EMA(21)\n", "long = ta.increasing(ta.ema(asset.close, 50))\n", "# long = ta.macd(asset.close).iloc[:,1] > 0 # MACD Histogram is positive\n", "\n", "asset.ta.ema(length=8, append=True)\n", "asset.ta.ema(length=21, append=True)\n", "asset.ta.ema(length=50, append=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Calculate Trend Returns from the long trend" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
| \n", " | CLTR | \n", "TR_LOGRET | \n", "CLTR_Trends | \n", "CLTR_Trades | \n", "
|---|---|---|---|---|
| date | \n", "\n", " | \n", " | \n", " | \n", " |
| 2020-08-24 | \n", "0.629078 | \n", "0.011889 | \n", "1 | \n", "0 | \n", "
| 2020-08-25 | \n", "0.620840 | \n", "-0.008238 | \n", "1 | \n", "0 | \n", "
| 2020-08-26 | \n", "0.634348 | \n", "0.013507 | \n", "1 | \n", "0 | \n", "
| 2020-08-27 | \n", "0.622321 | \n", "-0.012026 | \n", "1 | \n", "0 | \n", "
| 2020-08-28 | \n", "0.620700 | \n", "-0.001621 | \n", "1 | \n", "0 | \n", "