MalikShehram commited on
Commit
82dce4b
·
verified ·
1 Parent(s): 899a53a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -25
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
- Defaults to CPU mode for rock-solid stability inside standard containers.
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, converts them into a PyTorch tensor,
22
- and generates high-probability prediction arrays.
 
 
 
 
23
  """
24
- # Ensure input data is formatted as a 2D float32 tensor: [Batch Size, Sequence Length]
25
- context_tensor = torch.tensor([history_array], dtype=torch.float32)
26
-
27
- # Run inference via Chronos-Bolt
 
 
28
  forecast = self.pipeline.predict(
29
  context=context_tensor,
30
- prediction_length=prediction_length
31
  )
32
-
33
- # Extract sample paths [Quantiles: 10th percentile, 50th percentile, 90th percentile]
34
- quantiles = forecast[0].numpy()
35
-
36
- low_bounds = quantiles[:, 0]
37
- median_predictions = quantiles[:, 1]
38
- high_bounds = quantiles[:, 2]
39
-
40
- # Calculate an Institutional Confirmation Confidence Score
41
- # Measures the projected directional momentum against the last known market price
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
  }