Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -6,9 +6,7 @@ from datetime import datetime, timedelta
|
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
from plotly.subplots import make_subplots
|
| 8 |
import spaces
|
| 9 |
-
|
| 10 |
-
from chronos import Chronos2Pipeline
|
| 11 |
-
|
| 12 |
|
| 13 |
def get_indonesian_stocks():
|
| 14 |
return {
|
|
@@ -159,27 +157,30 @@ def format_large_number(num):
|
|
| 159 |
@spaces.GPU(duration=120)
|
| 160 |
def predict_prices(data, model=None, tokenizer=None, prediction_days=30):
|
| 161 |
try:
|
| 162 |
-
# PENGGANTIAN: Gunakan Chronos2Pipeline dan model amazon/chronos-2
|
| 163 |
pipeline = Chronos2Pipeline.from_pretrained("amazon/chronos-2", device_map="auto")
|
| 164 |
|
| 165 |
-
# Chronos-2 membutuhkan input dalam format DataFrame (predict_df)
|
| 166 |
context_df = data[['Close']].reset_index()
|
| 167 |
context_df.columns = ['timestamp', 'target']
|
| 168 |
context_df['id'] = 'stock_price'
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
with torch.no_grad():
|
| 171 |
-
# Menggunakan predict_df()
|
| 172 |
pred_df = pipeline.predict_df(
|
| 173 |
context_df,
|
| 174 |
prediction_length=prediction_days,
|
| 175 |
id_column="id",
|
| 176 |
timestamp_column="timestamp",
|
| 177 |
target="target",
|
| 178 |
-
# Kita ambil kuantil 0.5 (median) sebagai prediksi mean
|
| 179 |
quantile_levels=[0.5]
|
| 180 |
)
|
| 181 |
|
| 182 |
-
# Ekstraksi hasil prediksi dari DataFrame
|
| 183 |
mean_forecast = pred_df['target_0.5'].values.astype(np.float32)
|
| 184 |
predicted_dates = pred_df['timestamp']
|
| 185 |
|
|
@@ -189,14 +190,10 @@ def predict_prices(data, model=None, tokenizer=None, prediction_days=30):
|
|
| 189 |
predicted_mean = float(np.mean(mean_forecast))
|
| 190 |
change_pct = ((predicted_mean - last_price) / last_price) * 100 if last_price != 0 else 0
|
| 191 |
|
| 192 |
-
# Perbarui summary model
|
| 193 |
return {'values': mean_forecast, 'dates': predicted_dates, 'high_30d': predicted_high, 'low_30d': predicted_low, 'mean_30d': predicted_mean, 'change_pct': change_pct, 'summary': f"AI Model: Amazon Chronos-2\nPredicted High: {predicted_high:.2f}\nPredicted Low: {predicted_low:.2f}\nExpected Change: {change_pct:.2f}%"}
|
| 194 |
|
| 195 |
except Exception as e:
|
| 196 |
-
# Error handling yang lebih baik
|
| 197 |
error_message = f'Model error: {e}'
|
| 198 |
-
if "context_tensor" in str(e) or "context" in str(e) or "pipeline" in str(e):
|
| 199 |
-
error_message = f"Prediction API Error (Chronos-2): Cek instalasi 'chronos-forecasting' dan argumen di predict_prices(). Detail: {e}"
|
| 200 |
print(f"Error in prediction: {e}")
|
| 201 |
return {'values': [], 'dates': [], 'high_30d': 0, 'low_30d': 0, 'mean_30d': 0, 'change_pct': 0, 'summary': error_message}
|
| 202 |
|
|
@@ -206,8 +203,6 @@ def create_prediction_chart(data, predictions):
|
|
| 206 |
fig = go.Figure()
|
| 207 |
fig.add_trace(go.Scatter(x=data.index[-60:], y=data['Close'].values[-60:], name='Historical Price', line=dict(color='blue', width=2)))
|
| 208 |
fig.add_trace(go.Scatter(x=predictions['dates'], y=predictions['values'], name='AI Prediction', line=dict(color='red', width=2, dash='dash')))
|
| 209 |
-
# Perhitungan band harus menggunakan prediksi yang sudah dikuantil (jika ada) atau distandardisasi
|
| 210 |
-
# Karena kita hanya menggunakan satu kuantil (0.5), kita asumsikan pred_std kecil
|
| 211 |
pred_std = np.std(predictions['values']) if len(predictions['values']) > 1 else 0.05 * predictions['values'][0]
|
| 212 |
upper_band = predictions['values'] + (pred_std * 1.96)
|
| 213 |
lower_band = predictions['values'] - (pred_std * 1.96)
|
|
|
|
| 6 |
import plotly.graph_objects as go
|
| 7 |
from plotly.subplots import make_subplots
|
| 8 |
import spaces
|
| 9 |
+
from chronos import Chronos2Pipeline
|
|
|
|
|
|
|
| 10 |
|
| 11 |
def get_indonesian_stocks():
|
| 12 |
return {
|
|
|
|
| 157 |
@spaces.GPU(duration=120)
|
| 158 |
def predict_prices(data, model=None, tokenizer=None, prediction_days=30):
|
| 159 |
try:
|
|
|
|
| 160 |
pipeline = Chronos2Pipeline.from_pretrained("amazon/chronos-2", device_map="auto")
|
| 161 |
|
|
|
|
| 162 |
context_df = data[['Close']].reset_index()
|
| 163 |
context_df.columns = ['timestamp', 'target']
|
| 164 |
context_df['id'] = 'stock_price'
|
| 165 |
|
| 166 |
+
# Fix Error: Could not infer frequency (membuat data menjadi frekuensi harian)
|
| 167 |
+
context_df['timestamp'] = pd.to_datetime(context_df['timestamp'])
|
| 168 |
+
context_df = context_df.set_index('timestamp').asfreq('D').fillna(method='ffill').reset_index()
|
| 169 |
+
|
| 170 |
+
context_df['id'] = 'stock_price'
|
| 171 |
+
context_df.columns = ['timestamp', 'target', 'id']
|
| 172 |
+
|
| 173 |
+
|
| 174 |
with torch.no_grad():
|
|
|
|
| 175 |
pred_df = pipeline.predict_df(
|
| 176 |
context_df,
|
| 177 |
prediction_length=prediction_days,
|
| 178 |
id_column="id",
|
| 179 |
timestamp_column="timestamp",
|
| 180 |
target="target",
|
|
|
|
| 181 |
quantile_levels=[0.5]
|
| 182 |
)
|
| 183 |
|
|
|
|
| 184 |
mean_forecast = pred_df['target_0.5'].values.astype(np.float32)
|
| 185 |
predicted_dates = pred_df['timestamp']
|
| 186 |
|
|
|
|
| 190 |
predicted_mean = float(np.mean(mean_forecast))
|
| 191 |
change_pct = ((predicted_mean - last_price) / last_price) * 100 if last_price != 0 else 0
|
| 192 |
|
|
|
|
| 193 |
return {'values': mean_forecast, 'dates': predicted_dates, 'high_30d': predicted_high, 'low_30d': predicted_low, 'mean_30d': predicted_mean, 'change_pct': change_pct, 'summary': f"AI Model: Amazon Chronos-2\nPredicted High: {predicted_high:.2f}\nPredicted Low: {predicted_low:.2f}\nExpected Change: {change_pct:.2f}%"}
|
| 194 |
|
| 195 |
except Exception as e:
|
|
|
|
| 196 |
error_message = f'Model error: {e}'
|
|
|
|
|
|
|
| 197 |
print(f"Error in prediction: {e}")
|
| 198 |
return {'values': [], 'dates': [], 'high_30d': 0, 'low_30d': 0, 'mean_30d': 0, 'change_pct': 0, 'summary': error_message}
|
| 199 |
|
|
|
|
| 203 |
fig = go.Figure()
|
| 204 |
fig.add_trace(go.Scatter(x=data.index[-60:], y=data['Close'].values[-60:], name='Historical Price', line=dict(color='blue', width=2)))
|
| 205 |
fig.add_trace(go.Scatter(x=predictions['dates'], y=predictions['values'], name='AI Prediction', line=dict(color='red', width=2, dash='dash')))
|
|
|
|
|
|
|
| 206 |
pred_std = np.std(predictions['values']) if len(predictions['values']) > 1 else 0.05 * predictions['values'][0]
|
| 207 |
upper_band = predictions['values'] + (pred_std * 1.96)
|
| 208 |
lower_band = predictions['values'] - (pred_std * 1.96)
|