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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.01, shuffle=True)
|
| 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 = 600
|
| 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.randint(-100, 100)
|
| 322 |
+
rand_timeframe_offset = random.randint(-5, 5)
|
| 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.randint(-100, 100)
|
| 354 |
+
rand_timeframe_offset = random.randint(-5, 5)
|
| 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.randint(-100, 100)
|
| 386 |
+
rand_timeframe_offset = random.randint(-5, 5)
|
| 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://foreignly-epilimnetic-armanda.ngrok-free.dev/api/training/"
|
| 450 |
+
|
| 451 |
+
def predict_crypto_gradio(crypto_name, limit, timeframe_lstm, market_type, ohlcv_timeframe):
|
| 452 |
+
# Calculate validation_date
|
| 453 |
+
now_utc = datetime.datetime.utcnow()
|
| 454 |
+
if 'd' in ohlcv_timeframe.lower():
|
| 455 |
+
validation_date = now_utc.strftime("%Y-%m-%d")
|
| 456 |
+
elif 'h' in ohlcv_timeframe.lower():
|
| 457 |
+
validation_date = now_utc.strftime("%Y-%m-%d-%H")
|
| 458 |
+
else:
|
| 459 |
+
validation_date = now_utc.strftime("%Y-%m-%d-%H-%M") # Fallback for minutes or other units
|
| 460 |
+
|
| 461 |
+
# 1. Send PENDING status
|
| 462 |
+
pending_url = f"{BASE_API_URL}insert-pending/"
|
| 463 |
+
pending_data = {
|
| 464 |
+
"secret": SECRET_CODE,
|
| 465 |
+
"crypto_name": crypto_name,
|
| 466 |
+
"timeframe": ohlcv_timeframe,
|
| 467 |
+
"validation_date": validation_date,
|
| 468 |
+
"market_type":market_type
|
| 469 |
+
}
|
| 470 |
+
print(f"Sending pending status for {crypto_name}...")
|
| 471 |
+
try:
|
| 472 |
+
print(f"Pending status data: {pending_data}")
|
| 473 |
+
pending_resp = requests.post(pending_url, json=pending_data)
|
| 474 |
+
pending_resp.raise_for_status()
|
| 475 |
+
print(f"Pending status sent: {pending_resp.json()}")
|
| 476 |
+
except requests.exceptions.RequestException as e:
|
| 477 |
+
print(f"Error sending pending status: {e}")
|
| 478 |
+
return f"Error sending pending status: {e}"
|
| 479 |
+
|
| 480 |
+
# Retrieve the threshold for the message from the global THRESHOLDS dictionary
|
| 481 |
+
threshold = THRESHOLDS.get(crypto_name.upper(), {}).get(ohlcv_timeframe.lower(), 0.0)
|
| 482 |
+
|
| 483 |
+
# Call the main prediction workflow
|
| 484 |
+
results = run_prediction_workflow(
|
| 485 |
+
CryptoName=crypto_name,
|
| 486 |
+
Limit=limit,
|
| 487 |
+
Timeframe=timeframe_lstm, # Renamed to avoid conflict with ohlcv_timeframe
|
| 488 |
+
marketType=market_type,
|
| 489 |
+
ohlcv_timeframe=ohlcv_timeframe,
|
| 490 |
+
max_retries_per_iteration=4
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
# Format the output string as requested
|
| 494 |
+
output_str = f"Prediction 1: {results['iteration_1_result']['probability']:.4f} (Binary: {results['iteration_1_result']['class']})\n"
|
| 495 |
+
output_str += f"Prediction 2: {results['iteration_2_result']['probability']:.4f} (Binary: {results['iteration_2_result']['class']})\n"
|
| 496 |
+
output_str += f"Prediction 3: {results['iteration_3_result']['probability']:.4f} (Binary: {results['iteration_3_result']['class']})\n"
|
| 497 |
+
output_str += f"Combined Probability: {results['final_combined_prediction']['probability']:.4f}\n"
|
| 498 |
+
output_str += f"Combined Binary: {results['final_combined_prediction']['class']}\n"
|
| 499 |
+
|
| 500 |
+
# Generate the message based on combined prediction and market type
|
| 501 |
+
combined_binary = results['final_combined_prediction']['class']
|
| 502 |
+
message = ""
|
| 503 |
+
if market_type.lower() == 'bull' and combined_binary == 1:
|
| 504 |
+
message = f"Message: You should consider buying, as the stock might increase by approximately {threshold:.2f} points.\n"
|
| 505 |
+
elif market_type.lower() == 'bearish' and combined_binary == 1:
|
| 506 |
+
message = f"Message: You should consider selling, as the stock might decrease by approximately {threshold:.2f} points.\n"
|
| 507 |
+
elif combined_binary == 0:
|
| 508 |
+
message = "Message: No significant change is predicted for the specified market type.\n"
|
| 509 |
+
else:
|
| 510 |
+
message = "Message: Prediction is uncertain or not applicable to the selected market type and binary outcome.\n"
|
| 511 |
+
|
| 512 |
+
output_str += message
|
| 513 |
+
|
| 514 |
+
# 2. Send TRAINED status
|
| 515 |
+
trained_url = f"{BASE_API_URL}insert-trained/"
|
| 516 |
+
trained_data = {
|
| 517 |
+
"pendingId": pending_resp.json().get("id"),
|
| 518 |
+
"secret": SECRET_CODE,
|
| 519 |
+
"crypto_name": crypto_name,
|
| 520 |
+
"timeframe": ohlcv_timeframe,
|
| 521 |
+
"validation_date": validation_date,
|
| 522 |
+
"results": results,
|
| 523 |
+
"message":message,
|
| 524 |
+
"market_type":market_type# Send the full results dictionary
|
| 525 |
+
}
|
| 526 |
+
try:
|
| 527 |
+
trained_resp = requests.post(trained_url, json=trained_data)
|
| 528 |
+
trained_resp.raise_for_status()
|
| 529 |
+
print(f"Trained status sent: {trained_resp.json()}")
|
| 530 |
+
except requests.exceptions.RequestException as e:
|
| 531 |
+
print(f"Error sending trained status: {e}")
|
| 532 |
+
output_str += f"\nError sending trained status to backend: {e}"
|
| 533 |
+
|
| 534 |
+
return output_str
|
| 535 |
+
|
| 536 |
+
# Gradio Interface setup
|
| 537 |
+
iface = gr.Interface(
|
| 538 |
+
fn=predict_crypto_gradio,
|
| 539 |
+
inputs=[
|
| 540 |
+
gr.Dropdown(["BTC", "ETH"], label="Cryptocurrency"),
|
| 541 |
+
gr.Number(value=500, label="Data Limit (e.g., 500 days/hours)", info="Number of historical data points to fetch."),
|
| 542 |
+
gr.Slider(minimum=5, maximum=20, step=1, value=12, label="Timeframe (LSTM Timesteps)", info="Number of timesteps for the LSTM model."),
|
| 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()
|