Spaces:
Running
Running
Upload 6 files
Browse files- .gitignore +4 -0
- Dockerfile +18 -14
- app.py +24 -37
- requirements.txt +3 -6
- schemas.py +58 -0
- service.py +129 -0
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
.pytest_cache/
|
| 3 |
+
.venv/
|
| 4 |
+
*.pyc
|
Dockerfile
CHANGED
|
@@ -1,21 +1,25 @@
|
|
| 1 |
-
|
| 2 |
-
FROM python:3.10-slim
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 13 |
|
| 14 |
-
|
| 15 |
-
COPY . .
|
| 16 |
|
| 17 |
-
# 暴露 Space 默认端口
|
| 18 |
EXPOSE 7860
|
| 19 |
|
| 20 |
-
|
| 21 |
-
CMD ["python", "app.py"]
|
|
|
|
| 1 |
+
FROM python:3.13-slim
|
|
|
|
| 2 |
|
| 3 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
| 4 |
+
ENV PYTHONUNBUFFERED=1
|
| 5 |
+
ENV PORT=7860
|
| 6 |
+
ENV CUDA_VISIBLE_DEVICES=""
|
| 7 |
+
ENV TRANSFORMERS_NO_ADVISORY_WARNINGS=1
|
| 8 |
+
ENV HF_HUB_DISABLE_TELEMETRY=1
|
| 9 |
+
ENV TIMESFM_BACKEND=baseline_cpu
|
| 10 |
+
ENV TIMESFM_MAX_CONTEXT_LENGTH=512
|
| 11 |
+
ENV TIMESFM_MAX_HORIZON_STEP=288
|
| 12 |
+
ENV TIMESFM_MIN_REQUIRED_POINTS=32
|
| 13 |
+
ENV UV_SYSTEM_PYTHON=1
|
| 14 |
|
| 15 |
+
WORKDIR /app
|
|
|
|
| 16 |
|
| 17 |
+
COPY requirements.txt /app/requirements.txt
|
| 18 |
+
RUN python -m pip install --no-cache-dir uv
|
| 19 |
+
RUN uv pip install --no-cache-dir -r /app/requirements.txt
|
| 20 |
|
| 21 |
+
COPY . /app
|
|
|
|
| 22 |
|
|
|
|
| 23 |
EXPOSE 7860
|
| 24 |
|
| 25 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
|
|
|
app.py
CHANGED
|
@@ -1,44 +1,31 @@
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
| 2 |
-
from pydantic import BaseModel
|
| 3 |
-
import torch
|
| 4 |
-
from transformers import TimesFm2_5ModelForPrediction
|
| 5 |
-
import uvicorn
|
| 6 |
-
import os
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
# 1. 全局加载模型
|
| 11 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
-
model_id = "google/timesfm-2.5-200m-transformers"
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
|
|
|
| 16 |
|
| 17 |
-
class PredictRequest(BaseModel):
|
| 18 |
-
# 传入历史 K 线序列 (收盘价等)
|
| 19 |
-
inputs: list[float]
|
| 20 |
-
# 预测步长
|
| 21 |
-
horizon: int = 24
|
| 22 |
|
| 23 |
-
@app.post("/predict")
|
| 24 |
-
|
| 25 |
try:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
predictions = outputs.point_forecast # 获取点预测结果
|
| 34 |
-
|
| 35 |
-
return {
|
| 36 |
-
"status": "success",
|
| 37 |
-
"predictions": predictions.cpu().numpy().tolist()[0]
|
| 38 |
-
}
|
| 39 |
-
except Exception as e:
|
| 40 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 41 |
-
|
| 42 |
-
if __name__ == "__main__":
|
| 43 |
-
# Space 默认监听端口为 7860
|
| 44 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
from fastapi import FastAPI, HTTPException
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
from schemas import HealthResponse, PredictRequest, PredictResponse
|
| 6 |
+
from service import TimesFmService
|
| 7 |
+
|
| 8 |
+
app = FastAPI(title="TimesFm Space", version="0.1.0")
|
| 9 |
+
service = TimesFmService()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@app.get("/health", response_model=HealthResponse)
|
| 13 |
+
def health() -> HealthResponse:
|
| 14 |
+
return service.health()
|
| 15 |
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
@app.get("/")
|
| 18 |
+
def root() -> dict[str, str]:
|
| 19 |
+
return {"service": "timesfm", "status": "ok"}
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
@app.post("/predict", response_model=PredictResponse)
|
| 23 |
+
def predict(payload: PredictRequest) -> PredictResponse:
|
| 24 |
try:
|
| 25 |
+
return service.predict(payload)
|
| 26 |
+
except ValueError as exc:
|
| 27 |
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
| 28 |
+
except RuntimeError as exc:
|
| 29 |
+
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
| 30 |
+
except Exception as exc: # pragma: no cover - API guardrail
|
| 31 |
+
raise HTTPException(status_code=500, detail="prediction_failed") from exc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,6 +1,3 @@
|
|
| 1 |
-
fastapi
|
| 2 |
-
uvicorn
|
| 3 |
-
pydantic
|
| 4 |
-
torch --index-url https://download.pytorch.org/whl/cpu # 若用 GPU 则去掉 index-url
|
| 5 |
-
transformers
|
| 6 |
-
numpy
|
|
|
|
| 1 |
+
fastapi==0.115.12
|
| 2 |
+
uvicorn==0.34.0
|
| 3 |
+
pydantic==2.11.3
|
|
|
|
|
|
|
|
|
schemas.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import List
|
| 4 |
+
|
| 5 |
+
from pydantic import BaseModel, Field, field_validator
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class HealthResponse(BaseModel):
|
| 9 |
+
status: str
|
| 10 |
+
model: str
|
| 11 |
+
model_id: str
|
| 12 |
+
backend: str
|
| 13 |
+
device: str
|
| 14 |
+
ready: bool
|
| 15 |
+
max_context_length: int
|
| 16 |
+
max_horizon_step: int
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class PredictRequest(BaseModel):
|
| 20 |
+
symbol: str = Field(..., min_length=1, max_length=32)
|
| 21 |
+
close_prices: List[float] = Field(..., min_length=8)
|
| 22 |
+
context_length: int = Field(..., ge=8, le=2048)
|
| 23 |
+
horizons: List[int] = Field(..., min_length=1, max_length=64)
|
| 24 |
+
|
| 25 |
+
@field_validator("symbol")
|
| 26 |
+
@classmethod
|
| 27 |
+
def validate_symbol(cls, value: str) -> str:
|
| 28 |
+
normalized = value.strip().upper()
|
| 29 |
+
if not normalized:
|
| 30 |
+
raise ValueError("symbol must not be empty")
|
| 31 |
+
return normalized
|
| 32 |
+
|
| 33 |
+
@field_validator("close_prices")
|
| 34 |
+
@classmethod
|
| 35 |
+
def validate_close_prices(cls, values: List[float]) -> List[float]:
|
| 36 |
+
if any(price <= 0 for price in values):
|
| 37 |
+
raise ValueError("close_prices must be positive")
|
| 38 |
+
return values
|
| 39 |
+
|
| 40 |
+
@field_validator("horizons")
|
| 41 |
+
@classmethod
|
| 42 |
+
def validate_horizons(cls, values: List[int]) -> List[int]:
|
| 43 |
+
if any(step <= 0 for step in values):
|
| 44 |
+
raise ValueError("horizons must be positive integers")
|
| 45 |
+
if len(set(values)) != len(values):
|
| 46 |
+
raise ValueError("horizons must not contain duplicates")
|
| 47 |
+
return values
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class PredictionItem(BaseModel):
|
| 51 |
+
step: int = Field(..., gt=0)
|
| 52 |
+
pred_price: float = Field(..., gt=0)
|
| 53 |
+
pred_confidence: float = Field(..., ge=0, le=1)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class PredictResponse(BaseModel):
|
| 57 |
+
model_id: str
|
| 58 |
+
predictions: List[PredictionItem]
|
service.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
from statistics import mean
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from schemas import HealthResponse, PredictRequest, PredictResponse, PredictionItem
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TimesFmService:
|
| 12 |
+
"""CPU-first HF Space service wrapper.
|
| 13 |
+
|
| 14 |
+
HuggingFace free Spaces are CPU-only in our rollout, so this service keeps
|
| 15 |
+
the HTTP contract stable and intentionally avoids any GPU assumption. The
|
| 16 |
+
default backend is a deterministic CPU baseline that is cheap to start,
|
| 17 |
+
predictable for contract tests, and compatible with `tsf-bridge`.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self) -> None:
|
| 21 |
+
self.model_id = "timesfm"
|
| 22 |
+
self.model_name = os.getenv(
|
| 23 |
+
"TIMESFM_MODEL_NAME",
|
| 24 |
+
"google/timesfm-2.5-200m-transformers",
|
| 25 |
+
)
|
| 26 |
+
self.backend = os.getenv("TIMESFM_BACKEND", "baseline_cpu").strip() or "baseline_cpu"
|
| 27 |
+
self.device = "cpu"
|
| 28 |
+
self.ready = True
|
| 29 |
+
self.max_context_length = int(os.getenv("TIMESFM_MAX_CONTEXT_LENGTH", "512"))
|
| 30 |
+
self.max_horizon_step = int(os.getenv("TIMESFM_MAX_HORIZON_STEP", "288"))
|
| 31 |
+
self.confidence_floor = float(os.getenv("TIMESFM_CONFIDENCE_FLOOR", "0.20"))
|
| 32 |
+
self.confidence_ceiling = float(os.getenv("TIMESFM_CONFIDENCE_CEILING", "0.85"))
|
| 33 |
+
self.min_required_points = int(os.getenv("TIMESFM_MIN_REQUIRED_POINTS", "32"))
|
| 34 |
+
|
| 35 |
+
def health(self) -> HealthResponse:
|
| 36 |
+
return HealthResponse(
|
| 37 |
+
status="ok",
|
| 38 |
+
model=self.model_name,
|
| 39 |
+
model_id=self.model_id,
|
| 40 |
+
backend=self.backend,
|
| 41 |
+
device=self.device,
|
| 42 |
+
ready=self.ready,
|
| 43 |
+
max_context_length=self.max_context_length,
|
| 44 |
+
max_horizon_step=self.max_horizon_step,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
def predict(self, payload: PredictRequest) -> PredictResponse:
|
| 48 |
+
self._validate_request(payload)
|
| 49 |
+
closes = payload.close_prices[-payload.context_length :]
|
| 50 |
+
|
| 51 |
+
predictions = self._predict_with_baseline(closes, payload.horizons)
|
| 52 |
+
return PredictResponse(model_id=self.model_id, predictions=predictions)
|
| 53 |
+
|
| 54 |
+
def _validate_request(self, payload: PredictRequest) -> None:
|
| 55 |
+
if payload.context_length > self.max_context_length:
|
| 56 |
+
raise ValueError(
|
| 57 |
+
f"context_length {payload.context_length} exceeds "
|
| 58 |
+
f"TIMESFM_MAX_CONTEXT_LENGTH={self.max_context_length}"
|
| 59 |
+
)
|
| 60 |
+
if payload.context_length > len(payload.close_prices):
|
| 61 |
+
raise ValueError("context_length must not exceed len(close_prices)")
|
| 62 |
+
if len(payload.close_prices) < self.min_required_points:
|
| 63 |
+
raise ValueError(
|
| 64 |
+
f"at least {self.min_required_points} close prices are required "
|
| 65 |
+
"for CPU baseline stability"
|
| 66 |
+
)
|
| 67 |
+
if any(step > self.max_horizon_step for step in payload.horizons):
|
| 68 |
+
raise ValueError(
|
| 69 |
+
f"horizons contain values above TIMESFM_MAX_HORIZON_STEP={self.max_horizon_step}"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def _predict_with_baseline(
|
| 73 |
+
self, close_prices: list[float], horizons: list[int]
|
| 74 |
+
) -> list[PredictionItem]:
|
| 75 |
+
last_price = close_prices[-1]
|
| 76 |
+
short_window = close_prices[-min(8, len(close_prices)) :]
|
| 77 |
+
long_window = close_prices[-min(32, len(close_prices)) :]
|
| 78 |
+
|
| 79 |
+
short_mean = mean(short_window)
|
| 80 |
+
long_mean = mean(long_window)
|
| 81 |
+
momentum = 0.0 if short_mean == 0 else (last_price - short_mean) / short_mean
|
| 82 |
+
regime_bias = 0.0 if long_mean == 0 else (short_mean - long_mean) / long_mean
|
| 83 |
+
|
| 84 |
+
predictions: list[PredictionItem] = []
|
| 85 |
+
for step in horizons:
|
| 86 |
+
damped_step = math.log(step + 1.0)
|
| 87 |
+
expected_return = momentum * 0.55 + regime_bias * 0.45
|
| 88 |
+
expected_return *= min(1.0, damped_step / 3.5)
|
| 89 |
+
|
| 90 |
+
pred_price = max(0.00000001, last_price * (1.0 + expected_return))
|
| 91 |
+
confidence = self._confidence(close_prices, step, abs(expected_return))
|
| 92 |
+
predictions.append(
|
| 93 |
+
PredictionItem(
|
| 94 |
+
step=step,
|
| 95 |
+
pred_price=round(pred_price, 8),
|
| 96 |
+
pred_confidence=round(confidence, 4),
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
return predictions
|
| 100 |
+
|
| 101 |
+
def _confidence(
|
| 102 |
+
self, close_prices: list[float], step: int, expected_move_abs: float
|
| 103 |
+
) -> float:
|
| 104 |
+
if len(close_prices) < 3:
|
| 105 |
+
return self.confidence_floor
|
| 106 |
+
|
| 107 |
+
changes: list[float] = []
|
| 108 |
+
for previous, current in zip(close_prices[:-1], close_prices[1:]):
|
| 109 |
+
if previous <= 0:
|
| 110 |
+
continue
|
| 111 |
+
changes.append(abs((current - previous) / previous))
|
| 112 |
+
|
| 113 |
+
realized_vol = mean(changes[-min(32, len(changes)) :]) if changes else 0.0
|
| 114 |
+
signal_to_noise = expected_move_abs / (realized_vol + 1e-9)
|
| 115 |
+
horizon_decay = 1.0 / (1.0 + math.log(step + 1.0))
|
| 116 |
+
raw = 0.25 + min(signal_to_noise, 2.0) * 0.25 + horizon_decay * 0.35
|
| 117 |
+
return max(self.confidence_floor, min(self.confidence_ceiling, raw))
|
| 118 |
+
|
| 119 |
+
def describe_runtime(self) -> dict[str, Any]:
|
| 120 |
+
return {
|
| 121 |
+
"model_id": self.model_id,
|
| 122 |
+
"model_name": self.model_name,
|
| 123 |
+
"backend": self.backend,
|
| 124 |
+
"device": self.device,
|
| 125 |
+
"ready": self.ready,
|
| 126 |
+
"max_context_length": self.max_context_length,
|
| 127 |
+
"max_horizon_step": self.max_horizon_step,
|
| 128 |
+
"min_required_points": self.min_required_points,
|
| 129 |
+
}
|