Lullooo commited on
Commit
51f1e9c
·
verified ·
1 Parent(s): d6a1f82

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -165
app.py DELETED
@@ -1,165 +0,0 @@
1
- ################### PACKAGES
2
- import ccxt
3
- import pandas as pd
4
- import numpy as np
5
- from datetime import datetime, timedelta
6
- import time
7
- import requests
8
- from pytrends.request import TrendReq
9
- import joblib
10
- import gradio as gr
11
- from sklearn.preprocessing import StandardScaler
12
-
13
-
14
- ################### MODEL LOADING
15
- # Load XGBoost and NGBoost
16
- xgb_artifact = joblib.load("xgb_volatility_model.joblib")
17
- xgb_model = xgb_artifact["model"]
18
- xgb_features = xgb_artifact["feature_names"]
19
-
20
- ngb_artifact = joblib.load("ngb_volatility_model.joblib")
21
- ngb_model = ngb_artifact["model"]
22
- ngb_features = ngb_artifact["feature_names"]
23
-
24
- forecast_ngb_artifact = joblib.load("Forecast_ngb_volatility_model.joblib")
25
- forecast_ngb_model = forecast_ngb_artifact["model"]
26
- forecast_ngb_features = forecast_ngb_artifact["feature_names"]
27
-
28
- # Load KMeans + scaler
29
- kmeans_artifact = joblib.load("kmeans_model.joblib")
30
- kmeans_model = kmeans_artifact["model"]
31
- cluster_scaler = kmeans_artifact["scaler"]
32
- cluster_features_names = kmeans_artifact["feature_names"]
33
-
34
-
35
- ################### FEATURE GATHERING
36
- def fetch_ohlcv_last_6_days(symbol="BTC/USDT", date="2026-01-18", timeframe="1d"):
37
- binance = ccxt.binance()
38
- user_date = pd.to_datetime(date)
39
- start_date = user_date - timedelta(days=5) # 5 days before
40
- since = binance.parse8601(start_date.strftime("%Y-%m-%dT00:00:00Z"))
41
- data = binance.fetch_ohlcv(symbol, timeframe=timeframe, since=since, limit=6)
42
- df = pd.DataFrame(data, columns=["timestamp","open","high","low","close","volume"])
43
- df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
44
- df.set_index("timestamp", inplace=True)
45
- return df
46
-
47
- def fetch_fg_last_6_days(df):
48
- url = "https://api.alternative.me/fng/?limit=0&format=json"
49
- response = requests.get(url)
50
- fg_df = pd.DataFrame(response.json()["data"])
51
- fg_df["timestamp"] = pd.to_datetime(fg_df["timestamp"], unit="s")
52
- fg_df.set_index("timestamp", inplace=True)
53
- fg_df = fg_df[["value"]].astype(float)
54
- fg_df.rename(columns={"value":"fg_index"}, inplace=True)
55
- fg_df = fg_df.reindex(df.index, method="ffill")
56
- df["fg_index"] = fg_df["fg_index"].values
57
- return df
58
-
59
- def fetch_google_trend_for_date(keyword="Bitcoin", target_date="2024-01-15", window=7):
60
- pytrends = TrendReq(hl="en-US", tz=360)
61
- target_date = pd.to_datetime(target_date)
62
- start_date = (target_date - timedelta(days=window)).strftime("%Y-%m-%d")
63
- end_date = target_date.strftime("%Y-%m-%d")
64
- timeframe = f"{start_date} {end_date}"
65
- try:
66
- pytrends.build_payload([keyword], timeframe=timeframe)
67
- df = pytrends.interest_over_time()
68
- if df.empty:
69
- return 0
70
- df = df.rename(columns={keyword: "trend"})
71
- df = df.drop(columns=["isPartial"], errors="ignore")
72
- df.index = pd.to_datetime(df.index)
73
- if target_date in df.index:
74
- return df.loc[target_date, "trend"]
75
- else:
76
- return 0
77
- except:
78
- return 0
79
-
80
-
81
- ################### FEATURE ENGINEERING
82
- def engineer_features(df):
83
- df["log_return"] = np.log(df["close"] / df["close"].shift(1))
84
- df["hl_spread"] = df["high"] - df["low"]
85
- df["co_spread"] = df["close"] - df["open"]
86
- df["momentum_3"] = df["close"] - df["close"].shift(3)
87
- df["vol_change"] = df["volume"] - df["volume"].shift(1)
88
- df["rolling_std_5"] = df["log_return"].rolling(5).std()
89
- # Fill NaNs for first few rows
90
- df = df.fillna(0)
91
- return df
92
-
93
- ################### ASSIGN CLUSTER
94
- def assign_cluster(df):
95
- cluster_features = df[cluster_features_names]
96
- scaled = cluster_scaler.transform(cluster_features)
97
- df["cluster"] = kmeans_model.predict(scaled)
98
- return df
99
-
100
-
101
- ################### PREDICTION FUNCTION
102
- def predict_volatility(date):
103
- # Fetch raw data
104
- df = fetch_ohlcv_last_6_days(date=date)
105
- df = fetch_fg_last_6_days(df)
106
- trend_value = fetch_google_trend_for_date("Bitcoin", date)
107
- df["trend"] = trend_value
108
- df["trend"] = df["trend"].ffill().fillna(0)
109
-
110
- # Feature engineering
111
- df = engineer_features(df)
112
-
113
- # Clustering
114
- df = assign_cluster(df)
115
-
116
- # ---------------- NOWCASTING ----------------
117
- X_xgb = df.iloc[-1:][xgb_features]
118
- X_ngb = df.iloc[-1:][ngb_features]
119
-
120
- point = xgb_model.predict(X_xgb)[0]
121
- dist = ngb_model.pred_dist(X_ngb)
122
- low, high = dist.ppf([0.025, 0.975])[0]
123
-
124
- # ---------------- FORECASTING (t+1) ----------------
125
- X_ngb_fore = df.iloc[-1:][forecast_ngb_features]
126
-
127
- for_point = forecast_ngb_model.predict(X_ngb_fore)[0]
128
- for_dist = forecast_ngb_model.pred_dist(X_ngb_fore)
129
- for_low, for_high = for_dist.ppf([0.025, 0.975])[0]
130
-
131
- return point, low, high, for_point, for_low, for_high
132
-
133
-
134
-
135
- ################### GRADIO INTERFACE
136
- def gradio_predict(date):
137
- try:
138
- pd.to_datetime(date)
139
- except:
140
- return "❌ Invalid date format. Please use YYYY-MM-DD."
141
-
142
- try:
143
- point, low, high, for_point, for_low, for_high = predict_volatility(date)
144
-
145
- return (
146
- f"NOWCAST (t)\n"
147
- f"Volatility: {point:.4f}\n"
148
- f"95% CI: [{low:.4f}, {high:.4f}]\n\n"
149
- f"FORECAST (t+1)\n"
150
- f"Volatility: {for_point:.4f}\n"
151
- f"95% CI: [{for_low:.4f}, {for_high:.4f}]"
152
- )
153
- except Exception as e:
154
- return f"⚠️ Error while computing prediction:\n{str(e)}"
155
-
156
- demo = gr.Interface(
157
- fn=gradio_predict,
158
- inputs=gr.Textbox(label="Date (YYYY-MM-DD)"),
159
- outputs=gr.Textbox(label="Prediction"),
160
- title="Crypto Volatility Predictor",
161
- description="Enter a date to get predicted volatility and 95% confidence interval."
162
- )
163
-
164
- if __name__ == "__main__":
165
- demo.launch()