Communitygithub.com

timesfm-forecasting

Google의 제로샷 시계열 예측 도구

timesfm-forecasting란 무엇인가요?

이 스킬은 Google Research에서 개발한 시계열 기초 모델(Time Series Foundation Model)인 TimesFM을 에이전트 친화적인 환경에서 안전하게 로컬 추론할 수 있도록 래핑한 것입니다. TimesFM은 제로샷 방식으로 작동하여, 사용자가 별도의 학습 없이도 단변량 시계열 데이터를 입력하면 보정된 분위수 예측 구간과 함께 점 예측을 반환합니다. 이 스킬은 모델을 로드하기 전에 반드시 실행해야 하는 시스템 사전 점검 스크립트를 포함하여, 에이전트가 사용자의 머신에 과부하를 주는 상황을 방지합니다. Claude Code, Cursor, Codex 등 다양한 AI 에이전트 플랫폼에서 사용할 수 있으며, 판매, 수요, 센서 데이터, 가격, 날씨 등 다양한 단변량 시계열 예측 작업에 활용 가능합니다. 특히 기존의 ARIMA/ETS 모델을 수동으로 튜닝하지 않고도 기초 모델 기반의 확률론적 예측이 필요한 경우에 적합합니다.

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

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

TimesFM Forecasting

개요

TimesFM(Time Series Foundation Model)은 Google Research에서 개발한 시계열 예측용 사전 학습된 디코더 전용 기초 모델입니다. 제로샷(zero-shot) 으로 동작하여, 단변량 시계열을 입력하면 학습 없이 보정된 분위수 예측 구간과 함께 점 예측을 반환합니다.

이 스킬은 TimesFM을 안전하고 에이전트 친화적인 로컬 추론 환경으로 감쌉니다. 필수 시스템 사전 점검 기능이 포함되어 있어, 모델이 로드되기 전에 RAM, GPU 메모리, 디스크 공간을 확인하여 에이전트가 사용자의 머신을 다운시키는 일이 없도록 합니다.

핵심 수치: TimesFM 2.5는 2억 개의 파라미터를 사용합니다(디스크 약 800MB, CPU RAM 약 1.5GB, GPU VRAM 약 1GB). 보관된 v1/v2 5억 파라미터 모델은 약 32GB RAM이 필요합니다. 항상 시스템 점검을 먼저 실행하세요.

이 스킬을 사용해야 하는 경우

다음과 같은 경우에 이 스킬을 사용하세요:

  • 모든 단변량 시계열 예측(판매, 수요, 센서, 생체 신호, 가격, 날씨)
  • 사용자 정의 모델 학습 없이 제로샷 예측이 필요할 때
  • 보정된 예측 구간(분위수)을 포함한 확률론적 예측이 필요할 때
  • 모든 길이의 시계열(1~16,384개의 컨텍스트 포인트 처리 가능)
  • 수백, 수천 개의 시계열을 효율적으로 배치 예측해야 할 때
  • ARIMA/ETS 파라미터를 수동으로 튜닝하는 대신 기초 모델 방식을 원할 때

다음과 같은 경우에는 이 스킬을 사용하지 마세요:

  • 계수 해석이 가능한 고전적 통계 모델이 필요하다면 → statsmodels 사용
  • 시계열 분류 또는 클러스터링이 필요하다면 → aeon 사용
  • 다변량 벡터 자기회귀 또는 Granger 인과성이 필요하다면 → statsmodels 사용
  • 데이터가 시계열이 아닌 테이블 형식이라면 → scikit-learn 사용

이상 탐지 참고: TimesFM에는 내장된 이상 탐지 기능이 없지만, 분위수 예측을 예측 구간으로 사용할 수 있습니다. 90% 신뢰 구간(q10~q90) 밖의 값은 통계적으로 이상치입니다. 전체 예제는 examples/anomaly-detection/ 디렉토리를 참조하세요.

⚠️ 필수 사전 점검: 시스템 요구 사항 확인

중요 — 모델을 처음 로드하기 전에 항상 시스템 점검을 실행하세요.

python scripts/check_system.py

이 스크립트는 다음을 확인합니다:

  1. 사용 가능한 RAM — 4GB 미만이면 경고, 2GB 미만이면 차단
  2. GPU 가용성 — CUDA/MPS 장치 및 VRAM 감지
  3. 디스크 공간 — 약 800MB 모델 다운로드를 위한 공간 확인
  4. Python 버전 — 3.10+ 필요
  5. 기존 설치 — timesfm 및 torch 설치 여부 확인

참고: 모델 가중치는 이 저장소에 저장되지 않습니다. TimesFM 가중치(~800MB)는 첫 사용 시 HuggingFace에서 온디맨드로 다운로드되며 ~/.cache/huggingface/에 캐시됩니다. 사전 점검기는 다운로드가 시작되기 전에 충분한 리소스가 있는지 확인합니다.

flowchart TD
    accTitle: 사전 시스템 점검
    accDescr: TimesFM을 로드하기 전에 통과해야 하는 시스템 요구 사항 확인을 보여주는 의사 결정 흐름도.

    start["🚀 check_system.py 실행"] --> ram{"RAM ≥ 4 GB?"}
    ram -->|"예"| gpu{"GPU 사용 가능?"}
    ram -->|"아니오 (2-4 GB)"| warn_ram["⚠️ 경고: RAM 부족<br/>CPU 전용, 소규모 배치"]
    ram -->|"아니오 (< 2 GB)"| block["🛑 차단됨<br/>메모리 부족"]
    warn_ram --> disk
    gpu -->|"CUDA / MPS"| vram{"VRAM ≥ 2 GB?"}
    gpu -->|"CPU 전용"| cpu_ok["✅ CPU 모드<br/>느리지만 작동함"]
    vram -->|"예"| gpu_ok["✅ GPU 모드<br/>빠른 추론"]
    vram -->|"아니오"| cpu_ok
    gpu_ok --> disk{"디스크 ≥ 2 GB 여유?"}
    cpu_ok --> disk
    disk -->|"예"| ready["✅ 준비 완료<br/>모델 로드 안전"]
    disk -->|"아니오"| block_disk["🛑 차단됨<br/>가중치 저장 공간 필요"]

    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

모델 버전별 하드웨어 요구 사항

모델파라미터 수RAM (CPU)VRAM (GPU)디스크컨텍스트
TimesFM 2.5 (권장)200M≥ 4 GB≥ 2 GB~800 MB최대 16,384
TimesFM 2.0 (보관됨)500M≥ 16 GB≥ 8 GB~2 GB최대 2,048
TimesFM 1.0 (보관됨)200M≥ 8 GB≥ 4 GB~800 MB최대 2,048

권장 사항: 특별히 이전 체크포인트를 사용해야 하는 이유가 없다면 항상 TimesFM 2.5를 사용하세요. 더 작고 빠르며 8배 더 긴 컨텍스트를 지원합니다.

🔧 설치

1단계: 시스템 확인 (항상 먼저)

python scripts/check_system.py

2단계: TimesFM 설치

# uv 사용 (이 저장소 권장)
uv pip install timesfm[torch]

# JAX/Flax 백엔드 사용 (TPU/GPU에서 더 빠름)
uv pip install timesfm[flax]

3단계: 하드웨어에 맞는 PyTorch 설치

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

# 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 지원 내장

4단계: 설치 확인

import timesfm
import numpy as np
print(f"TimesFM 버전: {timesfm.__version__}")
print("설치 완료")

🎯 빠른 시작

최소 예제 (5줄)

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)),  # 모든 1-D 배열
])
# point.shape == (1, 24)        — 중간값 예측
# quantiles.shape == (1, 24, 10) — 10번째~90번째 백분위수 대역

CSV에서 예측하기

import pandas as pd, numpy as np

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

# 각 열을 배열 리스트로 변환
inputs = [df[col].dropna().values.astype(np.float32) for col in df.columns]

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

# 결과 DataFrame 생성
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번째 백분위수
        "upper_80": quantiles[i, :, 8],  # 80번째 백분위수
    })
    print(f"\n--- {col} ---")
    print(forecast_df.to_string(index=False))

공변량을 사용한 예측 (XReg)

TimesFM 2.5+는 forecast_with_covariates()를 통해 외생 변수를 지원합니다. timesfm[xreg]가 필요합니다.

# 필요: 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",  # 또는 "timesfm + xreg"
)
공변량 유형설명예시
dynamic_numerical시변 수치가격, 온도, 프로모션 비용
dynamic_categorical시변 범주형휴일 플래그, 요일
static_numerical계열별 수치매장 크기, 계정 연령
static_categorical계열별 범주형매장 유형, 지역, 제품 카테고리

XReg 모드:

  • "xreg + timesfm" (기본값): TimesFM이 먼저 예측한 후 XReg가 잔차를 조정합니다.
  • "timesfm + xreg": XReg가 먼저 적합된 후 TimesFM이 잔차를 예측합니다.

전체 예제는 examples/covariates-forecasting/ 디렉토리를 참조하세요(합성 소매 데이터 포함).

이상 탐지 (분위수 구간 활용)

TimesFM에는 내장된 이상 탐지 기능이 없지만, 분위수 예측이 자연스럽게 예측 구간을 제공하여 이상을 감지할 수 있습니다:

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

# 90% 예측 구간
lower_90 = q[0, :, 1]  # 10번째 백분위수
upper_90 = q[0, :, 9]  # 90번째 백분위수

# 이상 탐지: 90% CI 밖의 값
actual = test_values  # 홀드아웃 데이터
anomalies = (actual < lower_90) | (actual > upper_90)

# 심각도 수준
is_warning = (actual < q[0, :, 2]) | (actual > q[0, :, 8])  # 80% CI 밖
is_critical = anomalies  # 90% CI 밖
심각도조건해석
정상80% CI 내예상된 동작
경고80% CI 밖특이하지만 가능함
심각90% CI 밖통계적으로 드문 경우 (< 10% 확률)

전체 예제와 시각화는 examples/anomaly-detection/ 디렉토리를 참조하세요.

# 필요: 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",  # 또는 "timesfm + xreg"
)

출력, 구성, 워크플로우 및 튜닝

🔗 다른 스킬과의 통합

statsmodels와 함께 사용

비교 기준으로 고전적 모델(ARIMA, SARIMAX)에 statsmodels를 사용하세요:

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

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

# 비교
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}")

matplotlib / scientific-visualization와 함께 사용

예측 구간이 포함된 출판 품질의 그래프로 예측 결과를 시각화하세요.

exploratory-data-analysis와 함께 사용

예측 전에 시계열에 대한 탐색적 데이터 분석(EDA)을 수행하여 추세, 계절성, 정상성을 파악하세요.

📚 사용 가능한 스크립트

scripts/check_system.py

필수 사전 점검기. 모델을 처음 로드하기 전에 실행하세요.

python scripts/check_system.py

출력 예시:

=== TimesFM 시스템 요구 사항 확인 ===

[RAM]       총: 32.0 GB | 사용 가능: 24.3 GB  ✅ 통과
[GPU]       NVIDIA RTX 4090 | VRAM: 24.0 GB      ✅ 통과
[디스크]    여유: 142.5 GB                        ✅ 통과
[Python]    3.12.1                                 ✅ 통과
[timesfm]   설치됨 (2.5.0)                      ✅ 통과
[torch]     설치됨 (2.4.1+cu121)                ✅ 통과

판정: ✅ 시스템이 TimesFM 2.5 (GPU 모드) 사용 준비 완료
권장: per_core_batch_size=128

scripts/forecast_csv.py

자동 시스템 점검 기능이 포함된 엔드투엔드 CSV 예측.

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

📖 참조 문서

references/ 디렉토리의 상세 가이드:

파일내용
references/system_requirements.md하드웨어 계층, GPU/CPU 선택, 메모리 추정 공식
references/api_reference.md전체 ForecastConfig 문서, from_pretrained 옵션, 출력 형태
references/data_preparation.md입력 형식, NaN 처리, CSV 로딩, 공변량 설정

일반적인 실수

  1. 시스템 점검을 실행하지 않음 → 저 RAM 머신에서 모델 로드가 실패합니다. 항상 check_system.py를 먼저 실행하세요.
  2. model.compile()을 잊음 → RuntimeError: Model is not compiled. forecast() 전에 반드시 compile()을 호출해야 합니다.
  3. normalize_inputs=True를 설정하지 않음 → 큰 값을 가진 계열에 대해 불안정한 예측이 발생합니다.
  4. RAM 32GB 미만 머신에서 v1/v2 사용 → 대신 TimesFM 2.5 (200M 파라미터)를 사용하세요.
  5. fix_quantile_crossing=True를 설정하지 않음 → 분위수가 단조롭지 않을 수 있습니다(q10 > q50).
  6. 소형 GPU에서 과도하게 큰 per_core_batch_size → CUDA OOM 오류가 발생합니다. 작게 시작하여 늘리세요.
  7. 2차원 배열 전달 → TimesFM은 2차원 행렬이 아닌 1차원 배열의 리스트를 예상합니다.
  8. torch.set_float32_matmul_precision("high")를 잊음 → Ampere+ GPU에서 추론 속도가 느려집니다.
  9. 출력의 NaN을 처리하지 않음 → 매우 짧은 계열의 경우 가장자리 케이스가 발생합니다. 항상 np.isnan(point).any()를 확인하세요.
  10. 음수가 될 수 있는 계열에 infer_is_positive=True 사용 → 예측값이 0으로 고정됩니다. 온도, 수익률 등에는 False로 설정하세요.

모델 버전

timeline
    accTitle: TimesFM 버전 이력
    accDescr: TimesFM 모델 릴리스의 타임라인으로, 파라미터 수와 주요 개선 사항을 보여줍니다.

    section 2024
        TimesFM 1.0 : 200M 파라미터, 2K 컨텍스트, JAX 전용
        TimesFM 2.0 : 500M 파라미터, 2K 컨텍스트, PyTorch + JAX
    section 2025
        TimesFM 2.5 : 200M 파라미터, 16K 컨텍스트, 분위수 헤드, 빈도 표시기 없음
버전파라미터컨텍스트분위수 헤드빈도 플래그상태
2.5200M16,384✅ 연속형없음권장
2.0500M2,048✅ 이산형✅ per_seq_freq보관됨
1.0200M512❌ 없음✅ per_seq_freq보관됨

📄 라이선스

이 저장소는 Apache 2.0 라이선스에 따라 제공됩니다. TimesFM 모델 가중치는 Google의 TimesFM 라이선스에 따라 제공됩니다.

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.

관련 스킬