{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18102cea",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "!pip install -Uqq nixtla"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a50470ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide \n",
    "from nixtla.utils import in_colab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ace35684",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide \n",
    "IN_COLAB = in_colab()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b1ea1aa8",
   "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",
   "id": "6ecd9d32-9178-4768-bffa-d70c93c98311",
   "metadata": {},
   "source": [
    "# TimeGPT Quickstart (Polars)\n",
    "\n",
    "> TimeGPT is a production ready, generative pretrained transformer for time series. It's capable of accurately predicting various domains such as retail, electricity, finance, and IoT with just a few lines of code 🚀."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c48909a",
   "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/getting-started/21_polars_quickstart.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/getting-started/21_polars_quickstart')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e5b10a6-b39c-4583-bc2c-ab0b70eeea28",
   "metadata": {},
   "source": [
    "## Step 1: Create a TimeGPT account and generate your API key\n",
    "\n",
    "* Go to [dashboard.nixtla.io](https://dashboard.nixtla.io/)\n",
    "* Sign in with Google, GitHub or your email\n",
    "* Create your API key by going to 'API Keys' in the menu and clicking on 'Create New API Key'\n",
    "* Your new key will appear. Copy the API key using the button on the right.\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aa3705dd-6133-4eb0-8c53-8a8ff65ee455",
   "metadata": {},
   "source": [
    "<img src=\"https://github.com/Nixtla/nixtla/blob/main/nbs/img/dashboard.png?raw=true\" alt=\"Dashboard for TimeGPT API keys. Keys is in the middle, with trash and copy buttons on the right.\" width=\"700\" />"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f30be1a-3eaf-4133-8254-680e8f7cda72",
   "metadata": {},
   "source": [
    "## Step 2: Install Nixtla"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73ad0fc4-bcf1-4b7e-8e6c-5969982e1b78",
   "metadata": {},
   "source": [
    "In your favorite Python development environment:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9c35e70",
   "metadata": {},
   "source": [
    "Install `nixtla` with `pip`:\n",
    "    \n",
    "```shell\n",
    "pip install nixtla\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03e24b4f-6b8c-4ffa-82c6-f5b889fdd423",
   "metadata": {},
   "source": [
    "## Step 3: Import the Nixtla TimeGPT client"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d984aea-1315-4d4e-8b4d-b23efe947be1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from nixtla import NixtlaClient"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b73a131-390e-46b9-847b-173f7d3c869a",
   "metadata": {},
   "source": [
    "You can instantiate the `NixtlaClient` class providing your authentication API key. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f1098659-f250-4663-b588-f9e17065cafa",
   "metadata": {},
   "outputs": [],
   "source": [
    "nixtla_client = NixtlaClient(\n",
    "    api_key = 'my_api_key_provided_by_nixtla'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5b8ea7f-e30e-4001-a7a6-9e935e12180a",
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "if not IN_COLAB:\n",
    "    nixtla_client = NixtlaClient()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e7cea32-ade9-4b23-be93-9a4fbea7c6b2",
   "metadata": {},
   "source": [
    "Check your API key status with the `validate_api_key` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95fd6f32-8ada-4bd8-9083-77bb45bd2349",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.validate_api_key()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2597400",
   "metadata": {},
   "source": [
    "**This will get you started, but for more secure usage, see [Setting Up your API Key](https://docs.nixtla.io/docs/getting-started-setting_up_your_api_key).**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ca0d1f7-9730-4146-b6f3-596099ce6e3b",
   "metadata": {},
   "source": [
    "## Step 4: Start making forecasts!\n",
    "\n",
    "Now you can start making forecasts! Let's import an example using the classic `AirPassengers` dataset. This dataset contains the monthly number of airline passengers in Australia between 1949 and 1960. First, load the dataset and plot it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "687802f2-be84-4b81-95eb-44798c591daf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import polars as pl"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fded6ec5-949a-44b8-9a4a-8fc8a5295e06",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div><style>\n",
       ".dataframe > thead > tr,\n",
       ".dataframe > tbody > tr {\n",
       "  text-align: right;\n",
       "  white-space: pre-wrap;\n",
       "}\n",
       "</style>\n",
       "<small>shape: (5, 2)</small><table border=\"1\" class=\"dataframe\"><thead><tr><th>timestamp</th><th>value</th></tr><tr><td>date</td><td>i64</td></tr></thead><tbody><tr><td>1949-01-01</td><td>112</td></tr><tr><td>1949-02-01</td><td>118</td></tr><tr><td>1949-03-01</td><td>132</td></tr><tr><td>1949-04-01</td><td>129</td></tr><tr><td>1949-05-01</td><td>121</td></tr></tbody></table></div>"
      ],
      "text/plain": [
       "shape: (5, 2)\n",
       "┌────────────┬───────┐\n",
       "│ timestamp  ┆ value │\n",
       "│ ---        ┆ ---   │\n",
       "│ date       ┆ i64   │\n",
       "╞════════════╪═══════╡\n",
       "│ 1949-01-01 ┆ 112   │\n",
       "│ 1949-02-01 ┆ 118   │\n",
       "│ 1949-03-01 ┆ 132   │\n",
       "│ 1949-04-01 ┆ 129   │\n",
       "│ 1949-05-01 ┆ 121   │\n",
       "└────────────┴───────┘"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pl.read_csv(\n",
    "    'https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/air_passengers.csv',\n",
    "    try_parse_dates=True,\n",
    ")\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6242b73d-fd43-41be-b4db-123cf7cd5b11",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 72340 characters]",
      "text/plain": [
       "<Figure size 1600x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.plot(df, time_col='timestamp', target_col='value')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "defa26b8",
   "metadata": {},
   "source": [
    "> 📘 Data Requirements\n",
    ">\n",
    "> * Make sure the target variable column does not have missing or non-numeric values.\n",
    "> * Do not include gaps/jumps in the timestamps (for the given frequency) between the first and late timestamps. The forecast function will not impute missing dates.\n",
    "> * The time column should be of type [Date](https://docs.pola.rs/api/python/stable/reference/api/polars.datatypes.Date.html) or [Datetime](https://docs.pola.rs/api/python/stable/reference/api/polars.datatypes.Datetime.html).\n",
    ">\n",
    ">For further details go to [Data Requeriments](https://docs.nixtla.io/docs/getting-started-data_requirements)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7631f17b-0ca4-4cf1-9b89-182a7d85fda6",
   "metadata": {},
   "source": [
    "### Forecast a longer horizon into the future"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c4790e3",
   "metadata": {},
   "source": [
    "Next, forecast the next 12 months using the SDK `forecast` method. Set the following parameters:\n",
    "\n",
    "- `df`: A pandas DataFrame containing the time series data.\n",
    "- `h`: Horizons is the number of steps ahead to forecast.\n",
    "- `freq`: The polars offset alias, see the possible values [here](https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.dt.offset_by.html).\n",
    "- `time_col`: The column that identifies the datestamp.\n",
    "- `target_col`: The variable to forecast.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "793011c6-6845-410f-b6b1-3bdb87b41ce6",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:nixtla.nixtla_client:Validating inputs...\n",
      "INFO:nixtla.nixtla_client:Querying model metadata...\n",
      "INFO:nixtla.nixtla_client:Preprocessing dataframes...\n",
      "INFO:nixtla.nixtla_client:Restricting input...\n",
      "INFO:nixtla.nixtla_client:Calling Forecast Endpoint...\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><style>\n",
       ".dataframe > thead > tr,\n",
       ".dataframe > tbody > tr {\n",
       "  text-align: right;\n",
       "  white-space: pre-wrap;\n",
       "}\n",
       "</style>\n",
       "<small>shape: (5, 2)</small><table border=\"1\" class=\"dataframe\"><thead><tr><th>timestamp</th><th>TimeGPT</th></tr><tr><td>date</td><td>f64</td></tr></thead><tbody><tr><td>1961-01-01</td><td>437.837921</td></tr><tr><td>1961-02-01</td><td>426.062714</td></tr><tr><td>1961-03-01</td><td>463.116547</td></tr><tr><td>1961-04-01</td><td>478.244507</td></tr><tr><td>1961-05-01</td><td>505.646484</td></tr></tbody></table></div>"
      ],
      "text/plain": [
       "shape: (5, 2)\n",
       "┌────────────┬────────────┐\n",
       "│ timestamp  ┆ TimeGPT    │\n",
       "│ ---        ┆ ---        │\n",
       "│ date       ┆ f64        │\n",
       "╞════════════╪════════════╡\n",
       "│ 1961-01-01 ┆ 437.837921 │\n",
       "│ 1961-02-01 ┆ 426.062714 │\n",
       "│ 1961-03-01 ┆ 463.116547 │\n",
       "│ 1961-04-01 ┆ 478.244507 │\n",
       "│ 1961-05-01 ┆ 505.646484 │\n",
       "└────────────┴────────────┘"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "timegpt_fcst_df = nixtla_client.forecast(df=df, h=12, freq='1mo', time_col='timestamp', target_col='value')\n",
    "timegpt_fcst_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "638329d2-2d1b-49dd-8df7-1926f7d9b36b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 76468 characters]",
      "text/plain": [
       "<Figure size 1600x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.plot(df, timegpt_fcst_df, time_col='timestamp', target_col='value')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0397b0a9-07dc-45ad-a64b-ab619d34254f",
   "metadata": {},
   "source": [
    "You can also produce longer forecasts by increasing the horizon parameter and selecting the `timegpt-1-long-horizon` model. Use this model if you want to predict more than one seasonal period of your data.\n",
    "\n",
    "For example, let's forecast the next 36 months:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e69f5d11-b262-458f-8909-aaefc805cd23",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:nixtla.nixtla_client:Validating inputs...\n",
      "INFO:nixtla.nixtla_client:Querying model metadata...\n",
      "WARNING:nixtla.nixtla_client:The specified horizon \"h\" exceeds the model horizon. This may lead to less accurate forecasts. Please consider using a smaller horizon.\n",
      "INFO:nixtla.nixtla_client:Preprocessing dataframes...\n",
      "INFO:nixtla.nixtla_client:Restricting input...\n",
      "INFO:nixtla.nixtla_client:Calling Forecast Endpoint...\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><style>\n",
       ".dataframe > thead > tr,\n",
       ".dataframe > tbody > tr {\n",
       "  text-align: right;\n",
       "  white-space: pre-wrap;\n",
       "}\n",
       "</style>\n",
       "<small>shape: (5, 2)</small><table border=\"1\" class=\"dataframe\"><thead><tr><th>timestamp</th><th>TimeGPT</th></tr><tr><td>date</td><td>f64</td></tr></thead><tbody><tr><td>1961-01-01</td><td>436.843414</td></tr><tr><td>1961-02-01</td><td>419.351532</td></tr><tr><td>1961-03-01</td><td>458.943146</td></tr><tr><td>1961-04-01</td><td>477.876068</td></tr><tr><td>1961-05-01</td><td>505.656921</td></tr></tbody></table></div>"
      ],
      "text/plain": [
       "shape: (5, 2)\n",
       "┌────────────┬────────────┐\n",
       "│ timestamp  ┆ TimeGPT    │\n",
       "│ ---        ┆ ---        │\n",
       "│ date       ┆ f64        │\n",
       "╞════════════╪════════════╡\n",
       "│ 1961-01-01 ┆ 436.843414 │\n",
       "│ 1961-02-01 ┆ 419.351532 │\n",
       "│ 1961-03-01 ┆ 458.943146 │\n",
       "│ 1961-04-01 ┆ 477.876068 │\n",
       "│ 1961-05-01 ┆ 505.656921 │\n",
       "└────────────┴────────────┘"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "timegpt_fcst_df = nixtla_client.forecast(df=df, h=36, time_col='timestamp', target_col='value', freq='1mo', model='timegpt-1-long-horizon')\n",
    "timegpt_fcst_df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd521875-1a23-43a0-99ea-979ca0efc631",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 79516 characters]",
      "text/plain": [
       "<Figure size 1600x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "nixtla_client.plot(df, timegpt_fcst_df, time_col='timestamp', target_col='value')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff6d8e76-dbc1-407f-8a49-5e622735ca3d",
   "metadata": {},
   "source": [
    "### Produce a shorter forecast"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "12e9766e-d7a8-40f6-bfaa-4df07da6c505",
   "metadata": {},
   "source": [
    "You can also produce a shorter forecast. For this, we recommend using the default model, `timegpt-1`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94da9c70-b4e5-4f16-927f-4c153bbabaff",
   "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:Restricting input...\n",
      "INFO:nixtla.nixtla_client:Calling Forecast Endpoint...\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 75060 characters]",
      "text/plain": [
       "<Figure size 1600x350 with 1 Axes>"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "timegpt_fcst_df = nixtla_client.forecast(df=df, h=6, time_col='timestamp', target_col='value', freq='1mo')\n",
    "nixtla_client.plot(df, timegpt_fcst_df, time_col='timestamp', target_col='value')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
