Files
workspace/apps/timesfm-forecast/README.md

153 lines
4.5 KiB
Markdown
Executable File
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# TimesFM Forecast (Streamlit, OOP)
A maintainable, OOP-based Streamlit app to forecast multiple time series (by `key`) using **TimesFM**.
- Upload CSV with columns: `date`, `value`, `key`
- Select a **horizon range** (e.g., 112)
- App uses **all data as training** (no holdout)
- **Progress bar** while forecasting
- **Download** CSV with forecasts (`key, date, step, forecast`)
- Clean separation between UI and core logic
---
## 🚀 Quickstart (using `uv`)
> Requires Python **3.10+**.
> `uv` docs: https://docs.astral.sh/uv/
```bash
# 1) Clone
# (If you already downloaded this folder locally, cd into it and skip clone.)
# git clone https://github.com/<your-org>/timesfm-forecast.git
cd timesfm-forecast
# 2) Create a virtualenv (managed by uv)
uv venv
source .venv/bin/activate # Windows: .venv\Scriptsctivate
# 3) Install dependencies (editable mode)
uv pip install -e .
# 4) Run the app
uv run timesfm-app
# or directly:
# uv run streamlit run src/timesfm_app/ui/app.py
```
Open the URL shown in your terminal (typically http://localhost:8501).
---
## 📦 CSV Format
Upload a CSV with **columns**:
- `date` a date per observation (the app prefers `dd/mm/yyyy`, but will try general parsing)
- `value` numeric target
- `key` series identifier (one forecast per `key`)
Example: [examples/sample.csv](examples/sample.csv)
---
## ⚙️ Configuration (in the UI)
- **TimesFM model**: defaults to `google/timesfm-2.0-500m-pytorch`
- **Device**: `cuda` if available, otherwise `cpu`
- **Frequency code (TimesFM)**: defaults to **2 = monthly** (matches your original draft)
- **Fallback pandas frequency**: used to create future dates if per-key inference fails (`D,W,M,Q,Y`)
- **Batch size**: controls throughput vs memory
- **Horizon range**: inclusive range (e.g., 1..12). Output includes each step with its aligned date.
> The app uses `pandas.infer_freq` to detect per-key frequency; if inference fails, it falls back to your selection.
---
## 🧠 Design / OOP
- `TimesFMService` encapsulates model loading + batch inference.
- `ForecastPipeline` orchestrates validation, batching, inference, and future index construction. Returns a **long** DataFrame:
- `key, date, step, forecast`
- `DataValidator` / `FrequencyHelper` stateless utility classes.
- `ui/app.py` Streamlit-only, thin UI.
This structure makes it straightforward to add more backends (e.g., Prophet, Chronos) by introducing a new service class.
---
## 🧪 Tests
Install dev extras and run:
```bash
uv pip install -e ".[dev]"
uv run pytest
```
We provide a minimal test (`tests/test_pipeline.py`) that injects a **fake service** to validate pipeline behavior without loading a real model.
---
## 🖥️ GPU vs CPU (PyTorch)
By default, this project depends on `torch` without a pinned wheel. If you need a **CUDA** build, install the wheel for your CUDA version. Examples:
```bash
# CUDA 12.1 (example)
uv pip install torch --index-url https://download.pytorch.org/whl/cu121
# CPU-only (explicit)
uv pip install torch --index-url https://download.pytorch.org/whl/cpu
```
Then run the app and select **Device = cuda** in the sidebar. Make sure your NVIDIA drivers & CUDA runtime match the wheel.
---
## 📝 Output
You can download a CSV with columns:
- `key` series id
- `date` predicted timestamp (aligned to step)
- `step` horizon (1..H)
- `forecast` mean prediction
---
## 🧯 Troubleshooting
- **Model download slow / blocked**: the first run downloads the model weights from Hugging Face. Ensure internet connectivity and retry. You can also pre-download the model to your HF cache.
- **Out-of-memory on GPU**: reduce `Batch size`, or switch **Device** to `cpu`.
- **Dates misaligned**: pick the correct fallback pandas frequency (e.g., `M` for monthly) if your data has irregular gaps that prevent inference.
---
## 📸 UI Preview (Screenshots)
A quick visual tour of the Streamlit app — settings, upload, forecasting, preview, and visualization.
- **App Home + Settings Sidebar**
Shows the TimesFM configuration, frequency settings, batch size and horizon range.
![App home](examples/ui-1-home.png)
- **CSV Upload Modal**
Preview of the uploaded dataset before running the forecast.
![Upload modal](examples/ui-2-upload.png)
- **Forecast Preview (Long Format)**
First rows of the generated forecast output (key, date, step, forecast).
![Forecast preview](examples/ui-3-forecast-preview.png)
- **Single-Key Visualization**
Historical series + forecast plotted for a chosen key.
![Visualization](examples/ui-4-visualization.png)
---
## 📄 License
MIT
---