Communitygithub.com

timesfm-forecasting

Zero-Shot-Zeitreihenprognose mit Google

Was ist timesfm-forecasting?

Dieses Skill kapselt das TimesFM-Modell (Time Series Foundation Model) von Google Research für sichere, agentenfreundliche lokale Inferenz. Es ermöglicht Zero-Shot-Prognosen für beliebige univariate Zeitreihen – ohne Training. Das Skill enthält einen obligatorischen Preflight-System-Checker, der RAM, GPU-Speicher und Festplattenplatz prüft, bevor das Modell geladen wird, um Systemabstürze zu vermeiden. Es unterstützt sowohl probabilistische Prognosen mit kalibrierten Quantil-Intervallen als auch Batch-Prognosen für Hunderte von Serien. Das Skill ist für Claude Code, Cursor und Codex optimiert und bietet eine klare Trennung zwischen Modellinferenz und Systemvoraussetzungen.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/timesfm-forecasting

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

TimesFM-Prognose

Überblick

TimesFM (Time Series Foundation Model) ist ein vortrainiertes, Decoder-only Foundation Model, das von Google Research für Zeitreihenprognosen entwickelt wurde. Es funktioniert Zero-Shot – füttere es mit einer beliebigen univariaten Zeitreihe und es gibt Punktprognosen mit kalibrierten Quantil-Vorhersageintervallen zurück, ohne dass ein Training erforderlich ist.

Dieses Skill kapselt TimesFM für eine sichere, agentenfreundliche lokale Inferenz. Es enthält einen obligatorischen Preflight-System-Checker, der RAM, GPU-Speicher und Festplattenplatz überprüft, bevor das Modell jemals geladen wird, sodass der Agent niemals den Rechner des Benutzers zum Absturz bringt.

Wichtige Zahlen: TimesFM 2.5 verwendet 200 Millionen Parameter (~800 MB auf der Festplatte, ~1,5 GB RAM auf der CPU, ~1 GB VRAM auf der GPU). Das archivierte v1/v2 500M-Parameter-Modell benötigt ~32 GB RAM. Führe immer zuerst den System-Checker aus.

Wann dieses Skill verwendet werden sollte

Verwende dieses Skill, wenn:

  • Prognosen für beliebige univariate Zeitreihen (Verkauf, Nachfrage, Sensor, Vitaldaten, Preis, Wetter) benötigt werden
  • Zero-Shot-Prognosen ohne Training eines benutzerdefinierten Modells erforderlich sind
  • Probabilistische Prognosen mit kalibrierten Vorhersageintervallen (Quantilen) gewünscht werden
  • Zeitreihen beliebiger Länge vorliegen (das Modell verarbeitet 1–16.384 Kontextpunkte)
  • Hunderte oder Tausende von Serien effizient als Batch prognostiziert werden müssen
  • Ein Foundation-Model-Ansatz anstelle von manuell abgestimmten ARIMA/ETS-Parametern bevorzugt wird

Verwende dieses Skill nicht, wenn:

  • Klassische statistische Modelle mit Koeffizienteninterpretation benötigt werden → verwende statsmodels
  • Zeitreihenklassifikation oder -clustering benötigt wird → verwende aeon
  • Multivariate Vektorautoregression oder Granger-Kausalität benötigt wird → verwende statsmodels
  • Die Daten tabellarisch (nicht zeitlich) sind → verwende scikit-learn

Hinweis zur Anomalieerkennung: TimesFM hat keine integrierte Anomalieerkennung, aber du kannst die Quantil-Prognosen als Vorhersageintervalle verwenden – Werte außerhalb des 90%-KI (q10–q90) sind statistisch ungewöhnlich. Siehe das Verzeichnis examples/anomaly-detection/ für ein vollständiges Beispiel.

⚠️ Obligatorischer Preflight: Systemanforderungsprüfung

KRITISCH – Führe IMMER den System-Checker aus, bevor das Modell zum ersten Mal geladen wird.

python scripts/check_system.py

Dieses Skript prüft:

  1. Verfügbarer RAM – warnt, wenn unter 4 GB, blockiert, wenn unter 2 GB
  2. GPU-Verfügbarkeit – erkennt CUDA/MPS-Geräte und VRAM
  3. Festplattenspeicher – überprüft ausreichend Platz für den ~800 MB Modell-Download
  4. Python-Version – erfordert 3.10+
  5. Vorhandene Installation – prüft, ob timesfm und torch installiert sind

Hinweis: Modellgewichte werden NICHT in diesem Repository gespeichert. TimesFM-Gewichte (~800 MB) werden bei der ersten Verwendung on-demand von HuggingFace heruntergeladen und in ~/.cache/huggingface/ zwischengespeichert. Der Preflight-Checker stellt sicher, dass ausreichende Ressourcen vorhanden sind, bevor ein Download beginnt.

flowchart TD
    accTitle: Preflight System Check
    accDescr: Entscheidungsflussdiagramm, das die Systemanforderungsprüfungen zeigt, die vor dem Laden von TimesFM bestanden werden müssen.

    start["🚀 Führe check_system.py aus"] --> ram{"RAM ≥ 4 GB?"}
    ram -->|"Ja"| gpu{"GPU verfügbar?"}
    ram -->|"Nein (2-4 GB)"| warn_ram["⚠️ Warnung: Knapper RAM<br/>Nur CPU, kleine Batches"]
    ram -->|"Nein (< 2 GB)"| block["🛑 GESPERRT<br/>Unzureichender Speicher"]
    warn_ram --> disk
    gpu -->|"CUDA / MPS"| vram{"VRAM ≥ 2 GB?"}
    gpu -->|"Nur CPU"| cpu_ok["✅ CPU-Modus<br/>Langsamer, aber funktionsfähig"]
    vram -->|"Ja"| gpu_ok["✅ GPU-Modus<br/>Schnelle Inferenz"]
    vram -->|"Nein"| cpu_ok
    gpu_ok --> disk{"Festplatte ≥ 2 GB frei?"}
    cpu_ok --> disk
    disk -->|"Ja"| ready["✅ BEREIT<br/>Sicheres Laden des Modells"]
    disk -->|"Nein"| block_disk["🛑 GESPERRT<br/>Speicherplatz für Gewichte benötigt"]

    classDef ok fill:#dcfce7,stroke:#16a34a,stroke-width:2px,color:#14532d
    classDef warn fill:#fef9c3,stroke:#ca8a04,stroke-width:2px,color:#713f12
    classDef block fill:#fee2e2,stroke:#dc2626,stroke-width:2px,color:#7f1d1d
    classDef neutral fill:#f3f4f6,stroke:#6b7280,stroke-width:2px,color:#1f2937

    class ready,gpu_ok,cpu_ok ok
    class warn_ram warn
    class block,block_disk block
    class start,ram,gpu,vram,disk neutral

Hardware-Anforderungen nach Modellversion

ModellParameterRAM (CPU)VRAM (GPU)FestplatteKontext
TimesFM 2.5 (empfohlen)200M≥ 4 GB≥ 2 GB~800 MBbis zu 16.384
TimesFM 2.0 (archiviert)500M≥ 16 GB≥ 8 GB~2 GBbis zu 2.048
TimesFM 1.0 (archiviert)200M≥ 8 GB≥ 4 GB~800 MBbis zu 2.048

Empfehlung: Verwende immer TimesFM 2.5, es sei denn, du hast einen bestimmten Grund, einen älteren Checkpoint zu verwenden. Es ist kleiner, schneller und unterstützt 8× längeren Kontext.

🔧 Installation

Schritt 1: System überprüfen (immer zuerst)

python scripts/check_system.py

Schritt 2: TimesFM installieren

# Mit uv (von diesem Repository empfohlen)
uv pip install timesfm[torch]

# Für JAX/Flax-Backend (schneller auf TPU/GPU)
uv pip install timesfm[flax]

Schritt 3: PyTorch für deine Hardware installieren

# CUDA 12.1 (NVIDIA GPU)
uv pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cu121

# Nur CPU
uv pip install torch>=2.0.0 --index-url https://download.pytorch.org/whl/cpu

# Apple Silicon (MPS)
uv pip install torch>=2.0.0  # MPS-Unterstützung ist integriert

Schritt 4: Installation überprüfen

import timesfm
import numpy as np
print(f"TimesFM-Version: {timesfm.__version__}")
print("Installation OK")

🎯 Schnellstart

Minimalbeispiel (5 Zeilen)

import torch, numpy as np, timesfm

torch.set_float32_matmul_precision("high")

model = timesfm.TimesFM_2p5_200M_torch.from_pretrained(
    "google/timesfm-2.5-200m-pytorch"
)
model.compile(timesfm.ForecastConfig(
    max_context=1024, max_horizon=256, normalize_inputs=True,
    use_continuous_quantile_head=True, force_flip_invariance=True,
    infer_is_positive=True, fix_quantile_crossing=True,
))

point, quantiles = model.forecast(horizon=24, inputs=[
    np.sin(np.linspace(0, 20, 200)),  # beliebiges 1-D-Array
])
# point.shape == (1, 24)        — Median-Prognose
# quantiles.shape == (1, 24, 10) — 10. bis 90. Perzentil-Bänder

Prognose aus einer CSV

import pandas as pd, numpy as np

df = pd.read_csv("monthly_sales.csv", parse_dates=["date"], index_col="date")

# Jede Spalte in eine Liste von Arrays konvertieren
inputs = [df[col].dropna().values.astype(np.float32) for col in df.columns]

point, quantiles = model.forecast(horizon=12, inputs=inputs)

# Ergebnis-DataFrame erstellen
for i, col in enumerate(df.columns):
    last_date = df[col].dropna().index[-1]
    future_dates = pd.date_range(last_date, periods=13, freq="MS")[1:]
    forecast_df = pd.DataFrame({
        "date": future_dates,
        "forecast": point[i],
        "lower_80": quantiles[i, :, 2],  # 20. Perzentil
        "upper_80": quantiles[i, :, 8],  # 80. Perzentil
    })
    print(f"\n--- {col} ---")
    print(forecast_df.to_string(index=False))

Prognose mit Kovariaten (XReg)

TimesFM 2.5+ unterstützt exogene Variablen über forecast_with_covariates(). Erfordert timesfm[xreg].

# Erfordert: uv pip install timesfm[xreg]
point, quantiles = model.forecast_with_covariates(
    inputs=inputs,
    dynamic_numerical_covariates={"price": price_arrays},
    dynamic_categorical_covariates={"holiday": holiday_arrays},
    static_categorical_covariates={"region": region_labels},
    xreg_mode="xreg + timesfm",  # oder "timesfm + xreg"
)
KovariatentypBeschreibungBeispiel
dynamic_numericalZeitvariierende numerischePreis, Temperatur, Werbeausgaben
dynamic_categoricalZeitvariierende kategorialeFeiertagsflagge, Wochentag
static_numericalPro-Serie numerischeFilialgröße, Kontosaldo
static_categoricalPro-Serie kategorialeFilialtyp, Region, Produktkategorie

XReg-Modi:

  • "xreg + timesfm" (Standard): TimesFM prognostiziert zuerst, dann passt XReg die Residuen an
  • "timesfm + xreg": XReg passt zuerst, dann prognostiziert TimesFM die Residuen

Siehe examples/covariates-forecasting/ für ein vollständiges Beispiel mit synthetischen Einzelhandelsdaten.

Anomalieerkennung (über Quantilintervalle)

TimesFM hat keine integrierte Anomalieerkennung, aber die Quantil-Prognosen liefern auf natürliche Weise Vorhersageintervalle, die Anomalien erkennen können:

point, q = model.forecast(horizon=H, inputs=[values])

# 90%-Vorhersageintervall
lower_90 = q[0, :, 1]  # 10. Perzentil
upper_90 = q[0, :, 9]  # 90. Perzentil

# Anomalien erkennen: Werte außerhalb des 90%-KI
actual = test_values  # deine Holdout-Daten
anomalies = (actual < lower_90) | (actual > upper_90)

# Schweregrade
is_warning = (actual < q[0, :, 2]) | (actual > q[0, :, 8])  # außerhalb des 80%-KI
is_critical = anomalies  # außerhalb des 90%-KI
SchweregradBedingungInterpretation
NormalInnerhalb des 80%-KIErwartetes Verhalten
WarnungAußerhalb des 80%-KIUngewöhnlich, aber möglich
KritischAußerhalb des 90%-KIStatistisch selten (< 10% Wahrscheinlichkeit)

Siehe examples/anomaly-detection/ für ein vollständiges Beispiel mit Visualisierung.

# Erfordert: uv pip install timesfm[xreg]
point, quantiles = model.forecast_with_covariates(
    inputs=inputs,
    dynamic_numerical_covariates={"temperature": temp_arrays},
    dynamic_categorical_covariates={"day_of_week": dow_arrays},
    static_categorical_covariates={"region": region_labels},
    xreg_mode="xreg + timesfm",  # oder "timesfm + xreg"
)

Ausgabe, Konfiguration, Arbeitsabläufe und Optimierung

🔗 Integration mit anderen Skills

Mit statsmodels

Verwende statsmodels für klassische Modelle (ARIMA, SARIMAX) als Vergleichsbasis:

# TimesFM-Prognose
tfm_point, tfm_q = model.forecast(horizon=H, inputs=[values])

# statsmodels ARIMA-Prognose
from statsmodels.tsa.arima.model import ARIMA
arima = ARIMA(values, order=(1,1,1)).fit()
arima_forecast = arima.forecast(steps=H)

# Vergleiche
print(f"TimesFM MAE: {np.mean(np.abs(actual - tfm_point[0])):.2f}")
print(f"ARIMA MAE:   {np.mean(np.abs(actual - arima_forecast)):.2f}")

Mit matplotlib / scientific-visualization

Erstelle publikationsreife Grafiken von Prognosen mit Vorhersageintervallen.

Mit exploratory-data-analysis

Führe vor der Prognose eine explorative Datenanalyse der Zeitreihe durch, um Trends, Saisonalität und Stationarität zu verstehen.

📚 Verfügbare Skripte

scripts/check_system.py

Obligatorischer Preflight-Checker. Vor dem ersten Modellladen ausführen.

python scripts/check_system.py

Beispielausgabe:

=== TimesFM System Requirements Check ===

[RAM]       Gesamt: 32.0 GB | Verfügbar: 24.3 GB  ✅ BESTANDEN
[GPU]       NVIDIA RTX 4090 | VRAM: 24.0 GB      ✅ BESTANDEN
[Festplatte] Frei: 142.5 GB                       ✅ BESTANDEN
[Python]    3.12.1                                 ✅ BESTANDEN
[timesfm]   Installiert (2.5.0)                    ✅ BESTANDEN
[torch]     Installiert (2.4.1+cu121)              ✅ BESTANDEN

URTEIL: ✅ System ist bereit für TimesFM 2.5 (GPU-Modus)
Empfohlen: per_core_batch_size=128

scripts/forecast_csv.py

End-to-End-CSV-Prognose mit automatischem Systemcheck.

python scripts/forecast_csv.py input.csv \
    --horizon 24 \
    --date-col date \
    --value-cols sales,revenue \
    --output forecasts.csv

📖 Referenzdokumentation

Ausführliche Anleitungen in references/:

DateiInhalt
references/system_requirements.mdHardware-Stufen, GPU/CPU-Auswahl, Speicherschätzformeln
references/api_reference.mdVollständige ForecastConfig-Dokumentation, from_pretrained-Optionen, Ausgabeformen
references/data_preparation.mdEingabeformate, NaN-Behandlung, CSV-Laden, Kovariateneinrichtung

Häufige Fallstricke

  1. Systemcheck nicht ausgeführt → Modellladen stürzt auf Maschinen mit wenig RAM ab. Führe immer zuerst check_system.py aus.
  2. model.compile() vergessen → RuntimeError: Model is not compiled. Vor forecast() muss compile() aufgerufen werden.
  3. normalize_inputs=True nicht gesetzt → instabile Prognosen für Serien mit großen Werten.
  4. Verwendung von v1/v2 auf Maschinen mit < 32 GB RAM → stattdessen TimesFM 2.5 (200M Parameter) verwenden.
  5. fix_quantile_crossing=True nicht gesetzt → Quantile sind möglicherweise nicht monoton (q10 > q50).
  6. Große per_core_batch_size auf kleiner GPU → CUDA OOM. Klein anfangen, steigern.
  7. 2-D-Arrays übergeben → TimesFM erwartet eine Liste von 1-D-Arrays, keine 2-D-Matrix.
  8. torch.set_float32_matmul_precision("high") vergessen → langsamere Inferenz auf Ampere+ GPUs.
  9. NaN in der Ausgabe nicht behandelt → Grenzfälle mit sehr kurzen Serien. Immer np.isnan(point).any() prüfen.
  10. infer_is_positive=True für Serien, die negativ sein können → klemmt Prognosen auf Null. Setze False für Temperatur, Renditen usw.

Modellversionen

timeline
    accTitle: TimesFM Versionsverlauf
    accDescr: Zeitleiste der TimesFM-Modellveröffentlichungen mit Parameteranzahl und wichtigsten Verbesserungen.

    section 2024
        TimesFM 1.0 : 200M Parameter, 2K Kontext, nur JAX
        TimesFM 2.0 : 500M Parameter, 2K Kontext, PyTorch + JAX
    section 2025
        TimesFM 2.5 : 200M Parameter, 16K Kontext, Quantilkopf, kein Frequenzindikator
VersionParameterKontextQuantilkopfFrequenz-FlagStatus
2.5200M16.384✅❌Aktuell
2.0500M2.048❌✅Archiviert
1.0200M2.048❌✅Archiviert

Weitere Informationen findest du in references/system_requirements.md.

📄 Lizenz

Dieses Skill enthält den Code aus dem offiziellen Google TimesFM Repository, das unter der Apache License 2.0 lizenziert ist.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

Verwandte Skills