File size: 5,925 Bytes
59a4043
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""Hugging Face Space - BTC Prediction API"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import pandas as pd
import yfinance as yf
import torch
import numpy as np
import random
from chronos import ChronosPipeline
from datetime import date, timedelta
from typing import Optional

# ตั้ง seed
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)

app = FastAPI(title="BTC Prediction API", version="1.0.0")

# โหลด model ตอน startup
model_pipeline = None

@app.on_event("startup")
async def load_model():
    global model_pipeline
    print("🤖 Loading Chronos model...")
    model_pipeline = ChronosPipeline.from_pretrained(
        "amazon/chronos-t5-tiny",
        device_map="cpu",
        torch_dtype=torch.float32
    )
    print("✅ Model loaded successfully")


class PredictionRequest(BaseModel):
    start_date: str = "2020-01-01"
    window_size: int = 256


class BatchPredictionRequest(BaseModel):
    """สำหรับทำนายหลายวัน (ใช้ใน strategy filter)"""
    prices: list[float]  # ราคาที่ต้องการทำนาย
    window_size: int = 256


def get_btc_data(start: str) -> pd.DataFrame:
    """ดึงข้อมูล BTC"""
    end = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")
    btc = yf.download("BTC-USD", start=start, end=end, progress=False)
    
    if isinstance(btc.columns, pd.MultiIndex):
        btc.columns = btc.columns.get_level_values(0)
    
    df = btc[["Close"]].copy()
    df = df.ffill().dropna()
    return df


def predict_price(data: pd.DataFrame, window_size: int = 256) -> Optional[float]:
    """ทำนายราคา"""
    if model_pipeline is None:
        raise RuntimeError("Model not loaded")
    
    if len(data) < window_size:
        context = data['Close'].values.tolist()
    else:
        context = data['Close'].values[-window_size:].tolist()
    
    context_tensor = torch.tensor([context])
    
    torch.manual_seed(SEED)
    
    with torch.no_grad():
        forecast = model_pipeline.predict(
            context_tensor,
            prediction_length=1,
            num_samples=1
        )
    
    predicted_price = forecast[0, 0, 0].item()
    return float(predicted_price)


@app.get("/")
def root():
    return {
        "service": "BTC Prediction API",
        "model": "amazon/chronos-t5-tiny",
        "status": "ready" if model_pipeline else "loading"
    }


@app.get("/health")
def health():
    return {
        "status": "ok",
        "model_loaded": model_pipeline is not None
    }


@app.head("/health")
def health_head():
    """HEAD endpoint for uptime monitoring."""
    return


@app.post("/predict")
def predict(req: PredictionRequest):
    """ทำนายราคา BTC วันถัดไป"""
    try:
        if model_pipeline is None:
            raise HTTPException(status_code=503, detail="Model is still loading")
        
        # ดึงข้อมูล
        data = get_btc_data(req.start_date)
        
        if len(data) < 30:
            raise HTTPException(status_code=400, detail="Not enough data")
        
        # ทำนาย
        predicted_price = predict_price(data, req.window_size)
        
        if predicted_price is None:
            raise HTTPException(status_code=500, detail="Prediction failed")
        
        # คำนวณผลลัพธ์
        last_close = float(data["Close"].iloc[-1])
        last_date = data.index[-1]
        next_date = last_date + pd.Timedelta(days=1)
        change_pct = ((predicted_price / last_close) - 1) * 100
        
        return {
            "symbol": "BTC-USD",
            "last_date": str(last_date.date()),
            "next_date": str(next_date.date()),
            "last_close": last_close,
            "predicted_close": predicted_price,
            "predicted_change_pct": float(change_pct),
            "model": "amazon/chronos-t5-tiny",
            "window_size": req.window_size
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/predict_from_data")
def predict_from_data(req: BatchPredictionRequest):
    """ทำนายราคาจากข้อมูลที่ส่งมา (สำหรับ strategy filter)"""
    try:
        if model_pipeline is None:
            raise HTTPException(status_code=503, detail="Model is still loading")
        
        # ลดข้อกำหนดจาก 30 เป็น 10 วัน
        if len(req.prices) < 10:
            raise HTTPException(status_code=400, detail="Not enough data (need at least 10 prices)")
        
        # ใช้ราคาที่ส่งมา
        if len(req.prices) < req.window_size:
            context = req.prices
        else:
            context = req.prices[-req.window_size:]
        
        context_tensor = torch.tensor([context])
        
        torch.manual_seed(SEED)
        
        with torch.no_grad():
            forecast = model_pipeline.predict(
                context_tensor,
                prediction_length=1,
                num_samples=1
            )
        
        predicted_price = forecast[0, 0, 0].item()
        
        return {
            "predicted_price": float(predicted_price),
            "input_length": len(req.prices),
            "window_size": req.window_size
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)