Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,50 +1,62 @@
|
|
|
|
|
| 1 |
import torch
|
| 2 |
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
from chronos import BaseChronosPipeline
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
class SMCPredictionEngine:
|
| 7 |
def __init__(self, model_name="amazon/chronos-bolt-base"):
|
| 8 |
"""
|
| 9 |
Initializes the Hugging Face Time-Series Transformer.
|
| 10 |
-
|
| 11 |
"""
|
| 12 |
print(f"Loading pre-trained AI weights: {model_name}...")
|
| 13 |
self.pipeline = BaseChronosPipeline.from_pretrained(
|
| 14 |
model_name,
|
| 15 |
device_map="cpu",
|
| 16 |
-
torch_dtype=torch.float32
|
| 17 |
)
|
|
|
|
| 18 |
|
| 19 |
-
def calculate_forecast(self, history_array, prediction_length=12):
|
| 20 |
"""
|
| 21 |
-
Takes an array of historical prices
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
forecast = self.pipeline.predict(
|
| 29 |
context=context_tensor,
|
| 30 |
-
prediction_length=prediction_length
|
| 31 |
)
|
| 32 |
-
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
#
|
| 42 |
-
last_price = history_array[-1]
|
| 43 |
-
projected_change = ((median_predictions[-1] - last_price) / last_price) * 100
|
| 44 |
-
|
| 45 |
return {
|
| 46 |
"low": low_bounds,
|
| 47 |
"median": median_predictions,
|
| 48 |
"high": high_bounds,
|
| 49 |
-
"projected_change_pct": projected_change
|
| 50 |
}
|
|
|
|
| 1 |
+
import os
|
| 2 |
import torch
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
from chronos import BaseChronosPipeline
|
| 5 |
|
| 6 |
+
# Fix: Point HF cache to a writable path for the non-root HF Spaces user
|
| 7 |
+
os.environ.setdefault("HF_HOME", "/home/user/.cache/huggingface")
|
| 8 |
+
os.environ.setdefault("TRANSFORMERS_CACHE", "/home/user/.cache/huggingface")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
class SMCPredictionEngine:
|
| 12 |
def __init__(self, model_name="amazon/chronos-bolt-base"):
|
| 13 |
"""
|
| 14 |
Initializes the Hugging Face Time-Series Transformer.
|
| 15 |
+
Runs on CPU for compatibility with standard HF Spaces containers.
|
| 16 |
"""
|
| 17 |
print(f"Loading pre-trained AI weights: {model_name}...")
|
| 18 |
self.pipeline = BaseChronosPipeline.from_pretrained(
|
| 19 |
model_name,
|
| 20 |
device_map="cpu",
|
| 21 |
+
torch_dtype=torch.float32,
|
| 22 |
)
|
| 23 |
+
print("Model loaded successfully.")
|
| 24 |
|
| 25 |
+
def calculate_forecast(self, history_array: list | np.ndarray, prediction_length: int = 12) -> dict:
|
| 26 |
"""
|
| 27 |
+
Takes an array of historical prices and generates probabilistic forecasts.
|
| 28 |
+
|
| 29 |
+
BaseChronosPipeline.predict() returns a tensor of shape:
|
| 30 |
+
[batch_size, num_samples, prediction_length]
|
| 31 |
+
|
| 32 |
+
We derive low / median / high by taking quantiles across the sample axis (axis=1).
|
| 33 |
"""
|
| 34 |
+
context_tensor = torch.tensor(
|
| 35 |
+
np.array(history_array, dtype=np.float32).reshape(1, -1), # [1, seq_len]
|
| 36 |
+
dtype=torch.float32,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# forecast shape: [1, num_samples, prediction_length]
|
| 40 |
forecast = self.pipeline.predict(
|
| 41 |
context=context_tensor,
|
| 42 |
+
prediction_length=prediction_length,
|
| 43 |
)
|
| 44 |
+
|
| 45 |
+
# Convert to numpy: shape [num_samples, prediction_length]
|
| 46 |
+
samples = forecast[0].numpy() # drop batch dimension
|
| 47 |
+
|
| 48 |
+
# Derive quantile bands across the sample axis
|
| 49 |
+
low_bounds = np.quantile(samples, 0.10, axis=0) # 10th percentile
|
| 50 |
+
median_predictions = np.quantile(samples, 0.50, axis=0) # median
|
| 51 |
+
high_bounds = np.quantile(samples, 0.90, axis=0) # 90th percentile
|
| 52 |
+
|
| 53 |
+
# Projected momentum: % change from last known price to median forecast end
|
| 54 |
+
last_price = float(history_array[-1])
|
| 55 |
+
projected_change = ((median_predictions[-1] - last_price) / last_price) * 100.0
|
| 56 |
+
|
| 57 |
return {
|
| 58 |
"low": low_bounds,
|
| 59 |
"median": median_predictions,
|
| 60 |
"high": high_bounds,
|
| 61 |
+
"projected_change_pct": float(projected_change),
|
| 62 |
}
|