{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Import Python packages\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import macrosynergy\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import polars as pl\n",
    "import os\n",
    "import time\n",
    "\n",
    "from macrosynergy.panel import view_timelines\n",
    "from macrosynergy.management.types import QuantamentalDataFrame\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Import Python bindings - `msyrs`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import msyrs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "DATA_FOLDER_PATH = \"E:/Work/jpmaqs-data\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "nb_start_time = time.time()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "cids_dm = \"AUD.CAD.CHF.EUR.GBP.JPY.NOK.NZD.SEK.USD\".split(\".\")\n",
    "cids_em = \"CLP.COP.CZK.HUF.IDR.ILS.INR.KRW.MXN.PLN.THB.TRY.TWD.ZAR\".split(\".\")\n",
    "cids = cids_dm + cids_em\n",
    "cids_dux = list(set(cids) - set([\"IDR\", \"NZD\"]))\n",
    "\n",
    "\n",
    "xcats =  \"EQXR_NSA.EQXR_VT10.FXXR_NSA.FXXR_VT10.FXCRR_NSA.FXTARGETED_NSA.FXUNTRADABLE_NSA\".split(\n",
    "    \".\"\n",
    ")\n",
    "\n",
    "tickers = [f\"{c}_{x}\" for c in cids for x in xcats]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "sel_cids = [\"USD\", \"EUR\", \"GBP\", \"AUD\", \"CAD\"]\n",
    "tickers = [f\"{c}_{x}\" for c in sel_cids for x in xcats]\n",
    "start = \"1990-01-01\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time taken to load qdf batch: 0.7572264671325684\n"
     ]
    }
   ],
   "source": [
    "starttime = time.time()\n",
    "\n",
    "new_df: pl.DataFrame = msyrs.qdf.load_qdf_from_download_bank(\n",
    "    folder_path=DATA_FOLDER_PATH, tickers=tickers\n",
    ")\n",
    "print(f\"Time taken to load qdf batch: {time.time() - starttime}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time taken: 0.34043407440185547\n",
      "Time taken:  0.0\n"
     ]
    }
   ],
   "source": [
    "# df: polars::prelude::DataFrame,\n",
    "# xcat: String,\n",
    "# cids: Option<Vec<String>>,\n",
    "# lback_periods: Option<usize>,\n",
    "# lback_method: Option<String>,\n",
    "# half_life: Option<f64>,\n",
    "# start: Option<String>,\n",
    "# end: Option<String>,\n",
    "# est_freq: Option<String>,\n",
    "# remove_zeros: Option<bool>,\n",
    "# postfix: Option<String>,\n",
    "# nan_tolerance: Option<f64>,\n",
    "\n",
    "starttime = time.time()\n",
    "hv = msyrs.panel.historic_vol(\n",
    "    df=new_df,\n",
    "    xcat=\"EQXR_NSA\",\n",
    "    cids=None,\n",
    "    lback_periods=21,\n",
    "    lback_method=\"xma\",\n",
    "    half_life=11,\n",
    "    start=None,\n",
    "    end=None,\n",
    "    est_freq=\"D\",\n",
    "    remove_zeros=None,\n",
    "    postfix=\"_HV_RS\",\n",
    "    nan_tolerance=None,\n",
    ")\n",
    "print(f\"Time taken: {time.time() - starttime}\")\n",
    "\n",
    "starttime = time.time()\n",
    "a = 1 + 5\n",
    "print(\"Time taken: \", time.time() - starttime)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 154412 characters]",
      "text/plain": [
       "<Figure size 2075.09x855 with 5 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "hdf = hv.to_pandas()\n",
    "\n",
    "hdf = QuantamentalDataFrame.from_wide(\n",
    "    (\n",
    "        \n",
    "        QuantamentalDataFrame(hdf)\n",
    "        .to_wide()\n",
    "        .reindex(\n",
    "            pd.bdate_range(\n",
    "                start=hdf[\"real_date\"].min(),\n",
    "                end=hdf[\"real_date\"].max(),\n",
    "                freq=\"B\",\n",
    "            ),\n",
    "            method=\"ffill\",\n",
    "        )\n",
    "        .dropna(axis=\"rows\", how=\"all\")\n",
    "    ).sort_index(),\n",
    "    categorical=False,\n",
    ")\n",
    "\n",
    "view_timelines(df=hdf)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time taken: 14.346926927566528\n",
      "Time taken:  0.0\n"
     ]
    }
   ],
   "source": [
    "from macrosynergy.panel.historic_vol import historic_vol\n",
    "\n",
    "new_df_pd = QuantamentalDataFrame(\n",
    "    new_df.to_pandas(), categorical=False\n",
    ")\n",
    "cids = new_df_pd['cid'].unique().tolist()\n",
    "\n",
    "starttime = time.time()\n",
    "hv_bench = historic_vol(\n",
    "    df=new_df_pd,\n",
    "    xcat='EQXR_NSA',\n",
    "    cids=cids,\n",
    "    lback_periods=21,\n",
    "    lback_meth=\"xma\",\n",
    "    half_life=11,\n",
    "    est_freq=\"D\",\n",
    "    blacklist=None,\n",
    "    remove_zeros=True,\n",
    "    postfix=\"_HV_PY\",\n",
    "    nan_tolerance=0.001,\n",
    ")\n",
    "print(f\"Time taken: {time.time() - starttime}\")\n",
    "\n",
    "starttime = time.time()\n",
    "a = 1 + 5\n",
    "print(\"Time taken: \", time.time() - starttime)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 156104 characters]",
      "text/plain": [
       "<Figure size 2075.09x855 with 5 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "view_timelines(df=hv_bench)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 155000 characters]",
      "text/plain": [
       "<Figure size 2075.09x855 with 5 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "hv_bench = hv_bench.dropna(axis=\"rows\", how=\"any\").reset_index(drop=True)\n",
    "bdr = pd.bdate_range(new_df_pd.real_date.min(), new_df_pd.real_date.max())\n",
    "hv_bench = QuantamentalDataFrame.from_wide(\n",
    "    QuantamentalDataFrame(hv_bench).to_wide().reindex(bdr, method=\"ffill\"),\n",
    "    categorical=False,\n",
    ").reset_index(drop=True)\n",
    "\n",
    "view_timelines(df=hv_bench)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 445652 characters]",
      "text/plain": [
       "<Figure size 2075.09x855 with 5 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def zscore_series(s: pd.Series) -> pd.Series:\n",
    "    return (s - s.mean()) / s.std()\n",
    "\n",
    "\n",
    "a = QuantamentalDataFrame.from_wide(\n",
    "    QuantamentalDataFrame(hv_bench)\n",
    "    .to_wide()\n",
    "    .apply(lambda x: zscore_series(x), axis=1, result_type=\"expand\")\n",
    ")\n",
    "\n",
    "b = QuantamentalDataFrame.from_wide(\n",
    "    QuantamentalDataFrame(hdf)\n",
    "    .to_wide()\n",
    "    .apply(lambda x: zscore_series(x), axis=1, result_type=\"expand\")\n",
    ")\n",
    "\n",
    "view_timelines(QuantamentalDataFrame.from_qdf_list([a, b]).dropna(axis=\"rows\", how=\"any\").reset_index(drop=True))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 191552 characters]",
      "text/plain": [
       "<Figure size 2075.09x855 with 5 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# a = QuantamentalDataFrame(hv_bench).to_wide().apply(lambda x: zscore_series(x), axis=1, result_type=\"expand\").rename(columns=lambda x: '_'.join(x.split(\"_\")[:-1]))\n",
    "\n",
    "# b = QuantamentalDataFrame(hdf).to_wide().apply(lambda x: zscore_series(x), axis=1, result_type=\"expand\").rename(columns=lambda x: '_'.join(x.split(\"_\")[:-1]))\n",
    "\n",
    "a = QuantamentalDataFrame(hv_bench).to_wide().rename(columns=lambda x: '_'.join(x.split(\"_\")[:-1]))\n",
    "\n",
    "b = QuantamentalDataFrame(hdf).to_wide().rename(columns=lambda x: '_'.join(x.split(\"_\")[:-1]))\n",
    "\n",
    "diff = (a.abs() - b.abs()).abs() / (a.abs())\n",
    "\n",
    "view_timelines(QuantamentalDataFrame.from_wide(diff))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time taken: 19.609023094177246 seconds\n"
     ]
    }
   ],
   "source": [
    "end_time = time.time()\n",
    "print(f\"Time taken: {end_time - nb_start_time} seconds\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
