Spaces:
Sleeping
Sleeping
Commit
·
0b7a7fc
1
Parent(s):
b44004b
First commit
Browse files- .gitignore +3 -1
- notebooks/01_api_bitcoin.ipynb +66 -0
- notebooks/02_model_inference.ipynb +346 -0
- requirements.txt +7 -0
- src/app.py +71 -0
- src/model.py +25 -0
- src/utils.py +63 -0
.gitignore
CHANGED
|
@@ -191,4 +191,6 @@ cython_debug/
|
|
| 191 |
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
| 192 |
# refer to https://docs.cursor.com/context/ignore-files
|
| 193 |
.cursorignore
|
| 194 |
-
.cursorindexingignore
|
|
|
|
|
|
|
|
|
| 191 |
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
| 192 |
# refer to https://docs.cursor.com/context/ignore-files
|
| 193 |
.cursorignore
|
| 194 |
+
.cursorindexingignore
|
| 195 |
+
|
| 196 |
+
/data
|
notebooks/01_api_bitcoin.ipynb
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 25,
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"outputs": [],
|
| 8 |
+
"source": [
|
| 9 |
+
"import numpy as np \n",
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import yfinance as yf"
|
| 12 |
+
]
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"cell_type": "code",
|
| 16 |
+
"execution_count": 26,
|
| 17 |
+
"metadata": {},
|
| 18 |
+
"outputs": [],
|
| 19 |
+
"source": [
|
| 20 |
+
"def get_bitcoin_history_yf(start_date, end_date):\n",
|
| 21 |
+
" btc = yf.Ticker(\"BTC-USD\")\n",
|
| 22 |
+
" hist = btc.history(start=start_date, end=end_date)\n",
|
| 23 |
+
" return hist.reset_index()[[\"Date\", \"Close\"]].rename(columns={\"Date\": \"date\", \"Close\": \"price\"})"
|
| 24 |
+
]
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"execution_count": 27,
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"outputs": [],
|
| 31 |
+
"source": [
|
| 32 |
+
"df = get_bitcoin_history_yf(start_date=\"2024-02-01\", end_date=\"2025-01-01\")"
|
| 33 |
+
]
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"execution_count": 32,
|
| 38 |
+
"metadata": {},
|
| 39 |
+
"outputs": [],
|
| 40 |
+
"source": [
|
| 41 |
+
"# df.to_csv(\"/Users/sebastianalejandrosarastizambonino/Documents/conferences/time_series_u_palermo/data/bitcoin_history_yf.csv\", index=False)"
|
| 42 |
+
]
|
| 43 |
+
}
|
| 44 |
+
],
|
| 45 |
+
"metadata": {
|
| 46 |
+
"kernelspec": {
|
| 47 |
+
"display_name": "tsfm",
|
| 48 |
+
"language": "python",
|
| 49 |
+
"name": "python3"
|
| 50 |
+
},
|
| 51 |
+
"language_info": {
|
| 52 |
+
"codemirror_mode": {
|
| 53 |
+
"name": "ipython",
|
| 54 |
+
"version": 3
|
| 55 |
+
},
|
| 56 |
+
"file_extension": ".py",
|
| 57 |
+
"mimetype": "text/x-python",
|
| 58 |
+
"name": "python",
|
| 59 |
+
"nbconvert_exporter": "python",
|
| 60 |
+
"pygments_lexer": "ipython3",
|
| 61 |
+
"version": "3.11.13"
|
| 62 |
+
}
|
| 63 |
+
},
|
| 64 |
+
"nbformat": 4,
|
| 65 |
+
"nbformat_minor": 2
|
| 66 |
+
}
|
notebooks/02_model_inference.ipynb
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": 8,
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"outputs": [],
|
| 8 |
+
"source": [
|
| 9 |
+
"import timesfm\n",
|
| 10 |
+
"import pandas as pd"
|
| 11 |
+
]
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"cell_type": "code",
|
| 15 |
+
"execution_count": 51,
|
| 16 |
+
"metadata": {},
|
| 17 |
+
"outputs": [
|
| 18 |
+
{
|
| 19 |
+
"name": "stderr",
|
| 20 |
+
"output_type": "stream",
|
| 21 |
+
"text": [
|
| 22 |
+
"Fetching 5 files: 100%|██████████| 5/5 [00:00<00:00, 48545.19it/s]\n"
|
| 23 |
+
]
|
| 24 |
+
}
|
| 25 |
+
],
|
| 26 |
+
"source": [
|
| 27 |
+
"tfm = timesfm.TimesFm(\n",
|
| 28 |
+
" hparams=timesfm.TimesFmHparams(\n",
|
| 29 |
+
" backend=\"gpu\",\n",
|
| 30 |
+
" per_core_batch_size=32,\n",
|
| 31 |
+
" horizon_len=10,\n",
|
| 32 |
+
" num_layers=50,\n",
|
| 33 |
+
" use_positional_embedding=False,\n",
|
| 34 |
+
" context_len=2048,\n",
|
| 35 |
+
" ),\n",
|
| 36 |
+
" checkpoint=timesfm.TimesFmCheckpoint(\n",
|
| 37 |
+
" huggingface_repo_id=\"google/timesfm-2.0-500m-pytorch\"),\n",
|
| 38 |
+
" )"
|
| 39 |
+
]
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "markdown",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"source": [
|
| 45 |
+
"Create a function to process a dataframe"
|
| 46 |
+
]
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "code",
|
| 50 |
+
"execution_count": 52,
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"outputs": [],
|
| 53 |
+
"source": [
|
| 54 |
+
"def process_dataframe(df):\n",
|
| 55 |
+
" df = df.rename(\n",
|
| 56 |
+
" columns={\n",
|
| 57 |
+
" \"date\": \"ds\",\n",
|
| 58 |
+
" \"price\": \"y\"\n",
|
| 59 |
+
" }\n",
|
| 60 |
+
" )\n",
|
| 61 |
+
" df['ds'] = pd.to_datetime(df['ds'])\n",
|
| 62 |
+
" df['unique_id'] = \"bitcoin\"\n",
|
| 63 |
+
" return df"
|
| 64 |
+
]
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"execution_count": 53,
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"outputs": [],
|
| 71 |
+
"source": [
|
| 72 |
+
"df = pd.read_csv(\n",
|
| 73 |
+
" \"/Users/sebastianalejandrosarastizambonino/Documents/conferences/time_series_u_palermo/data/bitcoin_history_yf.csv\",\n",
|
| 74 |
+
")"
|
| 75 |
+
]
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"execution_count": 54,
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"outputs": [],
|
| 82 |
+
"source": [
|
| 83 |
+
"df_final = process_dataframe(df)"
|
| 84 |
+
]
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "markdown",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"Create a function to make inference over the model"
|
| 91 |
+
]
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"execution_count": 55,
|
| 96 |
+
"metadata": {},
|
| 97 |
+
"outputs": [
|
| 98 |
+
{
|
| 99 |
+
"name": "stdout",
|
| 100 |
+
"output_type": "stream",
|
| 101 |
+
"text": [
|
| 102 |
+
"Help on method forecast_on_df in module timesfm.timesfm_base:\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"forecast_on_df(inputs: pandas.core.frame.DataFrame, freq: str, forecast_context_len: int = 0, value_name: str = 'values', model_name: str = 'timesfm', window_size: int | None = None, num_jobs: int = 1, normalize: bool = False, verbose: bool = True) -> pandas.core.frame.DataFrame method of timesfm.timesfm_torch.TimesFmTorch instance\n",
|
| 105 |
+
" Forecasts on a list of time series.\n",
|
| 106 |
+
" \n",
|
| 107 |
+
" Args:\n",
|
| 108 |
+
" inputs: A pd.DataFrame of all time series. The dataframe should have a\n",
|
| 109 |
+
" `unique_id` column for identifying the time series, a `ds` column for\n",
|
| 110 |
+
" timestamps and a value column for the time series values.\n",
|
| 111 |
+
" freq: string valued `freq` of data. Notice this is different from the\n",
|
| 112 |
+
" `freq` required by `forecast`. See `freq_map` for allowed values.\n",
|
| 113 |
+
" forecast_context_len: If provided none zero, we take the last\n",
|
| 114 |
+
" `forecast_context_len` time-points from each series as the forecast\n",
|
| 115 |
+
" context instead of the `context_len` set by the model.\n",
|
| 116 |
+
" value_name: The name of the value column.\n",
|
| 117 |
+
" model_name: name of the model to be written into future df.\n",
|
| 118 |
+
" window_size: window size of trend + residual decomposition. If None then\n",
|
| 119 |
+
" we do not do decomposition.\n",
|
| 120 |
+
" num_jobs: number of parallel processes to use for dataframe processing.\n",
|
| 121 |
+
" normalize: normalize context before forecasting or not.\n",
|
| 122 |
+
" verbose: output model states in terminal.\n",
|
| 123 |
+
" \n",
|
| 124 |
+
" Returns:\n",
|
| 125 |
+
" Future forecasts dataframe.\n",
|
| 126 |
+
"\n"
|
| 127 |
+
]
|
| 128 |
+
}
|
| 129 |
+
],
|
| 130 |
+
"source": [
|
| 131 |
+
"help(tfm.forecast_on_df)"
|
| 132 |
+
]
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"execution_count": 56,
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"outputs": [],
|
| 139 |
+
"source": [
|
| 140 |
+
"def predict_timesfm(df, model):\n",
|
| 141 |
+
" forecast_df = model.forecast_on_df(\n",
|
| 142 |
+
" inputs=df,\n",
|
| 143 |
+
" forecast_context_len=10,\n",
|
| 144 |
+
" freq=\"D\", # monthly\n",
|
| 145 |
+
" value_name=\"y\",\n",
|
| 146 |
+
" num_jobs=-1,\n",
|
| 147 |
+
" )\n",
|
| 148 |
+
" forecast_df = forecast_df[['ds', 'unique_id', 'timesfm']]\n",
|
| 149 |
+
" forecast_df = forecast_df.rename(\n",
|
| 150 |
+
" columns={\n",
|
| 151 |
+
" \"timesfm\": \"yhat\"\n",
|
| 152 |
+
" }\n",
|
| 153 |
+
" )\n",
|
| 154 |
+
" return forecast_df"
|
| 155 |
+
]
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"execution_count": 57,
|
| 160 |
+
"metadata": {},
|
| 161 |
+
"outputs": [
|
| 162 |
+
{
|
| 163 |
+
"data": {
|
| 164 |
+
"text/plain": [
|
| 165 |
+
"Index(['ds', 'y', 'unique_id'], dtype='object')"
|
| 166 |
+
]
|
| 167 |
+
},
|
| 168 |
+
"execution_count": 57,
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"output_type": "execute_result"
|
| 171 |
+
}
|
| 172 |
+
],
|
| 173 |
+
"source": [
|
| 174 |
+
"df_final.columns"
|
| 175 |
+
]
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"execution_count": 58,
|
| 180 |
+
"metadata": {},
|
| 181 |
+
"outputs": [
|
| 182 |
+
{
|
| 183 |
+
"name": "stdout",
|
| 184 |
+
"output_type": "stream",
|
| 185 |
+
"text": [
|
| 186 |
+
"Processing dataframe with multiple processes.\n",
|
| 187 |
+
" See https://github.com/google-research/timesfm/blob/master/README.md for updated APIs.\n",
|
| 188 |
+
"Loaded PyTorch TimesFM, likely because python version is 3.11.13 (main, Jun 5 2025, 08:21:08) [Clang 14.0.6 ].\n",
|
| 189 |
+
"Finished preprocessing dataframe.\n",
|
| 190 |
+
"Finished forecasting.\n"
|
| 191 |
+
]
|
| 192 |
+
}
|
| 193 |
+
],
|
| 194 |
+
"source": [
|
| 195 |
+
"forecast = predict_timesfm(df_final)"
|
| 196 |
+
]
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"execution_count": 59,
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"outputs": [
|
| 203 |
+
{
|
| 204 |
+
"data": {
|
| 205 |
+
"text/html": [
|
| 206 |
+
"<div>\n",
|
| 207 |
+
"<style scoped>\n",
|
| 208 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
| 209 |
+
" vertical-align: middle;\n",
|
| 210 |
+
" }\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" .dataframe tbody tr th {\n",
|
| 213 |
+
" vertical-align: top;\n",
|
| 214 |
+
" }\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" .dataframe thead th {\n",
|
| 217 |
+
" text-align: right;\n",
|
| 218 |
+
" }\n",
|
| 219 |
+
"</style>\n",
|
| 220 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
| 221 |
+
" <thead>\n",
|
| 222 |
+
" <tr style=\"text-align: right;\">\n",
|
| 223 |
+
" <th></th>\n",
|
| 224 |
+
" <th>ds</th>\n",
|
| 225 |
+
" <th>unique_id</th>\n",
|
| 226 |
+
" <th>yhat</th>\n",
|
| 227 |
+
" </tr>\n",
|
| 228 |
+
" </thead>\n",
|
| 229 |
+
" <tbody>\n",
|
| 230 |
+
" <tr>\n",
|
| 231 |
+
" <th>0</th>\n",
|
| 232 |
+
" <td>2025-01-01 00:00:00+00:00</td>\n",
|
| 233 |
+
" <td>bitcoin</td>\n",
|
| 234 |
+
" <td>93821.898438</td>\n",
|
| 235 |
+
" </tr>\n",
|
| 236 |
+
" <tr>\n",
|
| 237 |
+
" <th>1</th>\n",
|
| 238 |
+
" <td>2025-01-02 00:00:00+00:00</td>\n",
|
| 239 |
+
" <td>bitcoin</td>\n",
|
| 240 |
+
" <td>93758.367188</td>\n",
|
| 241 |
+
" </tr>\n",
|
| 242 |
+
" <tr>\n",
|
| 243 |
+
" <th>2</th>\n",
|
| 244 |
+
" <td>2025-01-03 00:00:00+00:00</td>\n",
|
| 245 |
+
" <td>bitcoin</td>\n",
|
| 246 |
+
" <td>93707.375000</td>\n",
|
| 247 |
+
" </tr>\n",
|
| 248 |
+
" <tr>\n",
|
| 249 |
+
" <th>3</th>\n",
|
| 250 |
+
" <td>2025-01-04 00:00:00+00:00</td>\n",
|
| 251 |
+
" <td>bitcoin</td>\n",
|
| 252 |
+
" <td>93779.257812</td>\n",
|
| 253 |
+
" </tr>\n",
|
| 254 |
+
" <tr>\n",
|
| 255 |
+
" <th>4</th>\n",
|
| 256 |
+
" <td>2025-01-05 00:00:00+00:00</td>\n",
|
| 257 |
+
" <td>bitcoin</td>\n",
|
| 258 |
+
" <td>93857.195312</td>\n",
|
| 259 |
+
" </tr>\n",
|
| 260 |
+
" <tr>\n",
|
| 261 |
+
" <th>5</th>\n",
|
| 262 |
+
" <td>2025-01-06 00:00:00+00:00</td>\n",
|
| 263 |
+
" <td>bitcoin</td>\n",
|
| 264 |
+
" <td>93959.531250</td>\n",
|
| 265 |
+
" </tr>\n",
|
| 266 |
+
" <tr>\n",
|
| 267 |
+
" <th>6</th>\n",
|
| 268 |
+
" <td>2025-01-07 00:00:00+00:00</td>\n",
|
| 269 |
+
" <td>bitcoin</td>\n",
|
| 270 |
+
" <td>94230.304688</td>\n",
|
| 271 |
+
" </tr>\n",
|
| 272 |
+
" <tr>\n",
|
| 273 |
+
" <th>7</th>\n",
|
| 274 |
+
" <td>2025-01-08 00:00:00+00:00</td>\n",
|
| 275 |
+
" <td>bitcoin</td>\n",
|
| 276 |
+
" <td>94447.601562</td>\n",
|
| 277 |
+
" </tr>\n",
|
| 278 |
+
" <tr>\n",
|
| 279 |
+
" <th>8</th>\n",
|
| 280 |
+
" <td>2025-01-09 00:00:00+00:00</td>\n",
|
| 281 |
+
" <td>bitcoin</td>\n",
|
| 282 |
+
" <td>94440.648438</td>\n",
|
| 283 |
+
" </tr>\n",
|
| 284 |
+
" <tr>\n",
|
| 285 |
+
" <th>9</th>\n",
|
| 286 |
+
" <td>2025-01-10 00:00:00+00:00</td>\n",
|
| 287 |
+
" <td>bitcoin</td>\n",
|
| 288 |
+
" <td>94379.914062</td>\n",
|
| 289 |
+
" </tr>\n",
|
| 290 |
+
" </tbody>\n",
|
| 291 |
+
"</table>\n",
|
| 292 |
+
"</div>"
|
| 293 |
+
],
|
| 294 |
+
"text/plain": [
|
| 295 |
+
" ds unique_id yhat\n",
|
| 296 |
+
"0 2025-01-01 00:00:00+00:00 bitcoin 93821.898438\n",
|
| 297 |
+
"1 2025-01-02 00:00:00+00:00 bitcoin 93758.367188\n",
|
| 298 |
+
"2 2025-01-03 00:00:00+00:00 bitcoin 93707.375000\n",
|
| 299 |
+
"3 2025-01-04 00:00:00+00:00 bitcoin 93779.257812\n",
|
| 300 |
+
"4 2025-01-05 00:00:00+00:00 bitcoin 93857.195312\n",
|
| 301 |
+
"5 2025-01-06 00:00:00+00:00 bitcoin 93959.531250\n",
|
| 302 |
+
"6 2025-01-07 00:00:00+00:00 bitcoin 94230.304688\n",
|
| 303 |
+
"7 2025-01-08 00:00:00+00:00 bitcoin 94447.601562\n",
|
| 304 |
+
"8 2025-01-09 00:00:00+00:00 bitcoin 94440.648438\n",
|
| 305 |
+
"9 2025-01-10 00:00:00+00:00 bitcoin 94379.914062"
|
| 306 |
+
]
|
| 307 |
+
},
|
| 308 |
+
"execution_count": 59,
|
| 309 |
+
"metadata": {},
|
| 310 |
+
"output_type": "execute_result"
|
| 311 |
+
}
|
| 312 |
+
],
|
| 313 |
+
"source": [
|
| 314 |
+
"forecast"
|
| 315 |
+
]
|
| 316 |
+
},
|
| 317 |
+
{
|
| 318 |
+
"cell_type": "code",
|
| 319 |
+
"execution_count": null,
|
| 320 |
+
"metadata": {},
|
| 321 |
+
"outputs": [],
|
| 322 |
+
"source": []
|
| 323 |
+
}
|
| 324 |
+
],
|
| 325 |
+
"metadata": {
|
| 326 |
+
"kernelspec": {
|
| 327 |
+
"display_name": "tsfm",
|
| 328 |
+
"language": "python",
|
| 329 |
+
"name": "python3"
|
| 330 |
+
},
|
| 331 |
+
"language_info": {
|
| 332 |
+
"codemirror_mode": {
|
| 333 |
+
"name": "ipython",
|
| 334 |
+
"version": 3
|
| 335 |
+
},
|
| 336 |
+
"file_extension": ".py",
|
| 337 |
+
"mimetype": "text/x-python",
|
| 338 |
+
"name": "python",
|
| 339 |
+
"nbconvert_exporter": "python",
|
| 340 |
+
"pygments_lexer": "ipython3",
|
| 341 |
+
"version": "3.11.13"
|
| 342 |
+
}
|
| 343 |
+
},
|
| 344 |
+
"nbformat": 4,
|
| 345 |
+
"nbformat_minor": 2
|
| 346 |
+
}
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==2.3.0
|
| 2 |
+
pandas==2.3.0
|
| 3 |
+
yfinance==0.2.62
|
| 4 |
+
timesfm==1.2.9
|
| 5 |
+
jax==0.6.1
|
| 6 |
+
torch==2.7.1
|
| 7 |
+
plotly==6.1.2
|
src/app.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import plotly.express as px
|
| 4 |
+
from model import get_model
|
| 5 |
+
from utils import get_bitcoin_history_yf, process_dataframe, predict_timesfm
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
st.title("Foundational Models para Series de Tiempo", anchor=None, help=None)
|
| 9 |
+
st.header("Creado por: Sebastian Sarasti", divider="gray")
|
| 10 |
+
st.markdown("More about me: [LinkedIn](https://www.linkedin.com/in/sebastiansarasti/)")
|
| 11 |
+
st.markdown("**Conferencia:** Universidad de Palermo")
|
| 12 |
+
|
| 13 |
+
st.markdown("Esta aplicación permite explorar modelos de series de tiempo utilizando modelos fundacionales basados en Transformers. El modelo fundacional seleccionado es TimesFM, fue desarrollado por Google. ")
|
| 14 |
+
|
| 15 |
+
st.markdown("**¿Cómo funciona?**")
|
| 16 |
+
|
| 17 |
+
st.markdown("1. **Selecciona las fechas**: Elige el rango de fechas para el cual deseas predecir los precios de Bitcoin.")
|
| 18 |
+
st.markdown("2. **Selecciona la ventana de forecast**: Permite configurar el modelo para predecir el horizonte de tiempo deseado.")
|
| 19 |
+
st.markdown("3. **Ejecuta el modelo**: Haz clic en el botón para ejecutar el modelo y obtener las predicciones.")
|
| 20 |
+
|
| 21 |
+
# create two columns for start date and end date
|
| 22 |
+
col1, col2 = st.columns(2)
|
| 23 |
+
with col1:
|
| 24 |
+
start_date = st.date_input("Fecha de Inicio", value="2025-01-31")
|
| 25 |
+
|
| 26 |
+
with col2:
|
| 27 |
+
end_date = st.date_input("Fecha de Fin", value="2025-06-10")
|
| 28 |
+
|
| 29 |
+
# create a slider for forecast horizon
|
| 30 |
+
forecast_horizon = st.slider(
|
| 31 |
+
"Ventana de Forecast",
|
| 32 |
+
min_value=1,
|
| 33 |
+
max_value=365,
|
| 34 |
+
value=st.session_state.get("forecast_horizon", 30),
|
| 35 |
+
help="Selecciona el horizonte de tiempo para las predicciones (en días)."
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# create a button to run the model
|
| 39 |
+
value = st.button("Ejecutar Modelo")
|
| 40 |
+
|
| 41 |
+
# ... después del botón "Ejecutar Modelo"
|
| 42 |
+
if value:
|
| 43 |
+
assert start_date < end_date, "La fecha de inicio debe ser anterior a la fecha de fin."
|
| 44 |
+
assert forecast_horizon > 0, "La ventana de forecast debe ser mayor a 0."
|
| 45 |
+
|
| 46 |
+
with st.spinner("Descargando datos ..."):
|
| 47 |
+
df = get_bitcoin_history_yf(start_date, end_date)
|
| 48 |
+
df = process_dataframe(df)
|
| 49 |
+
st.session_state["df"] = df
|
| 50 |
+
|
| 51 |
+
with st.spinner("Ejecutando modelo ..."):
|
| 52 |
+
model = get_model(forecast_horizon)
|
| 53 |
+
forecast_df = predict_timesfm(df=df, model=model)
|
| 54 |
+
forecast_df["type"] = "Forecast"
|
| 55 |
+
st.session_state["forecast_df"] = forecast_df
|
| 56 |
+
|
| 57 |
+
# nuevo botón separado
|
| 58 |
+
if "forecast_df" in st.session_state and st.button("Graficar Predicciones"):
|
| 59 |
+
df = st.session_state["df"]
|
| 60 |
+
forecast_df = st.session_state["forecast_df"]
|
| 61 |
+
df["type"] = "Historia"
|
| 62 |
+
df_final = pd.concat([df, forecast_df], ignore_index=True)
|
| 63 |
+
fig = px.line(
|
| 64 |
+
df_final,
|
| 65 |
+
x="ds",
|
| 66 |
+
y="y",
|
| 67 |
+
color="type",
|
| 68 |
+
title="Predicciones de Bitcoin con TimesFM",
|
| 69 |
+
labels={"ds": "Fecha", "y": "Precio (USD)", "type": "Tipo"},
|
| 70 |
+
)
|
| 71 |
+
st.plotly_chart(fig)
|
src/model.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import timesfm
|
| 2 |
+
|
| 3 |
+
def get_model(forecast_horizon):
|
| 4 |
+
"""
|
| 5 |
+
This function initializes and returns a TimesFM model for forecasting.
|
| 6 |
+
|
| 7 |
+
Args:
|
| 8 |
+
forecast_horizon (int): The number of time steps to forecast.
|
| 9 |
+
|
| 10 |
+
Returns:
|
| 11 |
+
TimesFM: An instance of the TimesFM model configured for the specified forecast horizon.
|
| 12 |
+
"""
|
| 13 |
+
model = timesfm.TimesFm(
|
| 14 |
+
hparams=timesfm.TimesFmHparams(
|
| 15 |
+
backend="cpu",
|
| 16 |
+
per_core_batch_size=32,
|
| 17 |
+
horizon_len=forecast_horizon,
|
| 18 |
+
num_layers=50,
|
| 19 |
+
use_positional_embedding=False,
|
| 20 |
+
context_len=2048,
|
| 21 |
+
),
|
| 22 |
+
checkpoint=timesfm.TimesFmCheckpoint(
|
| 23 |
+
huggingface_repo_id="google/timesfm-2.0-500m-pytorch"),
|
| 24 |
+
)
|
| 25 |
+
return model
|
src/utils.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yfinance as yf
|
| 2 |
+
import pandas as pd
|
| 3 |
+
|
| 4 |
+
def get_bitcoin_history_yf(start_date, end_date):
|
| 5 |
+
"""
|
| 6 |
+
This function fetches the historical price data for Bitcoin (BTC) using the yfinance library.
|
| 7 |
+
|
| 8 |
+
Args:
|
| 9 |
+
start_date (str): The start date for fetching historical data in 'YYYY-MM-DD' format.
|
| 10 |
+
end_date (str): The end date for fetching historical data in 'YYYY-MM-DD'
|
| 11 |
+
|
| 12 |
+
Returns:
|
| 13 |
+
pandas.DataFrame: A DataFrame containing the date and closing price of Bitcoin.
|
| 14 |
+
"""
|
| 15 |
+
btc = yf.Ticker("BTC-USD")
|
| 16 |
+
hist = btc.history(start=start_date, end=end_date)
|
| 17 |
+
return hist.reset_index()[["Date", "Close"]].rename(columns={"Date": "date", "Close": "price"})
|
| 18 |
+
|
| 19 |
+
def process_dataframe(df):
|
| 20 |
+
"""
|
| 21 |
+
This function processes the DataFrame to prepare it for forecasting.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
df (pandas.DataFrame): The input DataFrame containing the historical data.
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
pandas.DataFrame: A processed DataFrame with columns 'ds', 'y', and 'unique_id'.
|
| 28 |
+
"""
|
| 29 |
+
df = df.rename(
|
| 30 |
+
columns={
|
| 31 |
+
"date": "ds",
|
| 32 |
+
"price": "y"
|
| 33 |
+
}
|
| 34 |
+
)
|
| 35 |
+
df['ds'] = pd.to_datetime(df['ds'])
|
| 36 |
+
df['unique_id'] = "bitcoin"
|
| 37 |
+
return df
|
| 38 |
+
|
| 39 |
+
def predict_timesfm(df, model):
|
| 40 |
+
"""
|
| 41 |
+
Makes predictions using a trained TimesFM model on the provided DataFrame.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
|
| 45 |
+
df (pandas.DataFrame): The input DataFrame containing the data to be forecasted.
|
| 46 |
+
model (TimesFM): A trained TimesFM model for forecasting.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
pandas.DataFrame: A DataFrame containing the forecasted values with columns 'ds', 'unique_id', and 'yhat'.
|
| 50 |
+
"""
|
| 51 |
+
forecast_df = model.forecast_on_df(
|
| 52 |
+
inputs=df,
|
| 53 |
+
freq="D", # monthly
|
| 54 |
+
value_name="y",
|
| 55 |
+
num_jobs=2,
|
| 56 |
+
)
|
| 57 |
+
forecast_df = forecast_df[['ds', 'unique_id', 'timesfm']]
|
| 58 |
+
forecast_df = forecast_df.rename(
|
| 59 |
+
columns={
|
| 60 |
+
"timesfm": "y"
|
| 61 |
+
}
|
| 62 |
+
)
|
| 63 |
+
return forecast_df
|