MaTaylor commited on
Commit
effed4a
·
verified ·
1 Parent(s): 7faacd7

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +25 -0
  2. app.py +31 -0
  3. requirements.txt +3 -0
  4. schemas.py +58 -0
  5. service.py +137 -0
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 CHRONOS_BACKEND=baseline_cpu
10
+ ENV CHRONOS_MAX_CONTEXT_LENGTH=512
11
+ ENV CHRONOS_MAX_HORIZON_STEP=288
12
+ ENV CHRONOS_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 ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from fastapi import FastAPI, HTTPException
4
+
5
+ from schemas import HealthResponse, PredictRequest, PredictResponse
6
+ from service import ChronosService
7
+
8
+ app = FastAPI(title="Chronos Space", version="0.1.0")
9
+ service = ChronosService()
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": "chronos", "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
31
+ raise HTTPException(status_code=500, detail="prediction_failed") from exc
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
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,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ChronosService:
12
+ """CPU-first HF Space service wrapper for Chronos.
13
+
14
+ This scaffold is designed for HuggingFace free CPU Spaces and keeps the
15
+ serving contract aligned with `tsf-bridge`. The default backend is a
16
+ deterministic CPU baseline rather than real Chronos inference.
17
+ """
18
+
19
+ def __init__(self) -> None:
20
+ self.model_id = "chronos"
21
+ self.model_name = os.getenv(
22
+ "CHRONOS_MODEL_NAME",
23
+ "amazon/chronos-t5-small",
24
+ )
25
+ self.backend = os.getenv("CHRONOS_BACKEND", "baseline_cpu").strip() or "baseline_cpu"
26
+ self.device = "cpu"
27
+ self.ready = True
28
+ self.max_context_length = int(os.getenv("CHRONOS_MAX_CONTEXT_LENGTH", "512"))
29
+ self.max_horizon_step = int(os.getenv("CHRONOS_MAX_HORIZON_STEP", "288"))
30
+ self.confidence_floor = float(os.getenv("CHRONOS_CONFIDENCE_FLOOR", "0.16"))
31
+ self.confidence_ceiling = float(os.getenv("CHRONOS_CONFIDENCE_CEILING", "0.80"))
32
+ self.min_required_points = int(os.getenv("CHRONOS_MIN_REQUIRED_POINTS", "32"))
33
+
34
+ def health(self) -> HealthResponse:
35
+ return HealthResponse(
36
+ status="ok",
37
+ model=self.model_name,
38
+ model_id=self.model_id,
39
+ backend=self.backend,
40
+ device=self.device,
41
+ ready=self.ready,
42
+ max_context_length=self.max_context_length,
43
+ max_horizon_step=self.max_horizon_step,
44
+ )
45
+
46
+ def predict(self, payload: PredictRequest) -> PredictResponse:
47
+ self._validate_request(payload)
48
+ closes = payload.close_prices[-payload.context_length :]
49
+ predictions = self._predict_with_baseline(closes, payload.horizons)
50
+ return PredictResponse(model_id=self.model_id, predictions=predictions)
51
+
52
+ def _validate_request(self, payload: PredictRequest) -> None:
53
+ if payload.context_length > self.max_context_length:
54
+ raise ValueError(
55
+ f"context_length {payload.context_length} exceeds "
56
+ f"CHRONOS_MAX_CONTEXT_LENGTH={self.max_context_length}"
57
+ )
58
+ if payload.context_length > len(payload.close_prices):
59
+ raise ValueError("context_length must not exceed len(close_prices)")
60
+ if len(payload.close_prices) < self.min_required_points:
61
+ raise ValueError(
62
+ f"at least {self.min_required_points} close prices are required "
63
+ "for CPU baseline stability"
64
+ )
65
+ if any(step > self.max_horizon_step for step in payload.horizons):
66
+ raise ValueError(
67
+ f"horizons contain values above CHRONOS_MAX_HORIZON_STEP={self.max_horizon_step}"
68
+ )
69
+
70
+ def _predict_with_baseline(
71
+ self, close_prices: list[float], horizons: list[int]
72
+ ) -> list[PredictionItem]:
73
+ last_price = close_prices[-1]
74
+ short_window = close_prices[-min(10, len(close_prices)) :]
75
+ mid_window = close_prices[-min(24, len(close_prices)) :]
76
+ long_window = close_prices[-min(64, len(close_prices)) :]
77
+
78
+ short_mean = mean(short_window)
79
+ mid_mean = mean(mid_window)
80
+ long_mean = mean(long_window)
81
+ momentum = 0.0 if short_mean == 0 else (last_price - short_mean) / short_mean
82
+ mean_reversion = 0.0 if long_mean == 0 else (mid_mean - long_mean) / long_mean
83
+ local_trend = self._slope(mid_window)
84
+
85
+ predictions: list[PredictionItem] = []
86
+ for step in horizons:
87
+ horizon_scale = min(1.0, math.log(step + 1.0) / 3.8)
88
+ expected_return = momentum * 0.35 + mean_reversion * 0.30 + local_trend * 0.35
89
+ expected_return *= horizon_scale
90
+
91
+ pred_price = max(0.00000001, last_price * (1.0 + expected_return))
92
+ confidence = self._confidence(close_prices, step, abs(expected_return))
93
+ predictions.append(
94
+ PredictionItem(
95
+ step=step,
96
+ pred_price=round(pred_price, 8),
97
+ pred_confidence=round(confidence, 4),
98
+ )
99
+ )
100
+ return predictions
101
+
102
+ def _confidence(
103
+ self, close_prices: list[float], step: int, expected_move_abs: float
104
+ ) -> float:
105
+ if len(close_prices) < 3:
106
+ return self.confidence_floor
107
+
108
+ changes: list[float] = []
109
+ for previous, current in zip(close_prices[:-1], close_prices[1:]):
110
+ if previous <= 0:
111
+ continue
112
+ changes.append(abs((current - previous) / previous))
113
+
114
+ realized_vol = mean(changes[-min(64, len(changes)) :]) if changes else 0.0
115
+ stability = max(0.0, 1.0 - min(realized_vol * 18.0, 1.0))
116
+ horizon_decay = 1.0 / (1.0 + math.log(step + 1.0))
117
+ raw = 0.20 + min(expected_move_abs / (realized_vol + 1e-9), 2.0) * 0.18
118
+ raw += stability * 0.20 + horizon_decay * 0.22
119
+ return max(self.confidence_floor, min(self.confidence_ceiling, raw))
120
+
121
+ @staticmethod
122
+ def _slope(values: list[float]) -> float:
123
+ if len(values) < 2 or values[0] == 0:
124
+ return 0.0
125
+ return (values[-1] - values[0]) / values[0]
126
+
127
+ def describe_runtime(self) -> dict[str, Any]:
128
+ return {
129
+ "model_id": self.model_id,
130
+ "model_name": self.model_name,
131
+ "backend": self.backend,
132
+ "device": self.device,
133
+ "ready": self.ready,
134
+ "max_context_length": self.max_context_length,
135
+ "max_horizon_step": self.max_horizon_step,
136
+ "min_required_points": self.min_required_points,
137
+ }