{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e4414ec2",
   "metadata": {},
   "source": [
    "<div style=\"background-color:#000;\"><img src=\"pqn.png\"></img></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4a34016",
   "metadata": {},
   "source": [
    "This notebook demonstrates the use of technical indicators for stock analysis using OpenBB Terminal and TA-Lib. It loads historical stock prices for Apple (AAPL) and calculates Bollinger Bands (BBANDS), Relative Strength Index (RSI), and Moving Average Convergence Divergence (MACD). The data is then visualized to provide insights into stock price trends and potential trading signals. This analysis is useful for investors and traders to make informed decisions based on technical analysis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4f99d73",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "from talib import RSI, BBANDS, MACD"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "687cacb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "from openbb_terminal.sdk import openbb\n",
    "from openbb_terminal.sdk import TerminalStyle\n",
    "theme = TerminalStyle(\"light\", \"light\", \"light\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55b3ddb4",
   "metadata": {},
   "source": [
    "Load historical stock data for Apple (AAPL) and rename 'Adj Close' to 'close'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a4c3ed2",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = (\n",
    "    openbb\n",
    "    .stocks\n",
    "    .load(\"AAPL\", start_date=\"2020-01-01\")\n",
    "    .rename(columns={\"Adj Close\": \"close\"})\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81eaf1bb",
   "metadata": {},
   "source": [
    "Calculate Bollinger Bands (BBANDS) for the close prices with a 21-day period"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "628c013c",
   "metadata": {},
   "outputs": [],
   "source": [
    "up, mid, low = BBANDS(\n",
    "    data.close, \n",
    "    timeperiod=21, \n",
    "    nbdevup=2, \n",
    "    nbdevdn=2, \n",
    "    matype=0\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71e64502",
   "metadata": {},
   "source": [
    "Calculate Relative Strength Index (RSI) for the close prices with a 14-day period"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "efb493b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "rsi = RSI(data.close, timeperiod=14)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "410dd7f1",
   "metadata": {},
   "source": [
    "Calculate Moving Average Convergence Divergence (MACD) for the close prices with standard parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9857261",
   "metadata": {},
   "outputs": [],
   "source": [
    "macd, macdsignal, macdhist = MACD(\n",
    "    data.close, \n",
    "    fastperiod=12, \n",
    "    slowperiod=26, \n",
    "    signalperiod=9\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12793fb1",
   "metadata": {},
   "source": [
    "Create a DataFrame for the MACD components"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66d2556b",
   "metadata": {},
   "outputs": [],
   "source": [
    "macd = pd.DataFrame(\n",
    "    {\n",
    "        \"MACD\": macd,\n",
    "        \"MACD Signal\": macdsignal,\n",
    "        \"MACD History\": macdhist,\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f55ee6a",
   "metadata": {},
   "source": [
    "Create a DataFrame for the stock data and technical indicators"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "500d00d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = pd.DataFrame(\n",
    "    {\n",
    "        \"AAPL\": data.close,\n",
    "        \"BB Up\": up,\n",
    "        \"BB Mid\": mid,\n",
    "        \"BB down\": low,\n",
    "        \"RSI\": rsi,\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdb7f597",
   "metadata": {},
   "source": [
    "Plot the Bollinger Bands, RSI, and MACD indicators in subplots"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adfa1169",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(\n",
    "    nrows=3,\n",
    "    figsize=(15, 10),\n",
    "    sharex=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01d1b071",
   "metadata": {},
   "source": [
    "Plot Bollinger Bands and close prices"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6de6ec6d",
   "metadata": {},
   "outputs": [],
   "source": [
    "data.drop([\"RSI\"], axis=1).plot(\n",
    "    ax=axes[0],\n",
    "    lw=1,\n",
    "    title=\"BBANDS\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97855af1",
   "metadata": {},
   "source": [
    "Plot RSI and add horizontal lines at 70 and 30 to indicate overbought and oversold levels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17fc3747",
   "metadata": {},
   "outputs": [],
   "source": [
    "data[\"RSI\"].plot(\n",
    "    ax=axes[1],\n",
    "    lw=1,\n",
    "    title=\"RSI\"\n",
    ")\n",
    "axes[1].axhline(70, lw=1, ls=\"--\", c=\"k\")\n",
    "axes[1].axhline(30, lw=1, ls=\"--\", c=\"k\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5153654b",
   "metadata": {},
   "source": [
    "Plot MACD components"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8ae01fba",
   "metadata": {},
   "outputs": [],
   "source": [
    "macd.plot(\n",
    "    ax=axes[2],\n",
    "    lw=1,\n",
    "    title=\"MACD\",\n",
    "    rot=0\n",
    ")\n",
    "axes[2].set_xlabel(\"\")\n",
    "fig.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab373866",
   "metadata": {},
   "source": [
    "<a href=\"https://pyquantnews.com/\">PyQuant News</a> is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to <a href=\"https://gettingstartedwithpythonforquantfinance.com/\">get started with Python for quant finance</a>. For educational purposes. Not investment advise. Use at your own risk."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
