Spaces:
Sleeping
Sleeping
amitke
commited on
Commit
·
09fbd2c
1
Parent(s):
f3bda49
test
Browse files- inference.py +18 -3
- testing.py +71 -4
- train.py +58 -7
inference.py
CHANGED
|
@@ -46,8 +46,14 @@ def predict_next(symbol: str, n_days: int = 1):
|
|
| 46 |
model, scaler, meta = _load_artifacts(symbol)
|
| 47 |
seq_len = meta["seq_len"]
|
| 48 |
|
| 49 |
-
closes = _last_close_series(symbol, days=max(400, seq_len*5))
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
# seed window
|
| 53 |
window = scaled[-seq_len:].reshape(1, seq_len, 1).astype(np.float32)
|
|
@@ -63,5 +69,14 @@ def predict_next(symbol: str, n_days: int = 1):
|
|
| 63 |
window_t = torch.from_numpy(window.astype(np.float32))
|
| 64 |
|
| 65 |
preds_scaled = np.array(preds_scaled, dtype=np.float32).reshape(-1, 1)
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
return {"symbol": symbol.upper(), "days": n_days, "predictions": preds_unscaled, "seq_len": seq_len, "meta": meta}
|
|
|
|
| 46 |
model, scaler, meta = _load_artifacts(symbol)
|
| 47 |
seq_len = meta["seq_len"]
|
| 48 |
|
| 49 |
+
closes = _last_close_series(symbol, days=max(400, seq_len*5 + 20))
|
| 50 |
+
|
| 51 |
+
# Compute log returns on the fly
|
| 52 |
+
# closes is [N, 1]
|
| 53 |
+
prices = closes.flatten()
|
| 54 |
+
returns = np.log(prices[1:] / prices[:-1]).reshape(-1, 1)
|
| 55 |
+
|
| 56 |
+
scaled = scaler.transform(returns)
|
| 57 |
|
| 58 |
# seed window
|
| 59 |
window = scaled[-seq_len:].reshape(1, seq_len, 1).astype(np.float32)
|
|
|
|
| 69 |
window_t = torch.from_numpy(window.astype(np.float32))
|
| 70 |
|
| 71 |
preds_scaled = np.array(preds_scaled, dtype=np.float32).reshape(-1, 1)
|
| 72 |
+
preds_returns = scaler.inverse_transform(preds_scaled).flatten()
|
| 73 |
+
|
| 74 |
+
# Reconstruct prices from the last known close
|
| 75 |
+
last_close = prices[-1]
|
| 76 |
+
curr = last_close
|
| 77 |
+
preds_unscaled = []
|
| 78 |
+
for r in preds_returns:
|
| 79 |
+
curr = curr * np.exp(r)
|
| 80 |
+
preds_unscaled.append(curr)
|
| 81 |
+
|
| 82 |
return {"symbol": symbol.upper(), "days": n_days, "predictions": preds_unscaled, "seq_len": seq_len, "meta": meta}
|
testing.py
CHANGED
|
@@ -26,9 +26,15 @@ def evaluate(symbol: str):
|
|
| 26 |
end = datetime.utcnow().date()
|
| 27 |
start = end - timedelta(days=5*365)
|
| 28 |
df = yf.download(symbol, start=start.isoformat(), end=end.isoformat(), progress=False, auto_adjust=True)
|
| 29 |
-
data = df[["Close"]].dropna()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
scaled = scaler.transform(
|
| 32 |
split_idx = int(len(scaled) * 0.8)
|
| 33 |
test_scaled = scaled[split_idx - seq_len:] # include tail of train for continuity
|
| 34 |
|
|
@@ -42,8 +48,69 @@ def evaluate(symbol: str):
|
|
| 42 |
|
| 43 |
X_t = torch.from_numpy(X) # [N, T, 1]
|
| 44 |
pred_scaled = model(X_t).numpy()
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
rmse = math.sqrt(mean_squared_error(y_true, pred))
|
| 49 |
mae = mean_absolute_error(y_true, pred)
|
|
|
|
| 26 |
end = datetime.utcnow().date()
|
| 27 |
start = end - timedelta(days=5*365)
|
| 28 |
df = yf.download(symbol, start=start.isoformat(), end=end.isoformat(), progress=False, auto_adjust=True)
|
| 29 |
+
data = df[["Close"]].dropna()
|
| 30 |
+
|
| 31 |
+
# Compute returns
|
| 32 |
+
data['LogReturn'] = np.log(data['Close'] / data['Close'].shift(1))
|
| 33 |
+
data = data.dropna()
|
| 34 |
+
|
| 35 |
+
returns = data['LogReturn'].values.reshape(-1, 1)
|
| 36 |
|
| 37 |
+
scaled = scaler.transform(returns)
|
| 38 |
split_idx = int(len(scaled) * 0.8)
|
| 39 |
test_scaled = scaled[split_idx - seq_len:] # include tail of train for continuity
|
| 40 |
|
|
|
|
| 48 |
|
| 49 |
X_t = torch.from_numpy(X) # [N, T, 1]
|
| 50 |
pred_scaled = model(X_t).numpy()
|
| 51 |
+
|
| 52 |
+
# inverse returns
|
| 53 |
+
pred_returns = scaler.inverse_transform(pred_scaled).flatten()
|
| 54 |
+
|
| 55 |
+
# Reconstruct prices
|
| 56 |
+
# We need the price before the first test prediction
|
| 57 |
+
# The test set in 'data' starts at split_idx
|
| 58 |
+
# The first prediction corresponds to return at split_idx
|
| 59 |
+
# So base is price at split_idx - 1
|
| 60 |
+
|
| 61 |
+
# Note: 'data' here is the return-df (shifted).
|
| 62 |
+
# We need indices from the original df.
|
| 63 |
+
# It's cleaner to just align by length.
|
| 64 |
+
|
| 65 |
+
# Get original prices aligned with returns
|
| 66 |
+
# df['Close'] has N+1 items if returns has N items.
|
| 67 |
+
# data indices are a subset of df indices
|
| 68 |
+
|
| 69 |
+
# Let's match by index
|
| 70 |
+
test_indices = data.index[split_idx:]
|
| 71 |
+
# Price predecessors (bases)
|
| 72 |
+
# If a return is at time t, it depends on Price[t-1]
|
| 73 |
+
|
| 74 |
+
# Simple reconstruction:
|
| 75 |
+
# Get the price immediately preceding the test set
|
| 76 |
+
base_price_idx = split_idx - 1
|
| 77 |
+
if base_price_idx < 0:
|
| 78 |
+
# Fallback if split is at 0 (unlikely)
|
| 79 |
+
base_price = df['Close'].iloc[0]
|
| 80 |
+
else:
|
| 81 |
+
# The return at data.iloc[base_price_idx] is NOT the price
|
| 82 |
+
# data only has returns.
|
| 83 |
+
# We need to look at the original DF
|
| 84 |
+
# The 'data' was created by dropping first row of df.
|
| 85 |
+
# So data.iloc[0] corresponds to df.iloc[1].
|
| 86 |
+
# data.iloc[split_idx] is roughly df.iloc[split_idx+1]
|
| 87 |
+
|
| 88 |
+
# Exact alignment:
|
| 89 |
+
# data index i matches df index i (if we kept index)
|
| 90 |
+
pass
|
| 91 |
+
|
| 92 |
+
# Let's rely on the original df
|
| 93 |
+
# The returns in "y" (targets) correspond to `data.iloc[split_idx:]`
|
| 94 |
+
# The Prices we want to compare against are `df['Close'][data.index[split_idx:]]`
|
| 95 |
+
|
| 96 |
+
y_true_prices = df['Close'].loc[data.index[split_idx:]].values
|
| 97 |
+
|
| 98 |
+
# Base price for the FIRST prediction:
|
| 99 |
+
# The first return predicted is for data.index[split_idx]
|
| 100 |
+
# So we need Price at data.index[split_idx-1] (previous day)
|
| 101 |
+
# OR simpler: df['Close'].loc[data.index[split_idx-1]]
|
| 102 |
+
|
| 103 |
+
first_test_idx_pos = df.index.get_loc(data.index[split_idx])
|
| 104 |
+
base_price = df['Close'].iloc[first_test_idx_pos - 1]
|
| 105 |
+
|
| 106 |
+
reconstructed = []
|
| 107 |
+
curr = base_price
|
| 108 |
+
for r in pred_returns:
|
| 109 |
+
curr = curr * np.exp(r)
|
| 110 |
+
reconstructed.append(curr)
|
| 111 |
+
|
| 112 |
+
pred = np.array(reconstructed)
|
| 113 |
+
y_true = y_true_prices[:len(pred)] # sync lengths
|
| 114 |
|
| 115 |
rmse = math.sqrt(mean_squared_error(y_true, pred))
|
| 116 |
mae = mean_absolute_error(y_true, pred)
|
train.py
CHANGED
|
@@ -4,7 +4,7 @@ import numpy as np
|
|
| 4 |
import pandas as pd
|
| 5 |
import yfinance as yf
|
| 6 |
|
| 7 |
-
from sklearn.preprocessing import
|
| 8 |
from sklearn.metrics import mean_absolute_error, mean_squared_error
|
| 9 |
|
| 10 |
import torch
|
|
@@ -49,9 +49,17 @@ def train(symbol: str, seq_len: int = 60, epochs: int = 5, batch_size: int = 32,
|
|
| 49 |
|
| 50 |
# --- data ---
|
| 51 |
df = fetch_data(symbol, start, end)
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
scaled = scaler.fit_transform(data)
|
| 56 |
|
| 57 |
split_idx = int(len(scaled) * 0.8)
|
|
@@ -107,9 +115,52 @@ def train(symbol: str, seq_len: int = 60, epochs: int = 5, batch_size: int = 32,
|
|
| 107 |
model.eval()
|
| 108 |
with torch.no_grad():
|
| 109 |
X_t = torch.from_numpy(X_test_like_train).float().to(device)
|
| 110 |
-
preds_scaled = model(X_t).cpu().numpy() # scaled
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
rmse = math.sqrt(mean_squared_error(y_true, preds))
|
| 115 |
mae = mean_absolute_error(y_true, preds)
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
import yfinance as yf
|
| 6 |
|
| 7 |
+
from sklearn.preprocessing import StandardScaler
|
| 8 |
from sklearn.metrics import mean_absolute_error, mean_squared_error
|
| 9 |
|
| 10 |
import torch
|
|
|
|
| 49 |
|
| 50 |
# --- data ---
|
| 51 |
df = fetch_data(symbol, start, end)
|
| 52 |
+
|
| 53 |
+
# Calculate Log Returns: ln(Pt / Pt-1)
|
| 54 |
+
# This makes the data stationary and solves scaling issues with absolute prices
|
| 55 |
+
df['LogReturn'] = np.log(df['Close'] / df['Close'].shift(1))
|
| 56 |
+
df = df.dropna()
|
| 57 |
+
|
| 58 |
+
data = df['LogReturn'].values.reshape(-1, 1)
|
| 59 |
+
|
| 60 |
+
# Use StandardScaler for returns (centered around 0)
|
| 61 |
+
from sklearn.preprocessing import StandardScaler
|
| 62 |
+
scaler = StandardScaler()
|
| 63 |
scaled = scaler.fit_transform(data)
|
| 64 |
|
| 65 |
split_idx = int(len(scaled) * 0.8)
|
|
|
|
| 115 |
model.eval()
|
| 116 |
with torch.no_grad():
|
| 117 |
X_t = torch.from_numpy(X_test_like_train).float().to(device)
|
| 118 |
+
preds_scaled = model(X_t).cpu().numpy() # scaled log-returns
|
| 119 |
+
|
| 120 |
+
# Inverse transform to get actual log-returns
|
| 121 |
+
preds_returns = scaler.inverse_transform(preds_scaled).flatten()
|
| 122 |
+
y_true_returns = scaler.inverse_transform(y_test_like_train).flatten()
|
| 123 |
+
|
| 124 |
+
# Reconstruct Prices
|
| 125 |
+
# We need the reference price just before the test sequence started
|
| 126 |
+
# The 'test_scaled' starts at split_idx.
|
| 127 |
+
# The corresponding Price index in df is also split_idx (after dropna for shift).
|
| 128 |
+
# actually, X_test_like_train covers the test set.
|
| 129 |
+
# We need the price at (split_idx - 1) as the base for the first return in test set.
|
| 130 |
+
|
| 131 |
+
# Get original prices corresponding to the test set
|
| 132 |
+
# The test set indices in 'data' start at split_idx
|
| 133 |
+
# So the price at split_idx corresponds to the first return in test_scaled
|
| 134 |
+
# Price[t] = Price[t-1] * exp(Return[t])
|
| 135 |
+
|
| 136 |
+
test_prices = df['Close'].values[split_idx:]
|
| 137 |
+
# validation: len(test_prices) should equal len(y_test_like_train)
|
| 138 |
+
# But make_sequences consumes 'seq_len' from the start.
|
| 139 |
+
# X_test_like_train was built from [train_scaled[-seq_len:], test_scaled]
|
| 140 |
+
# So it actually produces predictions for ALL of test_scaled.
|
| 141 |
+
|
| 142 |
+
# Let's reconstruct systematically:
|
| 143 |
+
# We need the price that precedes the first prediction.
|
| 144 |
+
# The first target in y_test_like_train corresponds to `test_scaled[0]`.
|
| 145 |
+
# The price for that is df['Close'].iloc[split_idx].
|
| 146 |
+
# The PREVIOUS price is df['Close'].iloc[split_idx - 1].
|
| 147 |
+
|
| 148 |
+
base_price = df['Close'].iloc[split_idx - 1]
|
| 149 |
+
|
| 150 |
+
reconstructed_preds = []
|
| 151 |
+
curr = base_price
|
| 152 |
+
for r in preds_returns:
|
| 153 |
+
curr = curr * np.exp(r)
|
| 154 |
+
reconstructed_preds.append(curr)
|
| 155 |
+
|
| 156 |
+
# We can perform the same for standard checks, or just compare against actual test prices
|
| 157 |
+
# actual test prices:
|
| 158 |
+
actual_prices = df['Close'].iloc[split_idx:].values
|
| 159 |
+
|
| 160 |
+
# Truncate if lengths differ (rare with this logic but good for safety)
|
| 161 |
+
min_len = min(len(reconstructed_preds), len(actual_prices))
|
| 162 |
+
preds = np.array(reconstructed_preds[:min_len])
|
| 163 |
+
y_true = actual_prices[:min_len]
|
| 164 |
|
| 165 |
rmse = math.sqrt(mean_squared_error(y_true, preds))
|
| 166 |
mae = mean_absolute_error(y_true, preds)
|