Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,473 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
import datetime
|
| 3 |
-
import pandas as pd
|
| 4 |
-
from sklearn.preprocessing import MinMaxScaler
|
| 5 |
import numpy as np
|
| 6 |
-
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
from
|
| 10 |
-
import random
|
| 11 |
-
import re
|
| 12 |
-
|
| 13 |
-
THRESHOLDS = {
|
| 14 |
-
"BTC": {
|
| 15 |
-
"1d": 450.0,
|
| 16 |
-
"12h": 400.0,
|
| 17 |
-
"6h": 350.5,
|
| 18 |
-
"4h": 300.0,
|
| 19 |
-
"2h": 300.5,
|
| 20 |
-
|
| 21 |
-
},
|
| 22 |
-
"ETH": {
|
| 23 |
-
"1d": 80.0,
|
| 24 |
-
"12h": 68.0,
|
| 25 |
-
"6h": 45,
|
| 26 |
-
"4h": 28.0,
|
| 27 |
-
"2h": 10.5,
|
| 28 |
-
},
|
| 29 |
-
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
def get_crypto_ohlcv_data(fsym="BTC", tsym="USD", limit=365, timeframe="1d", toTs=None, api_key=None):
|
| 34 |
-
fsym = fsym.upper()
|
| 35 |
-
timeframe = timeframe.lower()
|
| 36 |
-
|
| 37 |
-
# 1. Parse timeframe for API aggregate
|
| 38 |
-
match = re.match(r"(\d+)([a-z]+)", timeframe)
|
| 39 |
-
if not match:
|
| 40 |
-
raise ValueError("Timeframe format should be like '4h' or '1d'")
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
|
|
|
| 44 |
|
| 45 |
-
# 2. Retrieve Threshold from the editable dictionary
|
| 46 |
-
# Defaults to 0.0 if the crypto or timeframe isn't found
|
| 47 |
-
crypto_data = THRESHOLDS.get(fsym, {})
|
| 48 |
-
threshold = crypto_data.get(timeframe, 0.0)
|
| 49 |
-
|
| 50 |
-
# 3. API Request Setup
|
| 51 |
-
if 'd' in unit:
|
| 52 |
-
base_url = "https://min-api.cryptocompare.com/data/histoday"
|
| 53 |
-
elif 'h' in unit:
|
| 54 |
-
base_url = "https://min-api.cryptocompare.com/data/histohour"
|
| 55 |
-
elif 'm' in unit:
|
| 56 |
-
base_url = "https://min-api.cryptocompare.com/data/histominute"
|
| 57 |
-
else:
|
| 58 |
-
raise ValueError("Unit must be 'd', 'h', or 'm'")
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
params = {
|
| 61 |
-
"fsym":
|
| 62 |
-
"tsym": tsym,
|
| 63 |
"limit": limit,
|
| 64 |
-
"aggregate":
|
| 65 |
}
|
| 66 |
-
if api_key: params["api_key"] = api_key
|
| 67 |
-
if toTs: params["toTs"] = int(toTs)
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
resp = requests.get(base_url, params=params)
|
| 70 |
resp.raise_for_status()
|
|
|
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
if "Data" in raw_data and isinstance(raw_data["Data"], dict) and "Data" in raw_data["Data"]:
|
| 75 |
-
data = raw_data["Data"]["Data"]
|
| 76 |
-
elif "Data" in raw_data and isinstance(raw_data["Data"], list):
|
| 77 |
-
data = raw_data["Data"]
|
| 78 |
-
else:
|
| 79 |
-
data = []
|
| 80 |
-
|
| 81 |
-
# 4. Process DataFrame
|
| 82 |
-
df = pd.DataFrame(data)
|
| 83 |
-
if not df.empty:
|
| 84 |
-
df["date"] = pd.to_datetime(df["time"], unit="s")
|
| 85 |
-
df.set_index("date", inplace=True)
|
| 86 |
-
df = df[["open", "high", "low", "close"]]
|
| 87 |
-
|
| 88 |
-
print("Thresold Point == ",threshold," aggregate_value ===",aggregate_value)
|
| 89 |
-
|
| 90 |
-
return df, threshold
|
| 91 |
-
|
| 92 |
-
# Calculate RSI
|
| 93 |
-
def calculate_rsi(data, window=14):
|
| 94 |
-
diff = data.diff(1).dropna()
|
| 95 |
-
gain = diff.mask(diff < 0, 0)
|
| 96 |
-
loss = diff.mask(diff > 0, 0).abs()
|
| 97 |
-
avg_gain = gain.ewm(com=window - 1, min_periods=window).mean()
|
| 98 |
-
avg_loss = loss.ewm(com=window - 1, min_periods=window).mean()
|
| 99 |
-
rs = avg_gain / avg_loss
|
| 100 |
-
rsi = 100 - (100 / (1 + rs))
|
| 101 |
-
return rsi
|
| 102 |
-
# Calculate MACD
|
| 103 |
-
def calculate_macd(data, short_window=12, long_window=26, signal_window=9):
|
| 104 |
-
exp1 = data.ewm(span=short_window, adjust=False).mean()
|
| 105 |
-
exp2 = data.ewm(span=long_window, adjust=False).mean()
|
| 106 |
-
macd = exp1 - exp2
|
| 107 |
-
signal = macd.ewm(span=signal_window, adjust=False).mean()
|
| 108 |
-
histogram = macd - signal
|
| 109 |
-
return macd, signal, histogram
|
| 110 |
-
|
| 111 |
-
def create_dataset(data, timestep=12, X_scaler=None,marketType='bull', threshold_value=0.0):
|
| 112 |
-
if X_scaler is None:
|
| 113 |
-
raise ValueError("X_scaler must be provided to inverse_transform the data.")
|
| 114 |
-
|
| 115 |
-
close_index = 3
|
| 116 |
-
X, y = [], []
|
| 117 |
|
| 118 |
-
#
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
|
|
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
if marketType == 'bull':
|
| 130 |
-
y.append(1) if diff > threshold_value else y.append(0)
|
| 131 |
-
else:
|
| 132 |
-
y.append(1) if diff < -threshold_value else y.append(0)
|
| 133 |
-
X.append(x_a)
|
| 134 |
|
| 135 |
-
|
| 136 |
-
# This will be [[4, 5, 6]] in your example
|
| 137 |
-
prediction_window = np.array([data[-timestep:]])
|
| 138 |
|
| 139 |
-
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
def
|
| 142 |
-
|
| 143 |
-
Calculate classification accuracy.
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
""
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
return
|
| 157 |
-
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
| 158 |
|
| 159 |
class LSTM(nn.Module):
|
| 160 |
def __init__(self, input_dim, hidden_dim, num_layers, output_dim):
|
| 161 |
super(LSTM, self).__init__()
|
| 162 |
self.hidden_dim = hidden_dim
|
| 163 |
self.num_layers = num_layers
|
| 164 |
-
|
| 165 |
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True)
|
| 166 |
self.fc = nn.Linear(hidden_dim, output_dim)
|
| 167 |
-
|
| 168 |
self.linear_net = nn.Sequential(
|
| 169 |
-
nn.Linear(
|
| 170 |
-
nn.BatchNorm1d(128),
|
| 171 |
-
nn.ReLU(),
|
| 172 |
-
|
| 173 |
-
nn.Linear(128,64),
|
| 174 |
-
nn.BatchNorm1d(64),
|
| 175 |
-
nn.ReLU(),
|
| 176 |
-
nn.Linear(64,32),
|
| 177 |
-
nn.BatchNorm1d(32),
|
| 178 |
-
nn.ReLU(),
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
nn.Linear(32,1),
|
| 182 |
|
| 183 |
)
|
| 184 |
-
self.relu = nn.ReLU()
|
| 185 |
-
self.sigmoid = nn.Sigmoid()
|
| 186 |
|
| 187 |
def forward(self, x):
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
return out
|
| 192 |
|
| 193 |
|
| 194 |
-
def
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
else:
|
| 368 |
-
print(f"Iteration 2 failed on attempt {attempt + 1}. Adjusting parameters randomly and retrying...")
|
| 369 |
-
|
| 370 |
-
if not iteration_2_success_flag:
|
| 371 |
-
print(f"Warning: Iteration 2 could not achieve successful training after {max_retries_per_iteration} attempts. Using results from the last attempt (if any).")
|
| 372 |
-
all_iteration_results.append({"probability": prob2, "class": class2, "successful": iteration_2_success_flag})
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
# --- Iteration 3 ---
|
| 376 |
-
print(f"\n--- Starting Iteration 3 ---")
|
| 377 |
-
iteration_3_success_flag = False
|
| 378 |
-
base_limit_3 = Limit
|
| 379 |
-
base_timeframe_3 = Timeframe
|
| 380 |
-
|
| 381 |
-
prob3 = 0.0
|
| 382 |
-
class3 = 0
|
| 383 |
-
|
| 384 |
-
for attempt in range(max_retries_per_iteration):
|
| 385 |
-
rand_limit_offset = random.randrange(-100, 101, 2)
|
| 386 |
-
rand_timeframe_offset = random.randrange(-2, 9, 2)
|
| 387 |
-
current_limit_for_attempt = max(100, base_limit_3 + rand_limit_offset)
|
| 388 |
-
current_timeframe_for_attempt = max(5, base_timeframe_3 + rand_timeframe_offset)
|
| 389 |
-
|
| 390 |
-
print(f"Attempt {attempt + 1} for Iteration 3 with Limit={current_limit_for_attempt}, Timeframe={current_timeframe_for_attempt}...")
|
| 391 |
-
current_prob, current_class_val, success = _train_and_predict(CryptoName, current_limit_for_attempt, current_timeframe_for_attempt, marketType, ohlcv_timeframe)
|
| 392 |
-
|
| 393 |
-
if success:
|
| 394 |
-
print(f"Iteration 3 successful on attempt {attempt + 1}.")
|
| 395 |
-
prob3 = current_prob
|
| 396 |
-
class3 = current_class_val
|
| 397 |
-
iteration_3_success_flag = True
|
| 398 |
-
break
|
| 399 |
-
else:
|
| 400 |
-
print(f"Iteration 3 failed on attempt {attempt + 1}. Adjusting parameters randomly and retrying...")
|
| 401 |
-
|
| 402 |
-
if not iteration_3_success_flag:
|
| 403 |
-
print(f"Warning: Iteration 3 could not achieve successful training after {max_retries_per_iteration} attempts. Using results from the last attempt (if any).")
|
| 404 |
-
all_iteration_results.append({"probability": prob3, "class": class3, "successful": iteration_3_success_flag})
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
# --- Combine Predictions (Majority Vote) ---
|
| 408 |
-
print(f"\n--- Combining Final Prediction (Majority Vote) ---")
|
| 409 |
-
|
| 410 |
-
classes = [res['class'] for res in all_iteration_results]
|
| 411 |
-
probabilities = [res['probability'] for res in all_iteration_results]
|
| 412 |
-
|
| 413 |
-
# Determine the majority class
|
| 414 |
-
count_0 = classes.count(0)
|
| 415 |
-
count_1 = classes.count(1)
|
| 416 |
-
|
| 417 |
-
if count_1 >= 2: # If 2 or more predictions are 1
|
| 418 |
-
final_combined_class = 1
|
| 419 |
-
else: # If 2 or more predictions are 0
|
| 420 |
-
final_combined_class = 0
|
| 421 |
-
|
| 422 |
-
# Calculate the average probability for the majority class
|
| 423 |
-
majority_class_probs = [p for c, p in zip(classes, probabilities) if c == final_combined_class]
|
| 424 |
-
|
| 425 |
-
if majority_class_probs:
|
| 426 |
-
final_combined_prob = sum(majority_class_probs) / len(majority_class_probs)
|
| 427 |
-
else:
|
| 428 |
-
# This case should ideally not happen with 3 iterations and a majority vote
|
| 429 |
-
# But as a fallback, average all probabilities if no majority is clearly identified
|
| 430 |
-
# (e.g., if only one successful iteration or all predictions are somehow ambiguous)
|
| 431 |
-
final_combined_prob = sum(probabilities) / len(probabilities) if probabilities else 0.0
|
| 432 |
-
|
| 433 |
-
print(f"Combined Probability: {final_combined_prob:.4f}")
|
| 434 |
-
print(f"Combined Class (0 for no significant change, 1 for significant change): {final_combined_class}")
|
| 435 |
-
|
| 436 |
-
return {
|
| 437 |
-
"crypto_name": CryptoName,
|
| 438 |
-
"iteration_1_result": all_iteration_results[0],
|
| 439 |
-
"iteration_2_result": all_iteration_results[1],
|
| 440 |
-
"iteration_3_result": all_iteration_results[2],
|
| 441 |
-
"final_combined_prediction": {"probability": final_combined_prob, "class": final_combined_class}
|
| 442 |
-
}
|
| 443 |
|
| 444 |
-
import gradio as gr
|
| 445 |
-
import requests
|
| 446 |
-
import datetime
|
| 447 |
|
| 448 |
SECRET_CODE = "ilovemypythonprogram"
|
| 449 |
BASE_API_URL = "https://my-model-api.shares.zrok.io/api/training/"
|
| 450 |
|
| 451 |
-
def
|
| 452 |
-
timeframe_lstm=12
|
| 453 |
# Calculate validation_date
|
| 454 |
-
|
| 455 |
-
if 'd' in ohlcv_timeframe.lower():
|
| 456 |
-
validation_date = now_utc.strftime("%Y-%m-%d")
|
| 457 |
-
elif 'h' in ohlcv_timeframe.lower():
|
| 458 |
-
validation_date = now_utc.strftime("%Y-%m-%d-%H")
|
| 459 |
-
else:
|
| 460 |
-
validation_date = now_utc.strftime("%Y-%m-%d-%H-%M") # Fallback for minutes or other units
|
| 461 |
|
|
|
|
|
|
|
| 462 |
# 1. Send PENDING status
|
| 463 |
pending_url = f"{BASE_API_URL}insert-pending/"
|
| 464 |
pending_data = {
|
| 465 |
"secret": SECRET_CODE,
|
| 466 |
"crypto_name": crypto_name,
|
| 467 |
-
"timeframe":
|
| 468 |
-
"
|
| 469 |
-
|
| 470 |
}
|
|
|
|
| 471 |
print(f"Sending pending status for {crypto_name}...")
|
| 472 |
try:
|
| 473 |
print(f"Pending status data: {pending_data}")
|
|
@@ -477,52 +339,23 @@ def predict_crypto_gradio(crypto_name, limit, market_type, ohlcv_timeframe):
|
|
| 477 |
except requests.exceptions.RequestException as e:
|
| 478 |
print(f"Error sending pending status: {e}")
|
| 479 |
return f"Error sending pending status: {e}"
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
Timeframe=timeframe_lstm, # Renamed to avoid conflict with ohlcv_timeframe
|
| 489 |
-
marketType=market_type,
|
| 490 |
-
ohlcv_timeframe=ohlcv_timeframe,
|
| 491 |
-
max_retries_per_iteration=5
|
| 492 |
-
)
|
| 493 |
-
|
| 494 |
-
# Format the output string as requested
|
| 495 |
-
output_str = f"Prediction 1: {results['iteration_1_result']['probability']:.4f} (Binary: {results['iteration_1_result']['class']})\n"
|
| 496 |
-
output_str += f"Prediction 2: {results['iteration_2_result']['probability']:.4f} (Binary: {results['iteration_2_result']['class']})\n"
|
| 497 |
-
output_str += f"Prediction 3: {results['iteration_3_result']['probability']:.4f} (Binary: {results['iteration_3_result']['class']})\n"
|
| 498 |
-
output_str += f"Combined Probability: {results['final_combined_prediction']['probability']:.4f}\n"
|
| 499 |
-
output_str += f"Combined Binary: {results['final_combined_prediction']['class']}\n"
|
| 500 |
-
|
| 501 |
-
# Generate the message based on combined prediction and market type
|
| 502 |
-
combined_binary = results['final_combined_prediction']['class']
|
| 503 |
-
message = ""
|
| 504 |
-
if market_type.lower() == 'bull' and combined_binary == 1:
|
| 505 |
-
message = f"Message: You should consider buying, as the stock might increase by approximately {threshold:.2f} points.\n"
|
| 506 |
-
elif market_type.lower() == 'bearish' and combined_binary == 1:
|
| 507 |
-
message = f"Message: You should consider selling, as the stock might decrease by approximately {threshold:.2f} points.\n"
|
| 508 |
-
elif combined_binary == 0:
|
| 509 |
-
message = "Message: No significant change is predicted for the specified market type.\n"
|
| 510 |
-
else:
|
| 511 |
-
message = "Message: Prediction is uncertain or not applicable to the selected market type and binary outcome.\n"
|
| 512 |
-
|
| 513 |
-
output_str += message
|
| 514 |
-
|
| 515 |
-
# 2. Send TRAINED status
|
| 516 |
trained_url = f"{BASE_API_URL}insert-trained/"
|
| 517 |
trained_data = {
|
| 518 |
"pendingId": pending_resp.json().get("id"),
|
| 519 |
"secret": SECRET_CODE,
|
| 520 |
"crypto_name": crypto_name,
|
| 521 |
-
"timeframe":
|
| 522 |
-
"
|
| 523 |
-
"
|
| 524 |
-
|
| 525 |
-
"market_type":market_type# Send the full results dictionary
|
| 526 |
}
|
| 527 |
try:
|
| 528 |
trained_resp = requests.post(trained_url, json=trained_data)
|
|
@@ -531,21 +364,27 @@ def predict_crypto_gradio(crypto_name, limit, market_type, ohlcv_timeframe):
|
|
| 531 |
except requests.exceptions.RequestException as e:
|
| 532 |
print(f"Error sending trained status: {e}")
|
| 533 |
output_str += f"\nError sending trained status to backend: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 534 |
|
| 535 |
-
return output_str
|
| 536 |
|
| 537 |
-
#
|
| 538 |
iface = gr.Interface(
|
| 539 |
-
fn=
|
| 540 |
inputs=[
|
| 541 |
-
gr.
|
| 542 |
-
gr.
|
| 543 |
-
gr.
|
| 544 |
-
gr.Dropdown(["1d", "
|
| 545 |
],
|
| 546 |
-
outputs=gr.Textbox(label="Prediction
|
| 547 |
-
title="Cryptocurrency Price
|
| 548 |
-
description="
|
|
|
|
| 549 |
)
|
| 550 |
|
| 551 |
-
iface.launch(
|
|
|
|
| 1 |
+
# import all the necessary requirements
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
import requests
|
| 6 |
import datetime
|
|
|
|
|
|
|
| 7 |
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from sklearn.preprocessing import StandardScaler
|
| 10 |
+
import gradio as gr
|
| 11 |
+
from datetime import datetime, timezone, timedelta
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
import requests
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import re # Added missing import
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
timesteps = 16
|
| 19 |
+
future_forcecast_steps = 10
|
| 20 |
+
|
| 21 |
+
input_dim = 1
|
| 22 |
+
hidden_dim = 24
|
| 23 |
+
num_layers = 2
|
| 24 |
+
output_dim = 1
|
| 25 |
+
num_epochs = 1800
|
| 26 |
+
|
| 27 |
+
def get_crypto_ohlcv(crypto_name="BTC", tsym="USD", timeframe="1d", limit=100, api_key=None):
|
| 28 |
+
"""
|
| 29 |
+
Fetches OHLCV data from CryptoCompare with support for various timeframes.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
crypto_name (str): Symbol (e.g., "BTC", "ETH").
|
| 33 |
+
tsym (str): Target currency (e.g., "USD", "USDT").
|
| 34 |
+
timeframe (str): Support for "1h", "4h", "6h", "12h", "1d", "3d".
|
| 35 |
+
limit (int): Number of data points (max 2000 per request).
|
| 36 |
+
api_key (str): Your CryptoCompare API Key.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
# 1. Map timeframes to endpoints and aggregation levels
|
| 40 |
+
# format: { timeframe_string: (endpoint_suffix, aggregate_value) }
|
| 41 |
+
tf_map = {
|
| 42 |
+
"1h": ("hour", 1),
|
| 43 |
+
"4h": ("hour", 4),
|
| 44 |
+
"6h": ("hour", 6),
|
| 45 |
+
"12h": ("hour", 12),
|
| 46 |
+
"1d": ("day", 1),
|
| 47 |
+
"2d": ("day", 2),
|
| 48 |
+
"3d": ("day", 3),
|
| 49 |
+
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
if timeframe not in tf_map:
|
| 53 |
+
raise ValueError(f"Unsupported timeframe: {timeframe}. Use {list(tf_map.keys())}")
|
| 54 |
+
|
| 55 |
+
endpoint_type, agg = tf_map[timeframe]
|
| 56 |
+
base_url = f"https://min-api.cryptocompare.com/data/v2/histo{endpoint_type}"
|
| 57 |
+
|
| 58 |
+
# 2. Setup Parameters
|
| 59 |
params = {
|
| 60 |
+
"fsym": crypto_name.upper(),
|
| 61 |
+
"tsym": tsym.upper(),
|
| 62 |
"limit": limit,
|
| 63 |
+
"aggregate": agg
|
| 64 |
}
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
if api_key:
|
| 67 |
+
params["api_key"] = api_key
|
| 68 |
+
|
| 69 |
+
# 3. Request Data
|
| 70 |
resp = requests.get(base_url, params=params)
|
| 71 |
resp.raise_for_status()
|
| 72 |
+
json_data = resp.json()
|
| 73 |
|
| 74 |
+
if json_data.get("Response") == "Error":
|
| 75 |
+
raise RuntimeError(f"CryptoCompare Error: {json_data.get('Message')}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
# 4. Process Data
|
| 78 |
+
# v2 API stores data inside ['Data']['Data']
|
| 79 |
+
data_list = json_data["Data"]["Data"]
|
| 80 |
+
df = pd.DataFrame(data_list)
|
| 81 |
|
| 82 |
+
# Convert timestamp and clean up
|
| 83 |
+
df["date"] = pd.to_datetime(df["time"], unit="s")
|
| 84 |
+
df.set_index("date", inplace=True)
|
| 85 |
|
| 86 |
+
# Standardize columns
|
| 87 |
+
df = df[["open", "high", "low", "close", "volumefrom", "volumeto"]]
|
| 88 |
+
df.columns = ["open", "high", "low", "close", "volume_base", "volume_quote"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
return df
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
# --- Examples ---
|
| 93 |
+
# df_4h = get_crypto_ohlcv(crypto_name="ETH", timeframe="4h", limit=100)
|
| 94 |
+
# df_1d = get_crypto_ohlcv(crypto_name="SOL", timeframe="1d", limit=365)
|
| 95 |
|
| 96 |
+
def prepare_production_data(data_array, steps):
|
| 97 |
+
X, y = [], []
|
|
|
|
| 98 |
|
| 99 |
+
# We loop so that the last 'y' is the very last available data point
|
| 100 |
+
# Example: if len is 100 and steps is 10, the last i is 99.
|
| 101 |
+
# X takes [89:99], y takes [99]
|
| 102 |
+
for i in range(steps, len(data_array)):
|
| 103 |
+
X.append(data_array[i-steps:i, 0])
|
| 104 |
+
y.append(data_array[i, 0])
|
| 105 |
|
| 106 |
+
X, y = np.array(X), np.array(y)
|
| 107 |
+
|
| 108 |
+
# --- 5. The "Tomorrow" Input ---
|
| 109 |
+
# This is the last 'steps' of the dataset (e.g., 91-100)
|
| 110 |
+
# This has no 'y' because 'y' is the future we want to predict.
|
| 111 |
+
x_latest_window = data_array[-steps:].reshape(1, steps)
|
| 112 |
+
|
| 113 |
+
return X, y, x_latest_window
|
|
|
|
| 114 |
|
| 115 |
class LSTM(nn.Module):
|
| 116 |
def __init__(self, input_dim, hidden_dim, num_layers, output_dim):
|
| 117 |
super(LSTM, self).__init__()
|
| 118 |
self.hidden_dim = hidden_dim
|
| 119 |
self.num_layers = num_layers
|
| 120 |
+
|
| 121 |
self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True)
|
| 122 |
self.fc = nn.Linear(hidden_dim, output_dim)
|
|
|
|
| 123 |
self.linear_net = nn.Sequential(
|
| 124 |
+
nn.Linear(hidden_dim, 1),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
)
|
|
|
|
|
|
|
| 127 |
|
| 128 |
def forward(self, x):
|
| 129 |
+
batch_size = x.shape[0]
|
| 130 |
+
# Initialize h0 and c0 on the same device as x
|
| 131 |
+
h0 = torch.zeros(self.num_layers, batch_size, self.hidden_dim).to(x.device)
|
| 132 |
+
c0 = torch.zeros(self.num_layers, batch_size, self.hidden_dim).to(x.device)
|
| 133 |
+
out, (hn, cn) = self.lstm(x, (h0, c0)) # No need to detach if they don't require gradients and are not part of graph
|
| 134 |
+
out = self.linear_net(out[:, -1, :])
|
| 135 |
+
|
| 136 |
return out
|
| 137 |
|
| 138 |
|
| 139 |
+
def get_expiry_date(timeframe):
|
| 140 |
+
# 1. Get current time in UTC
|
| 141 |
+
now = datetime.now(timezone.utc)
|
| 142 |
+
|
| 143 |
+
# 2. Parse the timeframe (e.g., "2h" -> 2 and "h")
|
| 144 |
+
# This regex finds the digits and the letters separately
|
| 145 |
+
match = re.match(r"(\d+)([hd])", timeframe.lower())
|
| 146 |
+
|
| 147 |
+
if not match:
|
| 148 |
+
raise ValueError("Invalid timeframe format. Use '[int]h' or '[int]d'.")
|
| 149 |
+
|
| 150 |
+
value = int(match.group(1))
|
| 151 |
+
unit = match.group(2)
|
| 152 |
+
|
| 153 |
+
# 3. Calculate expiry (2 * the timeframe value)
|
| 154 |
+
multiplier = 2
|
| 155 |
+
expiry_value = value * multiplier
|
| 156 |
+
|
| 157 |
+
if unit == 'd':
|
| 158 |
+
expiry_date = now + timedelta(days=expiry_value)
|
| 159 |
+
else: # unit == 'h'
|
| 160 |
+
expiry_date = now + timedelta(hours=expiry_value)
|
| 161 |
+
|
| 162 |
+
return expiry_date
|
| 163 |
+
|
| 164 |
+
# Some training zones
|
| 165 |
+
def training_zone(model, criterion, optimiser, X_train_t, Y_train_t, num_epochs):
|
| 166 |
+
best_train_loss = float('inf')
|
| 167 |
+
model_save_path = "best_model.pth"
|
| 168 |
+
|
| 169 |
+
print(f"Starting Production Training...")
|
| 170 |
+
|
| 171 |
+
# Enable anomaly detection for debugging
|
| 172 |
+
import torch.autograd
|
| 173 |
+
torch.autograd.set_detect_anomaly(True)
|
| 174 |
+
|
| 175 |
+
for epoch in range(num_epochs):
|
| 176 |
+
model.train()
|
| 177 |
+
optimiser.zero_grad()
|
| 178 |
+
|
| 179 |
+
# Forward pass
|
| 180 |
+
y_pred = model(X_train_t)
|
| 181 |
+
loss = criterion(y_pred, Y_train_t)
|
| 182 |
+
|
| 183 |
+
# Backward pass
|
| 184 |
+
loss.backward()
|
| 185 |
+
optimiser.step()
|
| 186 |
+
|
| 187 |
+
current_loss = loss.item()
|
| 188 |
+
|
| 189 |
+
# --- 2. Save Model on Improvement ---
|
| 190 |
+
# Only save the best model if it's past epoch 1000
|
| 191 |
+
if current_loss < best_train_loss:
|
| 192 |
+
best_train_loss = current_loss
|
| 193 |
+
if epoch > 1000:
|
| 194 |
+
# Save the model state
|
| 195 |
+
torch.save(model.state_dict(), model_save_path)
|
| 196 |
+
|
| 197 |
+
if epoch % 100 == 0:
|
| 198 |
+
print(f"Epoch {epoch:04d} | New Best Loss: {current_loss:.6f} | Model Saved")
|
| 199 |
+
|
| 200 |
+
# Disable anomaly detection after training (optional, but good practice)
|
| 201 |
+
torch.autograd.set_detect_anomaly(False)
|
| 202 |
+
|
| 203 |
+
print("-" * 30)
|
| 204 |
+
print(f"Training Complete. Best Loss: {best_train_loss:.6f}")
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# predicting zone
|
| 208 |
+
def predict_zone(model, model_save_path, x_future_input, future_forecast_steps, scaler, timesteps):
|
| 209 |
+
|
| 210 |
+
# --- 1. Load and Set to Eval Mode ---
|
| 211 |
+
model.load_state_dict(torch.load(model_save_path))
|
| 212 |
+
model.eval()
|
| 213 |
+
|
| 214 |
+
forecasted_results = []
|
| 215 |
+
# Ensure we start with the very last available window from the real data
|
| 216 |
+
current_window = torch.from_numpy(x_future_input).float().to("cpu")
|
| 217 |
+
|
| 218 |
+
# Ensure it is reshaped to (1, timesteps, 1)
|
| 219 |
+
current_window = current_window.view(1, timesteps, 1)
|
| 220 |
+
print(current_window.shape)
|
| 221 |
+
|
| 222 |
+
# --- 2. Recursive Prediction Loop ---
|
| 223 |
+
with torch.no_grad():
|
| 224 |
+
for i in range(future_forecast_steps):
|
| 225 |
+
# Predict the next point (Day i+1)
|
| 226 |
+
prediction = model(current_window)
|
| 227 |
+
|
| 228 |
+
# Store prediction
|
| 229 |
+
forecasted_results.append(prediction.item())
|
| 230 |
+
|
| 231 |
+
# SLIDE THE WINDOW:
|
| 232 |
+
# 1. Remove the oldest price: current_window[:, 1:, :]
|
| 233 |
+
# 2. Append the new prediction: prediction.unsqueeze(1)
|
| 234 |
+
new_entry = prediction.unsqueeze(1)
|
| 235 |
+
current_window = torch.cat((current_window[:, 1:, :], new_entry), dim=1)
|
| 236 |
+
|
| 237 |
+
# --- 3. Unscale Results ---
|
| 238 |
+
forecasted_results_np = np.array(forecasted_results).reshape(-1, 1)
|
| 239 |
+
final_prices = scaler.inverse_transform(forecasted_results_np).flatten()
|
| 240 |
+
|
| 241 |
+
# --- 4. Visualization ---
|
| 242 |
+
plt.figure(figsize=(10, 5))
|
| 243 |
+
|
| 244 |
+
# Plotting the 10-day trend
|
| 245 |
+
days = range(1, future_forecast_steps + 1)
|
| 246 |
+
plt.plot(days, final_prices, marker='o', linestyle='-', color='#2ca02c', label='Forecasted Trend')
|
| 247 |
+
|
| 248 |
+
# Annotate the values on the graph for clarity
|
| 249 |
+
for i, price in enumerate(final_prices):
|
| 250 |
+
plt.annotate(f'{price:.2f}', (days[i], final_prices[i]),
|
| 251 |
+
textcoords="offset points", xytext=(0,10), ha='center', fontsize=8)
|
| 252 |
+
|
| 253 |
+
plt.title(f"Next {future_forecast_steps} Days: Predicted Price Pattern")
|
| 254 |
+
plt.xlabel("Days Ahead")
|
| 255 |
+
plt.ylabel("Price")
|
| 256 |
+
plt.xticks(days) # Ensure every day is marked on the X-axis
|
| 257 |
+
plt.grid(True, alpha=0.3, linestyle='--')
|
| 258 |
+
plt.legend()
|
| 259 |
+
plt.tight_layout()
|
| 260 |
+
plt.show()
|
| 261 |
+
# Removed redundant datetime import
|
| 262 |
+
# --- 5. Clean Console Output ---
|
| 263 |
+
print(f"\n--- {future_forecast_steps}-Day Future Forecast ---")
|
| 264 |
+
for day, price in enumerate(final_prices, 1):
|
| 265 |
+
print(f"Day {day}: {price:.2f}")
|
| 266 |
+
return final_prices
|
| 267 |
+
|
| 268 |
+
# Training Loop
|
| 269 |
+
def train_full(limit,tsym,crypto_name,timeframe):
|
| 270 |
+
df = get_crypto_ohlcv(crypto_name=crypto_name, tsym=tsym, timeframe=timeframe, limit=limit)
|
| 271 |
+
print(df.tail())
|
| 272 |
+
df = df.iloc[:-1]
|
| 273 |
+
|
| 274 |
+
data = df.copy()
|
| 275 |
+
data_series = data['close'].values.reshape(-1, 1)
|
| 276 |
+
|
| 277 |
+
# --- 2. Initialize Model, Criterion, Optimiser within the function ---
|
| 278 |
+
model = LSTM(input_dim=input_dim, hidden_dim=hidden_dim, output_dim=output_dim, num_layers=num_layers)
|
| 279 |
+
criterion = torch.nn.MSELoss(reduction='mean')
|
| 280 |
+
optimiser = torch.optim.Adam(model.parameters(), lr=0.01)
|
| 281 |
+
|
| 282 |
+
# --- 3. Scaling (Full Dataset) ---
|
| 283 |
+
# Since we are in "Production/Final Train" mode, we fit on everything
|
| 284 |
+
scaler = StandardScaler()
|
| 285 |
+
scaled_data = scaler.fit_transform(data_series)
|
| 286 |
+
|
| 287 |
+
# creating the data
|
| 288 |
+
x_train, y_train, x_future_input = prepare_production_data(scaled_data, timesteps)
|
| 289 |
+
|
| 290 |
+
print(f"Total data points: {len(data_series)}")
|
| 291 |
+
print(f"x_train shape: {x_train.shape}") # Should be (90, 10) if data is 100
|
| 292 |
+
print(f"y_train shape: {y_train.shape}") # Should be (90,)
|
| 293 |
+
|
| 294 |
+
# Verify the last training target is indeed the last value in our data
|
| 295 |
+
last_actual_val = data_series[-1][0]
|
| 296 |
+
last_y_unscaled = scaler.inverse_transform(y_train[-1].reshape(-1, 1))[0][0]
|
| 297 |
+
|
| 298 |
+
print(f"Last available price in data: {last_actual_val}")
|
| 299 |
+
print(f"Last target (y) in training: {last_y_unscaled}")
|
| 300 |
+
|
| 301 |
+
# Verify the input for "Tomorrow"
|
| 302 |
+
future_window_unscaled = scaler.inverse_transform(x_future_input).flatten()
|
| 303 |
+
print(f"Window to predict tomorrow: {future_window_unscaled}")
|
| 304 |
+
# converting to the torch
|
| 305 |
+
X_train_t = torch.Tensor(x_train).unsqueeze(-1)
|
| 306 |
+
Y_train_t = torch.Tensor(y_train).unsqueeze(-1)
|
| 307 |
+
# training zone
|
| 308 |
+
training_zone(model, criterion, optimiser, X_train_t,Y_train_t, num_epochs)
|
| 309 |
+
# prediction zone
|
| 310 |
+
predicted_array = predict_zone(model, "best_model.pth",x_future_input,future_forcecast_steps,scaler, timesteps)
|
| 311 |
+
return predicted_array
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
SECRET_CODE = "ilovemypythonprogram"
|
| 315 |
BASE_API_URL = "https://my-model-api.shares.zrok.io/api/training/"
|
| 316 |
|
| 317 |
+
def run_prediction_for_gradio(limit, tsym, crypto_name, timeframe):
|
|
|
|
| 318 |
# Calculate validation_date
|
| 319 |
+
now = datetime.now(timezone.utc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
|
| 321 |
+
# 2. Add 2 hours using timedelta
|
| 322 |
+
future_date = now + timedelta(hours=2)
|
| 323 |
# 1. Send PENDING status
|
| 324 |
pending_url = f"{BASE_API_URL}insert-pending/"
|
| 325 |
pending_data = {
|
| 326 |
"secret": SECRET_CODE,
|
| 327 |
"crypto_name": crypto_name,
|
| 328 |
+
"timeframe": timeframe,
|
| 329 |
+
"expiry_date": future_date.isoformat() # Convert datetime to ISO 8601 string
|
| 330 |
+
|
| 331 |
}
|
| 332 |
+
|
| 333 |
print(f"Sending pending status for {crypto_name}...")
|
| 334 |
try:
|
| 335 |
print(f"Pending status data: {pending_data}")
|
|
|
|
| 339 |
except requests.exceptions.RequestException as e:
|
| 340 |
print(f"Error sending pending status: {e}")
|
| 341 |
return f"Error sending pending status: {e}"
|
| 342 |
+
# Call the train_full function to get predictions
|
| 343 |
+
predicted_values = train_full(limit, tsym, crypto_name, timeframe)
|
| 344 |
+
|
| 345 |
+
# Initialize output_str before potential use in except block
|
| 346 |
+
output_str = ""
|
| 347 |
+
# finally inserting the actual data over the network
|
| 348 |
+
expiry_date = get_expiry_date(timeframe)
|
| 349 |
+
# 1. Send TRAINED status
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
trained_url = f"{BASE_API_URL}insert-trained/"
|
| 351 |
trained_data = {
|
| 352 |
"pendingId": pending_resp.json().get("id"),
|
| 353 |
"secret": SECRET_CODE,
|
| 354 |
"crypto_name": crypto_name,
|
| 355 |
+
"timeframe": timeframe,
|
| 356 |
+
"results": predicted_values.tolist(), # Convert numpy array to list for JSON serialization
|
| 357 |
+
"expiry_date": expiry_date.isoformat() # Convert datetime to ISO 8601 string
|
| 358 |
+
|
|
|
|
| 359 |
}
|
| 360 |
try:
|
| 361 |
trained_resp = requests.post(trained_url, json=trained_data)
|
|
|
|
| 364 |
except requests.exceptions.RequestException as e:
|
| 365 |
print(f"Error sending trained status: {e}")
|
| 366 |
output_str += f"\nError sending trained status to backend: {e}"
|
| 367 |
+
# Format the predicted values for display in Gradio
|
| 368 |
+
output_string = f"--- Next {future_forcecast_steps}-Day Future Forecast ---\n"
|
| 369 |
+
for day, price in enumerate(predicted_values, 1):
|
| 370 |
+
output_string += f"Day {day}: {price:.2f}\n"
|
| 371 |
+
return output_string
|
| 372 |
+
|
| 373 |
|
|
|
|
| 374 |
|
| 375 |
+
# Create the Gradio interface
|
| 376 |
iface = gr.Interface(
|
| 377 |
+
fn=run_prediction_for_gradio,
|
| 378 |
inputs=[
|
| 379 |
+
gr.Slider(minimum=100, maximum=2000, value=800, step=100, label="Limit (Number of data points)"),
|
| 380 |
+
gr.Dropdown(choices=["USD", "EUR", "GBP"], value="USD", label="Target Symbol (tsym)"),
|
| 381 |
+
gr.Dropdown(choices=["BTC", "ETH", "SOL"], value="ETH", label="Crypto Name"),
|
| 382 |
+
gr.Dropdown(choices=["1d", "3d", "1h", "4h", "6h", "12h"], value="1d", label="Timeframe")
|
| 383 |
],
|
| 384 |
+
outputs=gr.Textbox(label="Prediction Output", lines=8),
|
| 385 |
+
title="Cryptocurrency Price Predictor",
|
| 386 |
+
description="Enter parameters to get a 10-day price forecast for the selected cryptocurrency.",
|
| 387 |
+
allow_flagging="never"
|
| 388 |
)
|
| 389 |
|
| 390 |
+
iface.launch(server_name="0.0.0.0", debug=True)
|