Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551import requestsimport datetimeimport pandas as pdfrom sklearn.preprocessing import MinMaxScalerimport numpy as npfrom sklearn.model_selection import train_test_splitimport torchimport torch.nn as nnfrom torch.utils.data import DataLoader,TensorDatasetimport randomimport re
THRESHOLDS = { "BTC": { "1d": 450.0, "12h": 400.0, "6h": 350.5, "4h": 300.0, "2h": 300.5,
}, "ETH": { "1d": 80.0, "12h": 68.0, "6h": 45, "4h": 28.0, "2h": 10.5, },
}
def get_crypto_ohlcv_data(fsym="BTC", tsym="USD", limit=365, timeframe="1d", toTs=None, api_key=None): fsym = fsym.upper() timeframe = timeframe.lower()
# 1. Parse timeframe for API aggregate match = re.match(r"(\d+)([a-z]+)", timeframe) if not match: raise ValueError("Timeframe format should be like '4h' or '1d'")
aggregate_value = int(match.group(1)) unit = match.group(2)
# 2. Retrieve Threshold from the editable dictionary # Defaults to 0.0 if the crypto or timeframe isn't found crypto_data = THRESHOLDS.get(fsym, {}) threshold = crypto_data.get(timeframe, 0.0)
# 3. API Request Setup if 'd' in unit: base_url = "https://min-api.cryptocompare.com/data/histoday" elif 'h' in unit: base_url = "https://min-api.cryptocompare.com/data/histohour" elif 'm' in unit: base_url = "https://min-api.cryptocompare.com/data/histominute" else: raise ValueError("Unit must be 'd', 'h', or 'm'")
params = { "fsym": fsym, "tsym": tsym, "limit": limit, "aggregate": aggregate_value } if api_key: params["api_key"] = api_key if toTs: params["toTs"] = int(toTs)
resp = requests.get(base_url, params=params) resp.raise_for_status()
# Accessing the nested Data list raw_data = resp.json() if "Data" in raw_data and isinstance(raw_data["Data"], dict) and "Data" in raw_data["Data"]: data = raw_data["Data"]["Data"] elif "Data" in raw_data and isinstance(raw_data["Data"], list): data = raw_data["Data"] else: data = []
# 4. Process DataFrame df = pd.DataFrame(data) if not df.empty: df["date"] = pd.to_datetime(df["time"], unit="s") df.set_index("date", inplace=True) df = df[["open", "high", "low", "close"]]
print("Thresold Point == ",threshold," aggregate_value ===",aggregate_value)
return df, threshold
# Calculate RSIdef calculate_rsi(data, window=14): diff = data.diff(1).dropna() gain = diff.mask(diff < 0, 0) loss = diff.mask(diff > 0, 0).abs() avg_gain = gain.ewm(com=window - 1, min_periods=window).mean() avg_loss = loss.ewm(com=window - 1, min_periods=window).mean() rs = avg_gain / avg_loss rsi = 100 - (100 / (1 + rs)) return rsi# Calculate MACDdef calculate_macd(data, short_window=12, long_window=26, signal_window=9): exp1 = data.ewm(span=short_window, adjust=False).mean() exp2 = data.ewm(span=long_window, adjust=False).mean() macd = exp1 - exp2 signal = macd.ewm(span=signal_window, adjust=False).mean() histogram = macd - signal return macd, signal, histogram
def create_dataset(data, timestep=12, X_scaler=None,marketType='bull', threshold_value=0.0): if X_scaler is None: raise ValueError("X_scaler must be provided to inverse_transform the data.")
close_index = 3 X, y = [], []
# 1. Training/Validation pairs for i in range(len(data) - timestep): x_a = data[i : i + timestep] x_b = data[i + timestep]
scaled_a = X_scaler.inverse_transform(x_a[-1].reshape(1, -1))[0][close_index] scaled_b = X_scaler.inverse_transform(x_b.reshape(1, -1))[0][close_index]
# If the next day's close price is significantly higher (e.g., > threshold_value USD), classify as 1 (increase) # Otherwise, classify as 0 (no significant increase) diff = scaled_b - scaled_a if marketType == 'bull': y.append(1) if diff > threshold_value else y.append(0) else: y.append(1) if diff < -threshold_value else y.append(0) X.append(x_a)
# 2. The "Future" window (The very last sequence in the data) # This will be [[4, 5, 6]] in your example prediction_window = np.array([data[-timestep:]])
return np.array(X), np.array(y), prediction_window
def calculate_accuracy(y_true, y_pred): """ Calculate classification accuracy.
Args: y_true (array-like): true labels (0 or 1). y_pred (array-like): predicted labels (0 or 1).
Returns: float: accuracy score (0.0 to 1.0). """ y_true = np.array(y_true) y_pred = np.array(y_pred) correct = np.sum(y_true == y_pred) accuracy = correct / len(y_true) return accuracydevice = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class LSTM(nn.Module): def __init__(self, input_dim, hidden_dim, num_layers, output_dim): super(LSTM, self).__init__() self.hidden_dim = hidden_dim self.num_layers = num_layers self.batchNorm = nn.BatchNorm1d self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True) self.fc = nn.Linear(hidden_dim, output_dim)
self.linear_net = nn.Sequential( nn.Linear(256,128), nn.BatchNorm1d(128), nn.ReLU(),
nn.Linear(128,64), nn.BatchNorm1d(64), nn.ReLU(), nn.Linear(64,32), nn.BatchNorm1d(32), nn.ReLU(),
nn.Linear(32,1),
) self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid()
def forward(self, x): out, _ = self.lstm(x) # Let PyTorch create h0, c0 automatically out = self.fc(out[:, -1, :]) out = self.linear_net(out) return out
def train_full(model, dataloader, X_test, y_test, criterion, optimizer, num_epochs=100): avg_loss_history = [] best_val_loss = 10000.0 # Initialize with a high value
for epoch in range(num_epochs): avg_loss = [] # Stores training loss for current epoch model.train() for x, y in dataloader: optimizer.zero_grad() outputs = model(x).to(device).flatten() loss = criterion(outputs, y) loss.backward() avg_loss.append(loss.item()) optimizer.step() avg_loss_history.append(np.average(avg_loss)) # Store average train loss for current epoch
model.eval() with torch.no_grad(): test_preds = model(X_test).to(device).flatten() test_loss = criterion(test_preds, y_test)
# Update best_val_loss observed so far if test_loss.item() < best_val_loss: best_val_loss = test_loss.item()
# Early stopping condition based on user feedback if test_loss.item() < 0.13 and np.average(avg_loss) <0.13: # Stop if test loss is below this threshold test_accuracy = calculate_accuracy(y_test.detach().cpu().numpy(), torch.round(torch.sigmoid(test_preds)).detach().cpu().numpy()) print(f"Early stopping at Epoch {epoch+1} due to Test Loss = {test_loss.item():.4f} (Accuracy = {test_accuracy:.2f})") return True # Indicate successful training iteration
# Original periodic logging if (epoch + 1) % 50 == 0 or epoch == 0: # Re-evaluate test_loss and accuracy for logging purposes, ensuring up-to-date values # (test_loss and best_val_loss would be current from above eval block) current_test_accuracy = calculate_accuracy(y_test.cpu().numpy(), torch.round(torch.sigmoid(test_preds)).cpu().numpy()) 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}")
print(f"Training completed {num_epochs} epochs without reaching early stopping threshold.") return False # Indicate unsuccessful training iteration
def _train_and_predict(CryptoName, Limit, Timeframe, marketType, ohlcv_timeframe): # 1. Data Retrieval print(f"Fetching data for {CryptoName} for {Limit} days with timeframe {ohlcv_timeframe}...") df, threshold_value = get_crypto_ohlcv_data(fsym=CryptoName, limit=Limit, timeframe=ohlcv_timeframe)
# 2. Feature Engineering (RSI and MACD) df['RSI'] = calculate_rsi(df['close']) df['MACD'], df['MACD_Signal'], df['MACD_Histogram'] = calculate_macd(df['close'])
# 3. Data Cleaning: Drop rows with any NaN values that resulted from indicator calculations df_cleaned = df.dropna() # remove last row of df df_cleaned = df_cleaned.iloc[:-1] data = df_cleaned.copy() print(f"Original DataFrame shape: {df.shape}, Cleaned DataFrame shape: {data.shape}") print(df_cleaned.tail()) # 4. Scaling X_scaler = MinMaxScaler() X_scaled = X_scaler.fit_transform(data)
# 5. Dataset Creation # Timeframe parameter from user will be used as timestep timestep = Timeframe x_train, y_train, final_preds_raw = create_dataset(X_scaled, timestep=timestep, X_scaler=X_scaler, marketType=marketType, threshold_value=threshold_value) 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)")
# 6. Train-Test Split x_t, x_tes, y_t, y_tes = train_test_split(x_train, y_train, test_size=0.01, shuffle=True)
# 7. Tensor Conversion and move to device X_train_t = torch.tensor(x_t, dtype=torch.float32).to(device) y_train_t = torch.tensor(y_t, dtype=torch.float32).to(device) X_test = torch.tensor(x_tes, dtype=torch.float32).to(device) y_test = torch.tensor(y_tes, dtype=torch.float32).to(device) final_preds = torch.tensor(final_preds_raw, dtype=torch.float32).to(device) # print value counts of y_test and y_train_test print(f"y_train_t value counts: {torch.unique(y_train_t, return_counts=True)}") print(f"y_test value counts: {torch.unique(y_test, return_counts=True)}") # 8. DataLoader Creation batch_size = 64 train_dataset = TensorDataset(X_train_t, y_train_t) train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # 9. Model Initialization input_dim = X_scaled.shape[1] # Number of features hidden_dim = 20 num_layers = 2 output_dim = 256 # As per the LSTM class num_epochs = 600
model = LSTM(input_dim=input_dim, hidden_dim=hidden_dim, output_dim=output_dim, num_layers=num_layers).to(device) criterion = nn.BCEWithLogitsLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.0001) # weight_decay = L2
# 10. Training print(f"Starting model training for {num_epochs} epochs for current iteration...") training_success = train_full(model, train_dataloader, X_test, y_test, criterion, optimizer, num_epochs=num_epochs) if training_success: print("Model training complete for current iteration (early stopped).") else: print("Model training complete for current iteration (full epochs).")
# 11. Prediction model.eval() with torch.no_grad(): final_prediction_logits = model(final_preds).flatten() final_prediction_prob = torch.sigmoid(final_prediction_logits) final_prediction_class = torch.round(final_prediction_prob)
return final_prediction_prob.item(), int(final_prediction_class.item()), training_success
def run_prediction_workflow(CryptoName="BTC", Limit=500, Timeframe=12, marketType="bull", ohlcv_timeframe="1d", max_retries_per_iteration=3): all_iteration_results = []
# --- Iteration 1 --- print(f"--- Starting Iteration 1 ---") iteration_1_success_flag = False base_limit_1 = Limit base_timeframe_1 = Timeframe
prob1 = 0.0 class1 = 0
for attempt in range(max_retries_per_iteration): rand_limit_offset = random.randint(-100, 100) rand_timeframe_offset = random.randint(-5, 5) current_limit_for_attempt = max(100, base_limit_1 + rand_limit_offset) current_timeframe_for_attempt = max(5, base_timeframe_1 + rand_timeframe_offset)
print(f"Attempt {attempt + 1} for Iteration 1 with Limit={current_limit_for_attempt}, Timeframe={current_timeframe_for_attempt}...") current_prob, current_class_val, success = _train_and_predict(CryptoName, current_limit_for_attempt, current_timeframe_for_attempt, marketType, ohlcv_timeframe)
if success: print(f"Iteration 1 successful on attempt {attempt + 1}.") prob1 = current_prob class1 = current_class_val iteration_1_success_flag = True break else: print(f"Iteration 1 failed on attempt {attempt + 1}. Adjusting parameters randomly and retrying...")
if not iteration_1_success_flag: print(f"Warning: Iteration 1 could not achieve successful training after {max_retries_per_iteration} attempts. Using results from the last attempt (if any).") all_iteration_results.append({"probability": prob1, "class": class1, "successful": iteration_1_success_flag})
# --- Iteration 2 --- print(f"\n--- Starting Iteration 2 ---") iteration_2_success_flag = False base_limit_2 = Limit base_timeframe_2 = Timeframe
prob2 = 0.0 class2 = 0
for attempt in range(max_retries_per_iteration): rand_limit_offset = random.randint(-100, 100) rand_timeframe_offset = random.randint(-5, 5) current_limit_for_attempt = max(100, base_limit_2 + rand_limit_offset) current_timeframe_for_attempt = max(5, base_timeframe_2 + rand_timeframe_offset)
print(f"Attempt {attempt + 1} for Iteration 2 with Limit={current_limit_for_attempt}, Timeframe={current_timeframe_for_attempt}...") current_prob, current_class_val, success = _train_and_predict(CryptoName, current_limit_for_attempt, current_timeframe_for_attempt, marketType, ohlcv_timeframe)
if success: print(f"Iteration 2 successful on attempt {attempt + 1}.") prob2 = current_prob class2 = current_class_val iteration_2_success_flag = True break else: print(f"Iteration 2 failed on attempt {attempt + 1}. Adjusting parameters randomly and retrying...")
if not iteration_2_success_flag: print(f"Warning: Iteration 2 could not achieve successful training after {max_retries_per_iteration} attempts. Using results from the last attempt (if any).") all_iteration_results.append({"probability": prob2, "class": class2, "successful": iteration_2_success_flag})
# --- Iteration 3 --- print(f"\n--- Starting Iteration 3 ---") iteration_3_success_flag = False base_limit_3 = Limit base_timeframe_3 = Timeframe
prob3 = 0.0 class3 = 0
for attempt in range(max_retries_per_iteration): rand_limit_offset = random.randint(-100, 100) rand_timeframe_offset = random.randint(-5, 5) current_limit_for_attempt = max(100, base_limit_3 + rand_limit_offset) current_timeframe_for_attempt = max(5, base_timeframe_3 + rand_timeframe_offset)
print(f"Attempt {attempt + 1} for Iteration 3 with Limit={current_limit_for_attempt}, Timeframe={current_timeframe_for_attempt}...") current_prob, current_class_val, success = _train_and_predict(CryptoName, current_limit_for_attempt, current_timeframe_for_attempt, marketType, ohlcv_timeframe)
if success: print(f"Iteration 3 successful on attempt {attempt + 1}.") prob3 = current_prob class3 = current_class_val iteration_3_success_flag = True break else: print(f"Iteration 3 failed on attempt {attempt + 1}. Adjusting parameters randomly and retrying...")
if not iteration_3_success_flag: print(f"Warning: Iteration 3 could not achieve successful training after {max_retries_per_iteration} attempts. Using results from the last attempt (if any).") all_iteration_results.append({"probability": prob3, "class": class3, "successful": iteration_3_success_flag})
# --- Combine Predictions (Majority Vote) --- print(f"\n--- Combining Final Prediction (Majority Vote) ---")
classes = [res['class'] for res in all_iteration_results] probabilities = [res['probability'] for res in all_iteration_results]
# Determine the majority class count_0 = classes.count(0) count_1 = classes.count(1)
if count_1 >= 2: # If 2 or more predictions are 1 final_combined_class = 1 else: # If 2 or more predictions are 0 final_combined_class = 0
# Calculate the average probability for the majority class majority_class_probs = [p for c, p in zip(classes, probabilities) if c == final_combined_class]
if majority_class_probs: final_combined_prob = sum(majority_class_probs) / len(majority_class_probs) else: # This case should ideally not happen with 3 iterations and a majority vote # But as a fallback, average all probabilities if no majority is clearly identified # (e.g., if only one successful iteration or all predictions are somehow ambiguous) final_combined_prob = sum(probabilities) / len(probabilities) if probabilities else 0.0
print(f"Combined Probability: {final_combined_prob:.4f}") print(f"Combined Class (0 for no significant change, 1 for significant change): {final_combined_class}")
return { "crypto_name": CryptoName, "iteration_1_result": all_iteration_results[0], "iteration_2_result": all_iteration_results[1], "iteration_3_result": all_iteration_results[2], "final_combined_prediction": {"probability": final_combined_prob, "class": final_combined_class} }
import gradio as grimport requestsimport datetime
SECRET_CODE = "ilovemypythonprogram"BASE_API_URL = "https://foreignly-epilimnetic-armanda.ngrok-free.dev/api/training/"
def predict_crypto_gradio(crypto_name, limit, timeframe_lstm, market_type, ohlcv_timeframe): # Calculate validation_date now_utc = datetime.datetime.utcnow() if 'd' in ohlcv_timeframe.lower(): validation_date = now_utc.strftime("%Y-%m-%d") elif 'h' in ohlcv_timeframe.lower(): validation_date = now_utc.strftime("%Y-%m-%d-%H") else: validation_date = now_utc.strftime("%Y-%m-%d-%H-%M") # Fallback for minutes or other units
# 1. Send PENDING status pending_url = f"{BASE_API_URL}insert-pending/" pending_data = { "secret": SECRET_CODE, "crypto_name": crypto_name, "timeframe": ohlcv_timeframe, "validation_date": validation_date, "market_type":market_type } print(f"Sending pending status for {crypto_name}...") try: print(f"Pending status data: {pending_data}") pending_resp = requests.post(pending_url, json=pending_data) pending_resp.raise_for_status() print(f"Pending status sent: {pending_resp.json()}") except requests.exceptions.RequestException as e: print(f"Error sending pending status: {e}") return f"Error sending pending status: {e}"
# Retrieve the threshold for the message from the global THRESHOLDS dictionary threshold = THRESHOLDS.get(crypto_name.upper(), {}).get(ohlcv_timeframe.lower(), 0.0)
# Call the main prediction workflow results = run_prediction_workflow( CryptoName=crypto_name, Limit=limit, Timeframe=timeframe_lstm, # Renamed to avoid conflict with ohlcv_timeframe marketType=market_type, ohlcv_timeframe=ohlcv_timeframe, max_retries_per_iteration=4 )
# Format the output string as requested output_str = f"Prediction 1: {results['iteration_1_result']['probability']:.4f} (Binary: {results['iteration_1_result']['class']})\n" output_str += f"Prediction 2: {results['iteration_2_result']['probability']:.4f} (Binary: {results['iteration_2_result']['class']})\n" output_str += f"Prediction 3: {results['iteration_3_result']['probability']:.4f} (Binary: {results['iteration_3_result']['class']})\n" output_str += f"Combined Probability: {results['final_combined_prediction']['probability']:.4f}\n" output_str += f"Combined Binary: {results['final_combined_prediction']['class']}\n"
# Generate the message based on combined prediction and market type combined_binary = results['final_combined_prediction']['class'] message = "" if market_type.lower() == 'bull' and combined_binary == 1: message = f"Message: You should consider buying, as the stock might increase by approximately {threshold:.2f} points.\n" elif market_type.lower() == 'bearish' and combined_binary == 1: message = f"Message: You should consider selling, as the stock might decrease by approximately {threshold:.2f} points.\n" elif combined_binary == 0: message = "Message: No significant change is predicted for the specified market type.\n" else: message = "Message: Prediction is uncertain or not applicable to the selected market type and binary outcome.\n"
output_str += message
# 2. Send TRAINED status trained_url = f"{BASE_API_URL}insert-trained/" trained_data = { "pendingId": pending_resp.json().get("id"), "secret": SECRET_CODE, "crypto_name": crypto_name, "timeframe": ohlcv_timeframe, "validation_date": validation_date, "results": results, "message":message, "market_type":market_type# Send the full results dictionary } try: trained_resp = requests.post(trained_url, json=trained_data) trained_resp.raise_for_status() print(f"Trained status sent: {trained_resp.json()}") except requests.exceptions.RequestException as e: print(f"Error sending trained status: {e}") output_str += f"\nError sending trained status to backend: {e}"
return output_str
# Gradio Interface setupiface = gr.Interface( fn=predict_crypto_gradio, inputs=[ gr.Dropdown(["BTC", "ETH"], label="Cryptocurrency"), gr.Number(value=500, label="Data Limit (e.g., 500 days/hours)", info="Number of historical data points to fetch."), gr.Slider(minimum=5, maximum=20, step=1, value=12, label="Timeframe (LSTM Timesteps)", info="Number of timesteps for the LSTM model."), gr.Radio(["bull", "bearish"], label="Market Type", value="bull", info="Predict for bullish (increase) or bearish (decrease) market."), gr.Dropdown(["1d", "12h", "6h", "4h", "2h"], label="OHLCV Timeframe", value="1d", info="Granularity of historical data (e.g., 1 day, 4 hours).") ], outputs=gr.Textbox(label="Prediction Results"), title="Cryptocurrency Price Prediction", 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.")
iface.launch()app.pyAdded+551