RayoDeCodigos commited on
Commit
72f6e5f
·
verified ·
1 Parent(s): 3260c40

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -35
app.py CHANGED
@@ -1,63 +1,69 @@
1
- from fastapi import FastAPI, Request
2
- from chronos import ChronosPipeline
3
  import torch
4
  import numpy as np
 
 
5
 
6
  app = FastAPI()
7
 
8
- # Load the model once on startup
9
  pipeline = ChronosPipeline.from_pretrained(
10
- "amazon/chronos-t5-small", # or base/large depending on your Space hardware
11
  device_map="auto",
12
- torch_dtype=torch.bfloat16,
13
  )
14
 
15
  @app.post("/predict")
16
- async def predict(info: Request):
17
- data = await info.json()
18
- # Accept the full history array from your backend
19
- history_array = data.get("history", [])
20
- prediction_length = data.get("forecast_horizon", 12) # e.g., next 12 periods
21
 
22
- # Convert to tensor
23
- context = torch.tensor(history_array)
 
 
 
24
 
25
- # Chronos Prediction (Probabilistic)
26
- # returns shape: (num_samples, prediction_length)
27
- forecast = pipeline.predict(context, prediction_length)
28
 
29
- # Extract Quantiles (P10, P50, P90)
 
30
  low_bound = np.percentile(forecast.numpy(), 10, axis=0)
31
  median_pred = np.percentile(forecast.numpy(), 50, axis=0)
32
  high_bound = np.percentile(forecast.numpy(), 90, axis=0)
33
 
34
- # Trading Logic Calculations (Based on the first predicted step)
35
- entry_price = history_array[-1]
36
- predicted_next = median_pred[0]
37
- p10_support = low_bound[0]
38
 
39
- # Stop Loss (SL) set at the Lower Bound (P10)
40
- sl = p10_support
41
- risk = entry_price - sl
42
 
43
- # Take Profit (TP) based on 2:1 RR Ratio
44
- # Formula: Entry + (Risk * 2)
45
- tp = entry_price + (risk * 2) if risk > 0 else entry_price * 1.05
46
 
47
- # Verdict Logic
48
- if predicted_next > entry_price and entry_price > p10_support:
49
- verdict = "Strong Entry - Trend is Up"
50
- elif predicted_next < entry_price:
51
- verdict = "Wait - Potential Pullback Detected"
52
  else:
53
- verdict = "Neutral - High Volatility"
54
 
 
55
  return {
 
 
56
  "prediction": median_pred.tolist(),
57
  "upper_bound": high_bound.tolist(),
58
  "lower_bound": low_bound.tolist(),
59
- "suggested_tp": round(tp, 2),
60
- "suggested_sl": round(sl, 2),
61
  "verdict": verdict,
62
- "rr_ratio": "2:1"
63
  }
 
 
 
1
  import torch
2
  import numpy as np
3
+ from fastapi import FastAPI, Request
4
+ from chronos import ChronosPipeline
5
 
6
  app = FastAPI()
7
 
8
+ # Pipeline initialization with the corrected 'dtype'
9
  pipeline = ChronosPipeline.from_pretrained(
10
+ "amazon/chronos-t5-small",
11
  device_map="auto",
12
+ dtype=torch.bfloat16,
13
  )
14
 
15
  @app.post("/predict")
16
+ async def get_forecast(request: Request):
17
+ # 1. Receive data from your backend
18
+ body = await request.json()
19
+ history = body.get("history", [])
20
+ user_rr = body.get("rr_ratio", 2.0) # Default to 2:1 if not provided
21
 
22
+ if not history:
23
+ return {"error": "No history data provided"}
24
+
25
+ # 2. Convert history to tensor (No length limit - uses your 2-3 year data)
26
+ context = torch.tensor(history)
27
 
28
+ # 3. Predict (Defaulting to 12 steps ahead)
29
+ # Chronos returns (num_samples, prediction_length)
30
+ forecast = pipeline.predict(context, prediction_length=12)
31
 
32
+ # 4. Extract Quantiles for Bounds
33
+ # P10 = Lower Bound, P50 = Median (Prediction), P90 = Upper Bound
34
  low_bound = np.percentile(forecast.numpy(), 10, axis=0)
35
  median_pred = np.percentile(forecast.numpy(), 50, axis=0)
36
  high_bound = np.percentile(forecast.numpy(), 90, axis=0)
37
 
38
+ # 5. Trading System Logic
39
+ entry_price = history[-1]
40
+ next_move = median_pred[0]
 
41
 
42
+ # Stop Loss (SL) based on the model's P10 (statistical support)
43
+ # We ensure SL is actually below entry; if not, we use a 2% buffer
44
+ sl = min(low_bound[0], entry_price * 0.98)
45
 
46
+ # Calculate Take Profit (TP) based on User RR Ratio
47
+ risk_amount = entry_price - sl
48
+ tp = entry_price + (risk_amount * user_rr)
49
 
50
+ # 6. Verdict Engine
51
+ if next_move > entry_price * 1.01:
52
+ verdict = "Entry Confirmed: Upward momentum detected."
53
+ elif next_move < entry_price * 0.99:
54
+ verdict = "Wait: Potential pullback or downward trend."
55
  else:
56
+ verdict = "Neutral: Sideways movement expected. Wait for breakout."
57
 
58
+ # 7. Response to Backend
59
  return {
60
+ "status": "success",
61
+ "entry": float(entry_price),
62
  "prediction": median_pred.tolist(),
63
  "upper_bound": high_bound.tolist(),
64
  "lower_bound": low_bound.tolist(),
65
+ "suggested_sl": round(float(sl), 2),
66
+ "suggested_tp": round(float(tp), 2),
67
  "verdict": verdict,
68
+ "rr_applied": f"{user_rr}:1"
69
  }