Spaces:
Running
Running
File size: 13,653 Bytes
26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 9895d31 26c5c67 03234fd 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 03234fd 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 2f837e9 67f3e77 4951df2 67f3e77 26c5c67 67f3e77 26c5c67 db79667 badf071 db79667 390fb40 db79667 b212c42 6b985ed db79667 4795736 db79667 67f3e77 4d38bb5 26c5c67 fb9b2e0 db79667 26c5c67 67f3e77 4d38bb5 67f3e77 26c5c67 67f3e77 26c5c67 390fb40 26c5c67 67f3e77 26c5c67 67f3e77 26c5c67 67f3e77 4951df2 26c5c67 67f3e77 26c5c67 f8bb5d5 67f3e77 f8bb5d5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 | # import all the necessary requirements
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import requests
import datetime
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
import gradio as gr
from datetime import datetime, timezone, timedelta
import requests
import pandas as pd
import re # Added missing import
timesteps = 16
future_forcecast_steps = 10
input_dim = 1
hidden_dim = 24
num_layers = 2
output_dim = 1
num_epochs = 1700
def get_crypto_ohlcv(crypto_name="BTC", tsym="USD", timeframe="1d", limit=100, api_key="a2b2efc08d5160dc1bc03be8e03280dcb51daab10832c6ee698c95d065359589"):
"""
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 Parameters
params = {
"fsym": crypto_name.upper(),
"tsym": tsym.upper(),
"limit": limit,
"aggregate": agg
}
if api_key:
params["api_key"] = api_key
# 3. Request Data
resp = 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 up
df["date"] = pd.to_datetime(df["time"], unit="s")
df.set_index("date", inplace=True)
# Standardize columns
df = 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_window
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.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 x
h0 = 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 graph
out = self.linear_net(out[:, -1, :])
return out
def get_expiry_date(timeframe):
# 1. Get current time in UTC
now = datetime.now(timezone.utc)
# 2. Parse the timeframe (e.g., "2h" -> 2 and "h")
# This regex finds the digits and the letters separately
match = 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 = 2
expiry_value = value * multiplier
if unit == 'd':
expiry_date = now + timedelta(days=expiry_value)
else: # unit == 'h'
expiry_date = now + timedelta(hours=expiry_value)
return expiry_date
# Some training zones
def 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 debugging
import torch.autograd
torch.autograd.set_detect_anomaly(True)
for epoch in range(num_epochs):
model.train()
optimiser.zero_grad()
# Forward pass
y_pred = model(X_train_t)
loss = criterion(y_pred, Y_train_t)
# Backward pass
loss.backward()
optimiser.step()
current_loss = loss.item()
# --- 2. Save Model on Improvement ---
# Only save the best model if it's past epoch 1000
if current_loss < best_train_loss:
best_train_loss = current_loss
if epoch > 1000:
# Save the model state
torch.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 zone
def 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 data
current_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 prediction
forecasted_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 trend
days = 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 clarity
for 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-axis
plt.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 Loop
def 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 everything
scaler = StandardScaler()
scaled_data = scaler.fit_transform(data_series)
# creating the data
x_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 100
print(f"y_train shape: {y_train.shape}") # Should be (90,)
# Verify the last training target is indeed the last value in our data
last_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 torch
X_train_t = torch.Tensor(x_train).unsqueeze(-1)
Y_train_t = torch.Tensor(y_train).unsqueeze(-1)
# training zone
training_zone(model, criterion, optimiser, X_train_t,Y_train_t, num_epochs)
# prediction zone
predicted_array = predict_zone(model, "best_model.pth",x_future_input,future_forcecast_steps,scaler, timesteps)
return predicted_array
SECRET_CODE = "ilovemypythonprogram"
BASE_API_URL = "https://cryptmorrow.pythonanywhere.com/api/training/"
def run_prediction_for_gradio(tsym, crypto_name, timeframe):
limit = 800
# Calculate validation_date
now = datetime.now(timezone.utc)
# 2. Add 2 hours using timedelta
future_date = now + timedelta(hours=2)
data_to_send = {
"secret":SECRET_CODE,
"timeframe": timeframe,
"crypto_name": crypto_name,
"tysm": tsym,
}
# 2. Define the target URL
url = f"{BASE_API_URL}response-for-huggingface/"
result = ""
try:
# 3. Perform the POST request
# Using 'json=' automatically sets Content-Type to application/json
response = requests.post(url, json=data_to_send)
# 4. Handle the response
response.raise_for_status() # Check for HTTP errors (4xx or 5xx)
# Process the data (assuming the server returns JSON)
result = response.json()
print("Success! Response data:", result)
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
except Exception as err:
print(f"An error occurred: {err}")
# 1. Send PENDING status
predictionID = result.get("id")
# Call the train_full function to get predictions
predicted_values = train_full(limit,tsym, crypto_name, timeframe)
# Initialize output_str before potential use in except block
output_str = ""
# finally inserting the actual data over the network
expiry_date = get_expiry_date(timeframe)
# 1. Send TRAINED status
trained_url = f"{BASE_API_URL}insert-trained/"
trained_data = {
"pendingId": predictionID,
"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)
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}"
# Format the predicted values for display in Gradio
return True
# Create the Gradio interface
iface = gr.Interface(
fn=run_prediction_for_gradio,
inputs=[
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.",
flagging_mode="never"
)
iface.launch(
server_name="0.0.0.0",
server_port=7860,
debug=True
) |