Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724733 unmodified lines4774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275282 unmodified lines531532533534535536537538539540541542543544545546547548549550551import 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 reTHRESHOLDS = {"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 aggregatematch = 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 foundcrypto_data = THRESHOLDS.get(fsym, {})threshold = crypto_data.get(timeframe, 0.0)# 3. API Request Setupif '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_keyif toTs: params["toTs"] = int(toTs)resp = requests.get(base_url, params=params)resp.raise_for_status()# Accessing the nested Data listraw_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 DataFramedf = 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_lossrsi = 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 - exp2signal = macd.ewm(span=signal_window, adjust=False).mean()histogram = macd - signalreturn macd, signal, histogramdef 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 = 3X, y = [], []# 1. Training/Validation pairsfor 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_aif 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 exampleprediction_window = np.array([data[-timestep:]])return np.array(X), np.array(y), prediction_windowdef 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_dimself.num_layers = num_layersself.batchNorm = nn.BatchNorm1dself.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 automaticallyout = self.fc(out[:, -1, :])out = self.linear_net(out)return outdef 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 valuefor epoch in range(num_epochs):avg_loss = [] # Stores training loss for current epochmodel.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 epochmodel.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 farif test_loss.item() < best_val_loss:best_val_loss = test_loss.item()# Early stopping condition based on user feedbackif test_loss.item() < 0.13 and np.average(avg_loss) <0.13: # Stop if test loss is below this thresholdtest_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 loggingif (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 iterationdef _train_and_predict(CryptoName, Limit, Timeframe, marketType, ohlcv_timeframe):# 1. Data Retrievalprint(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 calculationsdf_cleaned = df.dropna()# remove last row of dfdf_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. ScalingX_scaler = MinMaxScaler()X_scaled = X_scaler.fit_transform(data)# 5. Dataset Creation# Timeframe parameter from user will be used as timesteptimestep = Timeframex_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 Splitx_t, x_tes, y_t, y_tes = train_test_split(x_train, y_train, test_size=0.015, shuffle=False)# 7. Tensor Conversion and move to deviceX_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_testprint(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 Creationbatch_size = 64train_dataset = TensorDataset(X_train_t, y_train_t)train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)# 9. Model Initializationinput_dim = X_scaled.shape[1] # Number of featureshidden_dim = 20num_layers = 2output_dim = 256 # As per the LSTM classnum_epochs = 800model = 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. Trainingprint(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. Predictionmodel.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_successdef 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 = Falsebase_limit_1 = Limitbase_timeframe_1 = Timeframeprob1 = 0.0class1 = 0for attempt in range(max_retries_per_iteration):rand_limit_offset = random.randrange(-100, 101, 2)rand_timeframe_offset = random.randrange(-2, 9, 2)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_probclass1 = current_class_valiteration_1_success_flag = Truebreakelse: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 = Falsebase_limit_2 = Limitbase_timeframe_2 = Timeframeprob2 = 0.0class2 = 0for attempt in range(max_retries_per_iteration):rand_limit_offset = random.randrange(-100, 101, 2)rand_timeframe_offset = random.randrange(-2, 9, 2)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_probclass2 = current_class_valiteration_2_success_flag = Truebreakelse: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 = Falsebase_limit_3 = Limitbase_timeframe_3 = Timeframeprob3 = 0.0class3 = 0for attempt in range(max_retries_per_iteration):rand_limit_offset = random.randrange(-100, 101, 2)rand_timeframe_offset = random.randrange(-2, 9, 2)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_probclass3 = current_class_valiteration_3_success_flag = Truebreakelse: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 classcount_0 = classes.count(0)count_1 = classes.count(1)if count_1 >= 2: # If 2 or more predictions are 1final_combined_class = 1else: # If 2 or more predictions are 0final_combined_class = 0# Calculate the average probability for the majority classmajority_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.0print(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 datetimeSECRET_CODE = "ilovemypythonprogram"BASE_API_URL = "https://my-model-api.shares.zrok.io/api/training/"def predict_crypto_gradio(crypto_name, limit, market_type, ohlcv_timeframe):timeframe_lstm=12# Calculate validation_datenow_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 statuspending_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}")3 unmodified linesexcept 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 dictionarythreshold = THRESHOLDS.get(crypto_name.upper(), {}).get(ohlcv_timeframe.lower(), 0.0)# Call the main prediction workflowresults = run_prediction_workflow(CryptoName=crypto_name,Limit=limit,Timeframe=timeframe_lstm, # Renamed to avoid conflict with ohlcv_timeframemarketType=market_type,ohlcv_timeframe=ohlcv_timeframe,max_retries_per_iteration=5)# Format the output string as requestedoutput_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 typecombined_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 statustrained_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)2 unmodified linesexcept 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.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(ssr_mode=False)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353 unmodified lines3393403413423433443453463473483493503513523533543553563573583593603612 unmodified lines364365366367368369370371372373374375376377378379380381382383384385386387388389390# import all the necessary requirementsimport torchimport torch.nn as nnimport matplotlib.pyplot as pltimport requestsimport datetimeimport numpy as npimport pandas as pdfrom sklearn.preprocessing import StandardScalerimport gradio as grfrom datetime import datetime, timezone, timedeltaimport requestsimport pandas as pdimport re # Added missing importtimesteps = 16future_forcecast_steps = 10input_dim = 1hidden_dim = 24num_layers = 2output_dim = 1num_epochs = 1800def get_crypto_ohlcv(crypto_name="BTC", tsym="USD", timeframe="1d", limit=100, api_key=None):"""Fetches OHLCV data from CryptoCompare with support for various timeframes.Args:crypto_name (str): Symbol (e.g., "BTC", "ETH").tsym (str): Target currency (e.g., "USD", "USDT").timeframe (str): Support for "1h", "4h", "6h", "12h", "1d", "3d".limit (int): Number of data points (max 2000 per request).api_key (str): Your CryptoCompare API Key."""# 1. Map timeframes to endpoints and aggregation levels# format: { timeframe_string: (endpoint_suffix, aggregate_value) }tf_map = {"1h": ("hour", 1),"4h": ("hour", 4),"6h": ("hour", 6),"12h": ("hour", 12),"1d": ("day", 1),"2d": ("day", 2),"3d": ("day", 3),}if timeframe not in tf_map:raise ValueError(f"Unsupported timeframe: {timeframe}. Use {list(tf_map.keys())}")endpoint_type, agg = tf_map[timeframe]base_url = f"https://min-api.cryptocompare.com/data/v2/histo{endpoint_type}"# 2. Setup Parametersparams = {"fsym": crypto_name.upper(),"tsym": tsym.upper(),"limit": limit,"aggregate": agg}if api_key:params["api_key"] = api_key# 3. Request Dataresp = requests.get(base_url, params=params)resp.raise_for_status()json_data = resp.json()if json_data.get("Response") == "Error":raise RuntimeError(f"CryptoCompare Error: {json_data.get('Message')}")# 4. Process Data# v2 API stores data inside ['Data']['Data']data_list = json_data["Data"]["Data"]df = pd.DataFrame(data_list)# Convert timestamp and clean updf["date"] = pd.to_datetime(df["time"], unit="s")df.set_index("date", inplace=True)# Standardize columnsdf = df[["open", "high", "low", "close", "volumefrom", "volumeto"]]df.columns = ["open", "high", "low", "close", "volume_base", "volume_quote"]return df# --- Examples ---# df_4h = get_crypto_ohlcv(crypto_name="ETH", timeframe="4h", limit=100)# df_1d = get_crypto_ohlcv(crypto_name="SOL", timeframe="1d", limit=365)def prepare_production_data(data_array, steps):X, y = [], []# We loop so that the last 'y' is the very last available data point# Example: if len is 100 and steps is 10, the last i is 99.# X takes [89:99], y takes [99]for i in range(steps, len(data_array)):X.append(data_array[i-steps:i, 0])y.append(data_array[i, 0])X, y = np.array(X), np.array(y)# --- 5. The "Tomorrow" Input ---# This is the last 'steps' of the dataset (e.g., 91-100)# This has no 'y' because 'y' is the future we want to predict.x_latest_window = data_array[-steps:].reshape(1, steps)return X, y, x_latest_windowclass LSTM(nn.Module):def __init__(self, input_dim, hidden_dim, num_layers, output_dim):super(LSTM, self).__init__()self.hidden_dim = hidden_dimself.num_layers = num_layersself.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(hidden_dim, 1),)def forward(self, x):batch_size = x.shape[0]# Initialize h0 and c0 on the same device as xh0 = torch.zeros(self.num_layers, batch_size, self.hidden_dim).to(x.device)c0 = torch.zeros(self.num_layers, batch_size, self.hidden_dim).to(x.device)out, (hn, cn) = self.lstm(x, (h0, c0)) # No need to detach if they don't require gradients and are not part of graphout = self.linear_net(out[:, -1, :])return outdef get_expiry_date(timeframe):# 1. Get current time in UTCnow = datetime.now(timezone.utc)# 2. Parse the timeframe (e.g., "2h" -> 2 and "h")# This regex finds the digits and the letters separatelymatch = re.match(r"(\d+)([hd])", timeframe.lower())if not match:raise ValueError("Invalid timeframe format. Use '[int]h' or '[int]d'.")value = int(match.group(1))unit = match.group(2)# 3. Calculate expiry (2 * the timeframe value)multiplier = 2expiry_value = value * multiplierif unit == 'd':expiry_date = now + timedelta(days=expiry_value)else: # unit == 'h'expiry_date = now + timedelta(hours=expiry_value)return expiry_date# Some training zonesdef training_zone(model, criterion, optimiser, X_train_t, Y_train_t, num_epochs):best_train_loss = float('inf')model_save_path = "best_model.pth"print(f"Starting Production Training...")# Enable anomaly detection for debuggingimport torch.autogradtorch.autograd.set_detect_anomaly(True)for epoch in range(num_epochs):model.train()optimiser.zero_grad()# Forward passy_pred = model(X_train_t)loss = criterion(y_pred, Y_train_t)# Backward passloss.backward()optimiser.step()current_loss = loss.item()# --- 2. Save Model on Improvement ---# Only save the best model if it's past epoch 1000if current_loss < best_train_loss:best_train_loss = current_lossif epoch > 1000:# Save the model statetorch.save(model.state_dict(), model_save_path)if epoch % 100 == 0:print(f"Epoch {epoch:04d} | New Best Loss: {current_loss:.6f} | Model Saved")# Disable anomaly detection after training (optional, but good practice)torch.autograd.set_detect_anomaly(False)print("-" * 30)print(f"Training Complete. Best Loss: {best_train_loss:.6f}")# predicting zonedef predict_zone(model, model_save_path, x_future_input, future_forecast_steps, scaler, timesteps):# --- 1. Load and Set to Eval Mode ---model.load_state_dict(torch.load(model_save_path))model.eval()forecasted_results = []# Ensure we start with the very last available window from the real datacurrent_window = torch.from_numpy(x_future_input).float().to("cpu")# Ensure it is reshaped to (1, timesteps, 1)current_window = current_window.view(1, timesteps, 1)print(current_window.shape)# --- 2. Recursive Prediction Loop ---with torch.no_grad():for i in range(future_forecast_steps):# Predict the next point (Day i+1)prediction = model(current_window)# Store predictionforecasted_results.append(prediction.item())# SLIDE THE WINDOW:# 1. Remove the oldest price: current_window[:, 1:, :]# 2. Append the new prediction: prediction.unsqueeze(1)new_entry = prediction.unsqueeze(1)current_window = torch.cat((current_window[:, 1:, :], new_entry), dim=1)# --- 3. Unscale Results ---forecasted_results_np = np.array(forecasted_results).reshape(-1, 1)final_prices = scaler.inverse_transform(forecasted_results_np).flatten()# --- 4. Visualization ---plt.figure(figsize=(10, 5))# Plotting the 10-day trenddays = range(1, future_forecast_steps + 1)plt.plot(days, final_prices, marker='o', linestyle='-', color='#2ca02c', label='Forecasted Trend')# Annotate the values on the graph for clarityfor i, price in enumerate(final_prices):plt.annotate(f'{price:.2f}', (days[i], final_prices[i]),textcoords="offset points", xytext=(0,10), ha='center', fontsize=8)plt.title(f"Next {future_forecast_steps} Days: Predicted Price Pattern")plt.xlabel("Days Ahead")plt.ylabel("Price")plt.xticks(days) # Ensure every day is marked on the X-axisplt.grid(True, alpha=0.3, linestyle='--')plt.legend()plt.tight_layout()plt.show()# Removed redundant datetime import# --- 5. Clean Console Output ---print(f"\n--- {future_forecast_steps}-Day Future Forecast ---")for day, price in enumerate(final_prices, 1):print(f"Day {day}: {price:.2f}")return final_prices# Training Loopdef train_full(limit,tsym,crypto_name,timeframe):df = get_crypto_ohlcv(crypto_name=crypto_name, tsym=tsym, timeframe=timeframe, limit=limit)print(df.tail())df = df.iloc[:-1]data = df.copy()data_series = data['close'].values.reshape(-1, 1)# --- 2. Initialize Model, Criterion, Optimiser within the function ---model = LSTM(input_dim=input_dim, hidden_dim=hidden_dim, output_dim=output_dim, num_layers=num_layers)criterion = torch.nn.MSELoss(reduction='mean')optimiser = torch.optim.Adam(model.parameters(), lr=0.01)# --- 3. Scaling (Full Dataset) ---# Since we are in "Production/Final Train" mode, we fit on everythingscaler = StandardScaler()scaled_data = scaler.fit_transform(data_series)# creating the datax_train, y_train, x_future_input = prepare_production_data(scaled_data, timesteps)print(f"Total data points: {len(data_series)}")print(f"x_train shape: {x_train.shape}") # Should be (90, 10) if data is 100print(f"y_train shape: {y_train.shape}") # Should be (90,)# Verify the last training target is indeed the last value in our datalast_actual_val = data_series[-1][0]last_y_unscaled = scaler.inverse_transform(y_train[-1].reshape(-1, 1))[0][0]print(f"Last available price in data: {last_actual_val}")print(f"Last target (y) in training: {last_y_unscaled}")# Verify the input for "Tomorrow"future_window_unscaled = scaler.inverse_transform(x_future_input).flatten()print(f"Window to predict tomorrow: {future_window_unscaled}")# converting to the torchX_train_t = torch.Tensor(x_train).unsqueeze(-1)Y_train_t = torch.Tensor(y_train).unsqueeze(-1)# training zonetraining_zone(model, criterion, optimiser, X_train_t,Y_train_t, num_epochs)# prediction zonepredicted_array = predict_zone(model, "best_model.pth",x_future_input,future_forcecast_steps,scaler, timesteps)return predicted_arraySECRET_CODE = "ilovemypythonprogram"BASE_API_URL = "https://my-model-api.shares.zrok.io/api/training/"def run_prediction_for_gradio(limit, tsym, crypto_name, timeframe):# Calculate validation_datenow = datetime.now(timezone.utc)# 2. Add 2 hours using timedeltafuture_date = now + timedelta(hours=2)# 1. Send PENDING statuspending_url = f"{BASE_API_URL}insert-pending/"pending_data = {"secret": SECRET_CODE,"crypto_name": crypto_name,"timeframe": timeframe,"expiry_date": future_date.isoformat() # Convert datetime to ISO 8601 string}print(f"Sending pending status for {crypto_name}...")try:print(f"Pending status data: {pending_data}")3 unmodified linesexcept requests.exceptions.RequestException as e:print(f"Error sending pending status: {e}")return f"Error sending pending status: {e}"# Call the train_full function to get predictionspredicted_values = train_full(limit, tsym, crypto_name, timeframe)# Initialize output_str before potential use in except blockoutput_str = ""# finally inserting the actual data over the networkexpiry_date = get_expiry_date(timeframe)# 1. Send TRAINED statustrained_url = f"{BASE_API_URL}insert-trained/"trained_data = {"pendingId": pending_resp.json().get("id"),"secret": SECRET_CODE,"crypto_name": crypto_name,"timeframe": timeframe,"results": predicted_values.tolist(), # Convert numpy array to list for JSON serialization"expiry_date": expiry_date.isoformat() # Convert datetime to ISO 8601 string}try:trained_resp = requests.post(trained_url, json=trained_data)2 unmodified linesexcept requests.exceptions.RequestException as e:print(f"Error sending trained status: {e}")output_str += f"\nError sending trained status to backend: {e}"# Format the predicted values for display in Gradiooutput_string = f"--- Next {future_forcecast_steps}-Day Future Forecast ---\n"for day, price in enumerate(predicted_values, 1):output_string += f"Day {day}: {price:.2f}\n"return output_string# Create the Gradio interfaceiface = gr.Interface(fn=run_prediction_for_gradio,inputs=[gr.Slider(minimum=100, maximum=2000, value=800, step=100, label="Limit (Number of data points)"),gr.Dropdown(choices=["USD", "EUR", "GBP"], value="USD", label="Target Symbol (tsym)"),gr.Dropdown(choices=["BTC", "ETH", "SOL"], value="ETH", label="Crypto Name"),gr.Dropdown(choices=["1d", "3d", "1h", "4h", "6h", "12h"], value="1d", label="Timeframe")],outputs=gr.Textbox(label="Prediction Output", lines=8),title="Cryptocurrency Price Predictor",description="Enter parameters to get a 10-day price forecast for the selected cryptocurrency.",allow_flagging="never")iface.launch(server_name="0.0.0.0", debug=True)
app.py+311-472