{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "!pip install -Uqq nixtla cryptocmd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide \n",
    "from nixtla.utils import in_colab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide \n",
    "IN_COLAB = in_colab()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "if not IN_COLAB:\n",
    "    from nixtla.utils import colab_badge\n",
    "    from dotenv import load_dotenv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Bitcoin price prediction\n",
    "\n",
    "> Learn how to use TimeGPT for financial time series forecasting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction \n",
    "\n",
    "Forecasting time series is a ubiquitous task in finance, supporting decisions in trading, risk management, and strategic planning. Despite its prevalence, predicting the future prices of financial assets remains a formidable challenge, mainly due to the inherent volatility of financial markets.\n",
    "\n",
    "For those who believe in the feasibility of forecasting these assets, or for professionals whose roles require such predictions, TimeGPT is a powerful tool that simplifies the forecasting process.\n",
    "\n",
    "In this tutorial, we will demonstrate how to use TimeGPT for financial time series forecasting, focusing on Bitcoin price prediction. We will also showcase how to use TimeGPT for uncertainty quantification, which is essential for risk management and decision-making.\n",
    "\n",
    "**Outline:** \n",
    "\n",
    "1. [Load Bitcoin Price Data](#load-bitcoin-price-data) \n",
    "\n",
    "2. [Get Started with TimeGPT](#get-started-with-timegpt)\n",
    "\n",
    "3. [Visualize the Data](#visualize-the-data)\n",
    "\n",
    "4. [Forecast with TimeGPT](#forecast-with-timegpt) \n",
    "\n",
    "5. [Extend Bitcon Price Analysis with TimeGPT](#extend-bitcoin-price-analysis-with-timegpt)\n",
    "\n",
    "6. [Understand the Model's Limitations](#understand-the-models-limitations)\n",
    "\n",
    "7. [References and Additional Material](#references-and-additional-material) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "[![](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Nixtla/nixtla/blob/main/nbs/docs/use-cases/2_bitcoin_price_prediction.ipynb)"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#| echo: false\n",
    "if not IN_COLAB:\n",
    "    load_dotenv()\n",
    "    colab_badge('docs/use-cases/2_bitcoin_price_prediction')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Load Bitcoin Price Data "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Bitcoin (₿) is the first decentralized digital currency and is one of the most popular cryptocurrencies. Transactions are managed and recorded on a public ledger known as the blockchain. Bitcoins are created as a reward for mining, a process that involves solving complex cryptographic tasks to verify transactions. This digital currency can be used as payment for goods and services, traded for other currencies, or held as a store of value.\n",
    "\n",
    "In this tutorial, we will first download the historical Bitcoin price data in USD as a `pandas` DataFrame. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Date</th>\n",
       "      <th>Close</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2020-01-01</td>\n",
       "      <td>7200.174316</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2020-01-02</td>\n",
       "      <td>6985.470215</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2020-01-03</td>\n",
       "      <td>7344.884277</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2020-01-04</td>\n",
       "      <td>7410.656738</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2020-01-05</td>\n",
       "      <td>7411.317383</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         Date        Close\n",
       "0  2020-01-01  7200.174316\n",
       "1  2020-01-02  6985.470215\n",
       "2  2020-01-03  7344.884277\n",
       "3  2020-01-04  7410.656738\n",
       "4  2020-01-05  7411.317383"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd \n",
    "\n",
    "df = pd.read_csv('https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/bitcoin_price_usd.csv', sep=',')  \n",
    "df.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This dataset contains the closing price of Bitcoin in USD from 2020-01-01 to 2023-12-31. It's important to note that unlike traditional financial assets, Bitcoin trades 24/7. Therefore, the closing price represents the price of Bitcoin at a specific time each day, rather than at the end of a trading day."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For convenience, we will rename the `Date` and `Close` columns to `ds` and `y`, respectively."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.rename(columns={'Date': 'ds', 'Close': 'y'}, inplace=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Get Started with TimeGPT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get started with `TimeGPT`, you need to instantiate the `NixtlaClient` class. For this, you will need a Nixtla API key. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nixtla import NixtlaClient"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nixtla_client = NixtlaClient(\n",
    "    # defaults to os.environ.get(\"NIXTLA_API_KEY\")\n",
    "    api_key = 'my_api_key_provided_by_nixtla'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 👍 Use an Azure AI endpoint\n",
    "> \n",
    "> To use an Azure AI endpoint, remember to set also the `base_url` argument:\n",
    "> \n",
    "> `nixtla_client = NixtlaClient(base_url=\"you azure ai endpoint\", api_key=\"your api_key\")`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide \n",
    "if not IN_COLAB:\n",
    "    nixtla_client = NixtlaClient()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To learn more about how to set up your API key, please refer to the [Setting Up Your Authentication API Key](https://docs.nixtla.io/docs/getting-started-setting_up_your_api_key) tutorial. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Visualize the Data "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before attempting any forecasting, it is good practice to visualize the data we want to predict. The `NixtlaClient` class includes a `plot` method for this purpose. \n",
    "\n",
    "The `plot` method has an `engine` argument that allows you to choose between different plotting libraries. Default is `matplotlib`, but you can also use `plotly` for interactive plots."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 95060 characters]",
      "text/plain": [
       "<Figure size 2400x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.plot(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you haven't renamed the column names of your DataFrame to `ds` and `y`, you will need to specify the `time_col` and `target_col` arguments of the `plot`method: \n",
    "\n",
    "``` python\n",
    "nixtla_client.plot(df, time_col='name of your time column', target_col='name of your target column')\n",
    "```\n",
    "\n",
    "This is necessary not only for the `plot` method but for all methods from the `NixtlaClient` class."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Forecast with TimeGPT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we are ready to generate predictions with TimeGPT. To do this, we will use the `forecast` method from the `NixtlaClient` class.\n",
    "\n",
    "The `forecast` method requires the following arguments:\n",
    "\n",
    "- `df`: The DataFrame containing the time series data\n",
    "\n",
    "- `h`: (int) The forecast horizon. In this case, we will forecast the next 7 days. \n",
    "\n",
    "- `level`: (list) The confidence level for the prediction intervals. Given the inherent volatility of Bitcoin, we will use multiple confidence levels. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:nixtla.nixtla_client:Validating inputs...\n",
      "INFO:nixtla.nixtla_client:Preprocessing dataframes...\n",
      "INFO:nixtla.nixtla_client:Inferred freq: D\n",
      "INFO:nixtla.nixtla_client:Restricting input...\n",
      "INFO:nixtla.nixtla_client:Calling Forecast Endpoint...\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>ds</th>\n",
       "      <th>TimeGPT</th>\n",
       "      <th>TimeGPT-lo-90</th>\n",
       "      <th>TimeGPT-lo-80</th>\n",
       "      <th>TimeGPT-lo-50</th>\n",
       "      <th>TimeGPT-hi-50</th>\n",
       "      <th>TimeGPT-hi-80</th>\n",
       "      <th>TimeGPT-hi-90</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2024-01-01</td>\n",
       "      <td>42269.460938</td>\n",
       "      <td>39567.209020</td>\n",
       "      <td>40429.953636</td>\n",
       "      <td>41380.654646</td>\n",
       "      <td>43158.267229</td>\n",
       "      <td>44108.968239</td>\n",
       "      <td>44971.712855</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2024-01-02</td>\n",
       "      <td>42469.917969</td>\n",
       "      <td>39697.941669</td>\n",
       "      <td>40578.197049</td>\n",
       "      <td>41466.511361</td>\n",
       "      <td>43473.324576</td>\n",
       "      <td>44361.638888</td>\n",
       "      <td>45241.894268</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2024-01-03</td>\n",
       "      <td>42864.078125</td>\n",
       "      <td>40538.871243</td>\n",
       "      <td>41586.252507</td>\n",
       "      <td>42284.316674</td>\n",
       "      <td>43443.839576</td>\n",
       "      <td>44141.903743</td>\n",
       "      <td>45189.285007</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2024-01-04</td>\n",
       "      <td>42881.621094</td>\n",
       "      <td>40603.117448</td>\n",
       "      <td>41216.106493</td>\n",
       "      <td>42058.539392</td>\n",
       "      <td>43704.702795</td>\n",
       "      <td>44547.135694</td>\n",
       "      <td>45160.124739</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2024-01-05</td>\n",
       "      <td>42773.457031</td>\n",
       "      <td>40213.699760</td>\n",
       "      <td>40665.384780</td>\n",
       "      <td>41489.812431</td>\n",
       "      <td>44057.101632</td>\n",
       "      <td>44881.529282</td>\n",
       "      <td>45333.214302</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           ds       TimeGPT  TimeGPT-lo-90  TimeGPT-lo-80  TimeGPT-lo-50  \\\n",
       "0  2024-01-01  42269.460938   39567.209020   40429.953636   41380.654646   \n",
       "1  2024-01-02  42469.917969   39697.941669   40578.197049   41466.511361   \n",
       "2  2024-01-03  42864.078125   40538.871243   41586.252507   42284.316674   \n",
       "3  2024-01-04  42881.621094   40603.117448   41216.106493   42058.539392   \n",
       "4  2024-01-05  42773.457031   40213.699760   40665.384780   41489.812431   \n",
       "\n",
       "   TimeGPT-hi-50  TimeGPT-hi-80  TimeGPT-hi-90  \n",
       "0   43158.267229   44108.968239   44971.712855  \n",
       "1   43473.324576   44361.638888   45241.894268  \n",
       "2   43443.839576   44141.903743   45189.285007  \n",
       "3   43704.702795   44547.135694   45160.124739  \n",
       "4   44057.101632   44881.529282   45333.214302  "
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "level = [50,80,90] # confidence levels \n",
    "\n",
    "fcst = nixtla_client.forecast(df, h=7, level=level)\n",
    "fcst.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 📘 Available models in Azure AI\n",
    ">\n",
    "> If you are using an Azure AI endpoint, please be sure to set `model=\"azureai\"`:\n",
    ">\n",
    "> `nixtla_client.forecast(..., model=\"azureai\")`\n",
    "> \n",
    "> For the public API, we support two models: `timegpt-1` and `timegpt-1-long-horizon`. \n",
    "> \n",
    "> By default, `timegpt-1` is used. Please see [this tutorial](https://docs.nixtla.io/docs/tutorials-long_horizon_forecasting) on how and when to use `timegpt-1-long-horizon`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can pass the forecasts we just generated to the `plot` method to visualize the predictions with the historical data.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 105152 characters]",
      "text/plain": [
       "<Figure size 2400x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.plot(df, fcst, level=level)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get a closer look at the predictions, we can zoom in on the plot or specify the maximum number of in-sample observations to be plotted using the `max_insample_length` argument. Note that setting `max_insample_length=60`, for instance, will display the last 60 historical values along with the complete forecast.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 81840 characters]",
      "text/plain": [
       "<Figure size 2400x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.plot(df, fcst, level=level, max_insample_length=60)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, if you set the `add_history` argument of the `forecast` method to `True`, `TimeGPT` will generate predictions for the historical observations too. This can be useful for assessing the model's performance on the training data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:nixtla.nixtla_client:Validating inputs...\n",
      "INFO:nixtla.nixtla_client:Preprocessing dataframes...\n",
      "INFO:nixtla.nixtla_client:Inferred freq: D\n",
      "INFO:nixtla.nixtla_client:Calling Forecast Endpoint...\n",
      "INFO:nixtla.nixtla_client:Calling Historical Forecast Endpoint...\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>ds</th>\n",
       "      <th>TimeGPT</th>\n",
       "      <th>TimeGPT-lo-50</th>\n",
       "      <th>TimeGPT-lo-80</th>\n",
       "      <th>TimeGPT-lo-90</th>\n",
       "      <th>TimeGPT-hi-50</th>\n",
       "      <th>TimeGPT-hi-80</th>\n",
       "      <th>TimeGPT-hi-90</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2020-02-03</td>\n",
       "      <td>9425.702148</td>\n",
       "      <td>7622.287194</td>\n",
       "      <td>5999.157479</td>\n",
       "      <td>5027.779677</td>\n",
       "      <td>11229.117103</td>\n",
       "      <td>12852.246818</td>\n",
       "      <td>13823.624619</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2020-02-04</td>\n",
       "      <td>9568.482422</td>\n",
       "      <td>7765.067467</td>\n",
       "      <td>6141.937752</td>\n",
       "      <td>5170.559951</td>\n",
       "      <td>11371.897376</td>\n",
       "      <td>12995.027092</td>\n",
       "      <td>13966.404893</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2020-02-05</td>\n",
       "      <td>9557.082031</td>\n",
       "      <td>7753.667077</td>\n",
       "      <td>6130.537362</td>\n",
       "      <td>5159.159560</td>\n",
       "      <td>11360.496986</td>\n",
       "      <td>12983.626701</td>\n",
       "      <td>13955.004502</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2020-02-06</td>\n",
       "      <td>9486.123047</td>\n",
       "      <td>7682.708092</td>\n",
       "      <td>6059.578377</td>\n",
       "      <td>5088.200576</td>\n",
       "      <td>11289.538001</td>\n",
       "      <td>12912.667717</td>\n",
       "      <td>13884.045518</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2020-02-07</td>\n",
       "      <td>9475.242188</td>\n",
       "      <td>7671.827233</td>\n",
       "      <td>6048.697518</td>\n",
       "      <td>5077.319716</td>\n",
       "      <td>11278.657142</td>\n",
       "      <td>12901.786857</td>\n",
       "      <td>13873.164659</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           ds      TimeGPT  TimeGPT-lo-50  TimeGPT-lo-80  TimeGPT-lo-90  \\\n",
       "0  2020-02-03  9425.702148    7622.287194    5999.157479    5027.779677   \n",
       "1  2020-02-04  9568.482422    7765.067467    6141.937752    5170.559951   \n",
       "2  2020-02-05  9557.082031    7753.667077    6130.537362    5159.159560   \n",
       "3  2020-02-06  9486.123047    7682.708092    6059.578377    5088.200576   \n",
       "4  2020-02-07  9475.242188    7671.827233    6048.697518    5077.319716   \n",
       "\n",
       "   TimeGPT-hi-50  TimeGPT-hi-80  TimeGPT-hi-90  \n",
       "0   11229.117103   12852.246818   13823.624619  \n",
       "1   11371.897376   12995.027092   13966.404893  \n",
       "2   11360.496986   12983.626701   13955.004502  \n",
       "3   11289.538001   12912.667717   13884.045518  \n",
       "4   11278.657142   12901.786857   13873.164659  "
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forecast = nixtla_client.forecast(df, h=7, level=level, add_history=True)\n",
    "forecast.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 📘 Available models in Azure AI\n",
    ">\n",
    "> If you are using an Azure AI endpoint, please be sure to set `model=\"azureai\"`:\n",
    ">\n",
    "> `nixtla_client.forecast(..., model=\"azureai\")`\n",
    "> \n",
    "> For the public API, we support two models: `timegpt-1` and `timegpt-1-long-horizon`. \n",
    "> \n",
    "> By default, `timegpt-1` is used. Please see [this tutorial](https://docs.nixtla.io/docs/tutorials-long_horizon_forecasting) on how and when to use `timegpt-1-long-horizon`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 208472 characters]",
      "text/plain": [
       "<Figure size 2400x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.plot(df, forecast, level=level)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Extend Bitcoin Price Analysis with TimeGPT"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Anomaly Detection "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Given the volatility of the price of Bitcoin, it can be useful to try to identify anomalies in the data. `TimeGPT` can be used for this by calling the `detect_anomalies` method from the `NixtlaClient` class. This method evaluates each observation against its context within the series, using statistical measures to determine its likelihood of being an anomaly. By default, it identifies anomalies based on a 99 percent prediction interval. To change this, you can specify the `level` argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:nixtla.nixtla_client:Validating inputs...\n",
      "INFO:nixtla.nixtla_client:Preprocessing dataframes...\n",
      "INFO:nixtla.nixtla_client:Inferred freq: D\n",
      "INFO:nixtla.nixtla_client:Calling Anomaly Detector Endpoint...\n"
     ]
    }
   ],
   "source": [
    "anomalies_df = nixtla_client.detect_anomalies(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 📘 Available models in Azure AI\n",
    ">\n",
    "> If you are using an Azure AI endpoint, please be sure to set `model=\"azureai\"`:\n",
    ">\n",
    "> `nixtla_client.detect_anomalies(..., model=\"azureai\")`\n",
    "> \n",
    "> For the public API, we support two models: `timegpt-1` and `timegpt-1-long-horizon`. \n",
    "> \n",
    "> By default, `timegpt-1` is used. Please see [this tutorial](https://docs.nixtla.io/docs/tutorials-long_horizon_forecasting) on how and when to use `timegpt-1-long-horizon`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 141940 characters]",
      "text/plain": [
       "<Figure size 2400x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.plot(df, anomalies_df, plot_anomalies=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To learn more about how to detect anomalies with `TimeGPT`, take a look at our [Anomaly Detection](https://docs.nixtla.io/docs/capabilities-anomaly-detection-anomaly_detection) tutorial.   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Add Exogenous Variables"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you have additional information that you believe could help improve the forecast, consider including it as an exogenous variable. For instance, you might add data such as the price of other cryptocurrencies, proprietary information, stock market indices, or the number of transactions in the Bitcoin network.\n",
    "\n",
    "`TimeGPT` supports the incorporation of exogenous variables in the `forecast` method. However, keep in mind that you'll need to know the future values of these variables.\n",
    "\n",
    "To learn how to incorporate exogenous variables to `TimeGPT`, refer to the [Exogenous Variables](https://docs.nixtla.io/docs/tutorials-exogenous_variables) tutorial."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Understand the Model's Limitations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As stated in the introduction, predicting the future prices of financial assets is a challenging task, especially for assets like Bitcoin. The predictions in this tutorial may appear accurate, mainly because they align with recent historical data and the model updates with new values at short intervals, avoiding significant deviations. However, the true challenge lies in forecasting Bitcoin's price for the upcoming days, not just its historical performance. For those who need or want to try to forecast these assets, `TimeGPT` can be an option that simplifies the forecasting process. With just a couple of lines of code, `TimeGPT` can help you: \n",
    "\n",
    "- Produce point forecasts \n",
    "- Quantify the uncertainty of your predictions \n",
    "- Produce in-sample forecasts \n",
    "- Detect anomalies \n",
    "- Incorporate exogenous variables\n",
    "\n",
    "To learn more about `TimeGPT` capabilities, please refer to the [TimeGPT Documentation](https://docs.nixtla.io/)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. References and Additional Material "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**References**\n",
    "\n",
    "* [Joaquín Amat Rodrigo and Javier Escobar Ortiz (2022), \"Bitcoin price prediction with Python, when the past does not repeat itself\"](https://www.cienciadedatos.net/documentos/py41-forecasting-cryptocurrency-bitcoin-machine-learning-python.html)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Furthermore, for many financial time series, the best estimate for the price is often a random walk model, meaning that the best forecast for tomorrow's price is today's price. Nixtla's [StatsForecast](https://nixtlaverse.nixtla.io/statsforecast/index.html) library allows you to easily implement this model and variations. "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
