freegpu commited on
Commit
26c5c67
·
verified ·
1 Parent(s): 9e76b2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +311 -472
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
- from sklearn.model_selection import train_test_split
7
- import torch
8
- import torch.nn as nn
9
- from torch.utils.data import DataLoader,TensorDataset
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
- aggregate_value = int(match.group(1))
43
- unit = match.group(2)
 
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": fsym,
62
- "tsym": tsym,
63
  "limit": limit,
64
- "aggregate": aggregate_value
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
- # Accessing the nested Data list
73
- raw_data = resp.json()
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
- # 1. Training/Validation pairs
119
- for i in range(len(data) - timestep):
120
- x_a = data[i : i + timestep]
121
- x_b = data[i + timestep]
122
 
123
- scaled_a = X_scaler.inverse_transform(x_a[-1].reshape(1, -1))[0][close_index]
124
- scaled_b = X_scaler.inverse_transform(x_b.reshape(1, -1))[0][close_index]
 
125
 
126
- # If the next day's close price is significantly higher (e.g., > threshold_value USD), classify as 1 (increase)
127
- # Otherwise, classify as 0 (no significant increase)
128
- diff = scaled_b - scaled_a
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
- # 2. The "Future" window (The very last sequence in the data)
136
- # This will be [[4, 5, 6]] in your example
137
- prediction_window = np.array([data[-timestep:]])
138
 
139
- return np.array(X), np.array(y), prediction_window
 
 
140
 
141
- def calculate_accuracy(y_true, y_pred):
142
- """
143
- Calculate classification accuracy.
144
 
145
- Args:
146
- y_true (array-like): true labels (0 or 1).
147
- y_pred (array-like): predicted labels (0 or 1).
 
 
 
148
 
149
- Returns:
150
- float: accuracy score (0.0 to 1.0).
151
- """
152
- y_true = np.array(y_true)
153
- y_pred = np.array(y_pred)
154
- correct = np.sum(y_true == y_pred)
155
- accuracy = correct / len(y_true)
156
- return accuracy
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
- self.batchNorm = nn.BatchNorm1d
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(256,128),
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
- out, _ = self.lstm(x) # Let PyTorch create h0, c0 automatically
189
- out = self.fc(out[:, -1, :])
190
- out = self.linear_net(out)
 
 
 
 
191
  return out
192
 
193
 
194
- def train_full(model, dataloader, X_test, y_test, criterion, optimizer, num_epochs=100):
195
- avg_loss_history = []
196
- best_val_loss = 10000.0 # Initialize with a high value
197
-
198
- for epoch in range(num_epochs):
199
- avg_loss = [] # Stores training loss for current epoch
200
- model.train()
201
- for x, y in dataloader:
202
- optimizer.zero_grad()
203
- outputs = model(x).to(device).flatten()
204
- loss = criterion(outputs, y)
205
- loss.backward()
206
- avg_loss.append(loss.item())
207
- optimizer.step()
208
- avg_loss_history.append(np.average(avg_loss)) # Store average train loss for current epoch
209
-
210
- model.eval()
211
- with torch.no_grad():
212
- test_preds = model(X_test).to(device).flatten()
213
- test_loss = criterion(test_preds, y_test)
214
-
215
- # Update best_val_loss observed so far
216
- if test_loss.item() < best_val_loss:
217
- best_val_loss = test_loss.item()
218
-
219
- # Early stopping condition based on user feedback
220
- if test_loss.item() < 0.13 and np.average(avg_loss) <0.13: # Stop if test loss is below this threshold
221
- test_accuracy = calculate_accuracy(y_test.detach().cpu().numpy(), torch.round(torch.sigmoid(test_preds)).detach().cpu().numpy())
222
- print(f"Early stopping at Epoch {epoch+1} due to Test Loss = {test_loss.item():.4f} (Accuracy = {test_accuracy:.2f})")
223
- return True # Indicate successful training iteration
224
-
225
- # Original periodic logging
226
- if (epoch + 1) % 50 == 0 or epoch == 0:
227
- # Re-evaluate test_loss and accuracy for logging purposes, ensuring up-to-date values
228
- # (test_loss and best_val_loss would be current from above eval block)
229
- current_test_accuracy = calculate_accuracy(y_test.cpu().numpy(), torch.round(torch.sigmoid(test_preds)).cpu().numpy())
230
- print(f"Epoch [{epoch+1}/{num_epochs}], Avg Train Loss: {avg_loss_history[-1]:.4f} Current Test Loss: {test_loss.item():.4f} Test Accuracy :{current_test_accuracy} Best Validation Loss Seen: {best_val_loss:.4f}")
231
-
232
- print(f"Training completed {num_epochs} epochs without reaching early stopping threshold.")
233
- return False # Indicate unsuccessful training iteration
234
-
235
-
236
-
237
- def _train_and_predict(CryptoName, Limit, Timeframe, marketType, ohlcv_timeframe):
238
- # 1. Data Retrieval
239
- print(f"Fetching data for {CryptoName} for {Limit} days with timeframe {ohlcv_timeframe}...")
240
- df, threshold_value = get_crypto_ohlcv_data(fsym=CryptoName, limit=Limit, timeframe=ohlcv_timeframe)
241
-
242
- # 2. Feature Engineering (RSI and MACD)
243
- df['RSI'] = calculate_rsi(df['close'])
244
- df['MACD'], df['MACD_Signal'], df['MACD_Histogram'] = calculate_macd(df['close'])
245
-
246
- # 3. Data Cleaning: Drop rows with any NaN values that resulted from indicator calculations
247
- df_cleaned = df.dropna()
248
- # remove last row of df
249
- df_cleaned = df_cleaned.iloc[:-1]
250
- data = df_cleaned.copy()
251
- print(f"Original DataFrame shape: {df.shape}, Cleaned DataFrame shape: {data.shape}")
252
- print(df_cleaned.tail())
253
- # 4. Scaling
254
- X_scaler = MinMaxScaler()
255
- X_scaled = X_scaler.fit_transform(data)
256
-
257
- # 5. Dataset Creation
258
- # Timeframe parameter from user will be used as timestep
259
- timestep = Timeframe
260
- x_train, y_train, final_preds_raw = create_dataset(X_scaled, timestep=timestep, X_scaler=X_scaler, marketType=marketType, threshold_value=threshold_value)
261
- print(f"Dataset created with timestep={timestep}. X_train shape: {x_train.shape}, y_train shape: {y_train.shape}, final_preds_raw shape: (1, 12, 8)")
262
-
263
- # 6. Train-Test Split
264
- x_t, x_tes, y_t, y_tes = train_test_split(x_train, y_train, test_size=0.015, shuffle=False)
265
-
266
- # 7. Tensor Conversion and move to device
267
- X_train_t = torch.tensor(x_t, dtype=torch.float32).to(device)
268
- y_train_t = torch.tensor(y_t, dtype=torch.float32).to(device)
269
- X_test = torch.tensor(x_tes, dtype=torch.float32).to(device)
270
- y_test = torch.tensor(y_tes, dtype=torch.float32).to(device)
271
- final_preds = torch.tensor(final_preds_raw, dtype=torch.float32).to(device)
272
- # print value counts of y_test and y_train_test
273
- print(f"y_train_t value counts: {torch.unique(y_train_t, return_counts=True)}")
274
- print(f"y_test value counts: {torch.unique(y_test, return_counts=True)}")
275
- # 8. DataLoader Creation
276
- batch_size = 64
277
- train_dataset = TensorDataset(X_train_t, y_train_t)
278
- train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
279
-
280
- # 9. Model Initialization
281
- input_dim = X_scaled.shape[1] # Number of features
282
- hidden_dim = 20
283
- num_layers = 2
284
- output_dim = 256 # As per the LSTM class
285
- num_epochs = 800
286
-
287
- model = LSTM(input_dim=input_dim, hidden_dim=hidden_dim, output_dim=output_dim, num_layers=num_layers).to(device)
288
- criterion = nn.BCEWithLogitsLoss()
289
- optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0001) # weight_decay = L2
290
-
291
- # 10. Training
292
- print(f"Starting model training for {num_epochs} epochs for current iteration...")
293
- training_success = train_full(model, train_dataloader, X_test, y_test, criterion, optimizer, num_epochs=num_epochs)
294
- if training_success:
295
- print("Model training complete for current iteration (early stopped).")
296
- else:
297
- print("Model training complete for current iteration (full epochs).")
298
-
299
- # 11. Prediction
300
- model.eval()
301
- with torch.no_grad():
302
- final_prediction_logits = model(final_preds).flatten()
303
- final_prediction_prob = torch.sigmoid(final_prediction_logits)
304
- final_prediction_class = torch.round(final_prediction_prob)
305
-
306
- return final_prediction_prob.item(), int(final_prediction_class.item()), training_success
307
-
308
- def run_prediction_workflow(CryptoName="BTC", Limit=500, Timeframe=12, marketType="bull", ohlcv_timeframe="1d", max_retries_per_iteration=3):
309
- all_iteration_results = []
310
-
311
- # --- Iteration 1 ---
312
- print(f"--- Starting Iteration 1 ---")
313
- iteration_1_success_flag = False
314
- base_limit_1 = Limit
315
- base_timeframe_1 = Timeframe
316
-
317
- prob1 = 0.0
318
- class1 = 0
319
-
320
- for attempt in range(max_retries_per_iteration):
321
- rand_limit_offset = random.randrange(-100, 101, 2)
322
- rand_timeframe_offset = random.randrange(-2, 9, 2)
323
- current_limit_for_attempt = max(100, base_limit_1 + rand_limit_offset)
324
- current_timeframe_for_attempt = max(5, base_timeframe_1 + rand_timeframe_offset)
325
-
326
- print(f"Attempt {attempt + 1} for Iteration 1 with Limit={current_limit_for_attempt}, Timeframe={current_timeframe_for_attempt}...")
327
- current_prob, current_class_val, success = _train_and_predict(CryptoName, current_limit_for_attempt, current_timeframe_for_attempt, marketType, ohlcv_timeframe)
328
-
329
- if success:
330
- print(f"Iteration 1 successful on attempt {attempt + 1}.")
331
- prob1 = current_prob
332
- class1 = current_class_val
333
- iteration_1_success_flag = True
334
- break
335
- else:
336
- print(f"Iteration 1 failed on attempt {attempt + 1}. Adjusting parameters randomly and retrying...")
337
-
338
- if not iteration_1_success_flag:
339
- print(f"Warning: Iteration 1 could not achieve successful training after {max_retries_per_iteration} attempts. Using results from the last attempt (if any).")
340
- all_iteration_results.append({"probability": prob1, "class": class1, "successful": iteration_1_success_flag})
341
-
342
-
343
- # --- Iteration 2 ---
344
- print(f"\n--- Starting Iteration 2 ---")
345
- iteration_2_success_flag = False
346
- base_limit_2 = Limit
347
- base_timeframe_2 = Timeframe
348
-
349
- prob2 = 0.0
350
- class2 = 0
351
-
352
- for attempt in range(max_retries_per_iteration):
353
- rand_limit_offset = random.randrange(-100, 101, 2)
354
- rand_timeframe_offset = random.randrange(-2, 9, 2)
355
- current_limit_for_attempt = max(100, base_limit_2 + rand_limit_offset)
356
- current_timeframe_for_attempt = max(5, base_timeframe_2 + rand_timeframe_offset)
357
-
358
- print(f"Attempt {attempt + 1} for Iteration 2 with Limit={current_limit_for_attempt}, Timeframe={current_timeframe_for_attempt}...")
359
- current_prob, current_class_val, success = _train_and_predict(CryptoName, current_limit_for_attempt, current_timeframe_for_attempt, marketType, ohlcv_timeframe)
360
-
361
- if success:
362
- print(f"Iteration 2 successful on attempt {attempt + 1}.")
363
- prob2 = current_prob
364
- class2 = current_class_val
365
- iteration_2_success_flag = True
366
- break
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 predict_crypto_gradio(crypto_name, limit, market_type, ohlcv_timeframe):
452
- timeframe_lstm=12
453
  # Calculate validation_date
454
- now_utc = datetime.datetime.utcnow()
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": ohlcv_timeframe,
468
- "validation_date": validation_date,
469
- "market_type":market_type
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
- # Retrieve the threshold for the message from the global THRESHOLDS dictionary
482
- threshold = THRESHOLDS.get(crypto_name.upper(), {}).get(ohlcv_timeframe.lower(), 0.0)
483
-
484
- # Call the main prediction workflow
485
- results = run_prediction_workflow(
486
- CryptoName=crypto_name,
487
- Limit=limit,
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": ohlcv_timeframe,
522
- "validation_date": validation_date,
523
- "results": results,
524
- "message":message,
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
- # Gradio Interface setup
538
  iface = gr.Interface(
539
- fn=predict_crypto_gradio,
540
  inputs=[
541
- gr.Dropdown(["BTC", "ETH"], label="Cryptocurrency"),
542
- gr.Number(value=500, label="Data Limit (e.g., 500 days/hours)", info="Number of historical data points to fetch."),
543
- gr.Radio(["bull", "bearish"], label="Market Type", value="bull", info="Predict for bullish (increase) or bearish (decrease) market."),
544
- gr.Dropdown(["1d", "12h", "6h", "4h", "2h"], label="OHLCV Timeframe", value="1d", info="Granularity of historical data (e.g., 1 day, 4 hours).")
545
  ],
546
- outputs=gr.Textbox(label="Prediction Results"),
547
- title="Cryptocurrency Price Prediction",
548
- description="Predicts cryptocurrency price movement (increase/decrease) based on historical OHLCV, RSI, and MACD data using an LSTM model. It runs three iterations with slightly varied parameters and provides a combined prediction based on majority vote."
 
549
  )
550
 
551
- iface.launch(ssr_mode=False)
 
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)