{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "120db895",
   "metadata": {},
   "source": [
    "<div style=\"background-color:#000;\"><img src=\"pqn.png\"></img></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98c6ae8b",
   "metadata": {},
   "source": [
    "This code uses the Kalman Filter to smooth financial time series data and compare it to a simple moving average. It loads historical stock prices for a specified date range and computes the Kalman Filter estimate of the average price. It then plots the Kalman Filter estimate alongside the actual prices and a 30-day moving average. This is useful for financial analysis and modeling to reduce noise and detect underlying trends in stock prices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d864e60",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7c52f92",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pykalman import KalmanFilter\n",
    "from openbb_terminal.sdk import openbb"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fa2307c",
   "metadata": {},
   "source": [
    "Load historical stock prices for LMT between specified start and end dates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "216b4c1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = openbb.stocks.load(\"LMT\", start_date=\"2013-01-01\", end_date=\"2015-01-01\")\n",
    "prices = data[\"Adj Close\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8486b4c",
   "metadata": {},
   "source": [
    "Initialize the Kalman Filter with specified parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a262938f",
   "metadata": {},
   "outputs": [],
   "source": [
    "kf = KalmanFilter(\n",
    "    transition_matrices = [1],\n",
    "    observation_matrices = [1],\n",
    "    initial_state_mean = 0,\n",
    "    initial_state_covariance = 1,\n",
    "    observation_covariance=1,\n",
    "    transition_covariance=0.01\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84830040",
   "metadata": {},
   "source": [
    "Apply Kalman Filter to the price data to estimate the average. The filter smooths the data to reduce noise and detect trends. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "733d4019",
   "metadata": {},
   "outputs": [],
   "source": [
    "state_means, _ = kf.filter(prices.values)\n",
    "state_means = pd.Series(state_means.flatten(), index=prices.index)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3bc4dde",
   "metadata": {},
   "source": [
    "Compute a 30-day rolling mean of the price data for comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b96677e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "mean30 = prices.rolling(window=30).mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cf2307d",
   "metadata": {},
   "source": [
    "Plot the Kalman Filter estimate, actual prices, and 30-day moving average to visualize data smoothing and trend detection"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42c88d04",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(state_means)\n",
    "plt.plot(prices)\n",
    "plt.plot(mean30)\n",
    "plt.title('Kalman filter estimate of average')\n",
    "plt.legend(['Kalman', 'Price', '30-day MA'])\n",
    "plt.xlabel('Day')\n",
    "plt.ylabel('Price')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "726482c3",
   "metadata": {},
   "source": [
    "Plot the last 200 days of Kalman Filter estimate, actual prices, and 30-day moving average for a more detailed view"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71660a32",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(state_means[-200:])\n",
    "plt.plot(prices[-200:])\n",
    "plt.plot(mean30[-200:])\n",
    "plt.title('Kalman filter estimate of average')\n",
    "plt.legend(['Kalman', 'Price', '30-day MA'])\n",
    "plt.xlabel('Day')\n",
    "plt.ylabel('Price')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa717712",
   "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
}
