Spaces:
Sleeping
Sleeping
Oscar Wang
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -6,7 +6,7 @@ import pandas as pd
|
|
6 |
import logging
|
7 |
|
8 |
# Set up logging
|
9 |
-
logging.basicConfig(level=logging.INFO)
|
10 |
|
11 |
def fetch_eth_price(period, past_data_limit=None):
|
12 |
eth = yf.Ticker("ETH-USD")
|
@@ -27,40 +27,71 @@ def fetch_eth_price(period, past_data_limit=None):
|
|
27 |
predict_steps = 720 # Next 30 days
|
28 |
freq = 'H' # Hourly frequency
|
29 |
else:
|
|
|
30 |
return None, None, None
|
31 |
|
32 |
data.index = pd.DatetimeIndex(data.index)
|
33 |
data = data.asfreq(freq) # Ensure the data has a consistent frequency
|
34 |
|
35 |
# Limit the amount of past data used for training
|
36 |
-
if past_data_limit is not None:
|
37 |
data = data.iloc[-past_data_limit:]
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
39 |
return data, predict_steps, freq
|
40 |
|
41 |
def make_predictions(data, predict_steps, freq):
|
|
|
|
|
|
|
|
|
42 |
logging.info("Starting model training...")
|
43 |
model = ARIMA(data['Close'], order=(5, 1, 0))
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
45 |
logging.info("Model training completed.")
|
46 |
|
47 |
logging.info("Generating predictions...")
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
49 |
future_dates = pd.date_range(start=data.index[-1], periods=predict_steps+1, freq=freq, inclusive='right')
|
50 |
forecast_df = pd.DataFrame(forecast, index=future_dates[1:], columns=['Prediction'])
|
51 |
-
logging.info("Predictions generated.")
|
52 |
-
|
53 |
return forecast_df
|
54 |
|
55 |
def plot_eth(period):
|
56 |
-
#
|
57 |
data, predict_steps, freq = fetch_eth_price(period, past_data_limit=500)
|
|
|
|
|
|
|
|
|
|
|
58 |
forecast_df = make_predictions(data, predict_steps, freq)
|
59 |
|
|
|
|
|
|
|
|
|
60 |
fig = go.Figure()
|
61 |
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='ETH Price'))
|
62 |
fig.add_trace(go.Scatter(x=forecast_df.index, y=forecast_df['Prediction'], mode='lines', name='Prediction', line=dict(dash='dash')))
|
63 |
fig.update_layout(title=f"ETH Price and Predictions ({period})", xaxis_title="Date", yaxis_title="Price (USD)")
|
|
|
|
|
64 |
|
65 |
return fig
|
66 |
|
|
|
6 |
import logging
|
7 |
|
8 |
# Set up logging
|
9 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
10 |
|
11 |
def fetch_eth_price(period, past_data_limit=None):
|
12 |
eth = yf.Ticker("ETH-USD")
|
|
|
27 |
predict_steps = 720 # Next 30 days
|
28 |
freq = 'H' # Hourly frequency
|
29 |
else:
|
30 |
+
logging.error("Invalid period selected.")
|
31 |
return None, None, None
|
32 |
|
33 |
data.index = pd.DatetimeIndex(data.index)
|
34 |
data = data.asfreq(freq) # Ensure the data has a consistent frequency
|
35 |
|
36 |
# Limit the amount of past data used for training
|
37 |
+
if past_data_limit is not None and len(data) > past_data_limit:
|
38 |
data = data.iloc[-past_data_limit:]
|
39 |
+
|
40 |
+
if data.empty:
|
41 |
+
logging.error("Data is empty after applying past data limit.")
|
42 |
+
return None, None, None
|
43 |
+
|
44 |
+
logging.info(f"Fetched {len(data)} data points for period '{period}'")
|
45 |
return data, predict_steps, freq
|
46 |
|
47 |
def make_predictions(data, predict_steps, freq):
|
48 |
+
if data is None or data.empty:
|
49 |
+
logging.error("No data available for model training.")
|
50 |
+
return None
|
51 |
+
|
52 |
logging.info("Starting model training...")
|
53 |
model = ARIMA(data['Close'], order=(5, 1, 0))
|
54 |
+
try:
|
55 |
+
model_fit = model.fit()
|
56 |
+
except Exception as e:
|
57 |
+
logging.error(f"Model training failed: {e}")
|
58 |
+
return None
|
59 |
+
|
60 |
logging.info("Model training completed.")
|
61 |
|
62 |
logging.info("Generating predictions...")
|
63 |
+
try:
|
64 |
+
forecast = model_fit.forecast(steps=predict_steps)
|
65 |
+
except Exception as e:
|
66 |
+
logging.error(f"Prediction generation failed: {e}")
|
67 |
+
return None
|
68 |
+
|
69 |
future_dates = pd.date_range(start=data.index[-1], periods=predict_steps+1, freq=freq, inclusive='right')
|
70 |
forecast_df = pd.DataFrame(forecast, index=future_dates[1:], columns=['Prediction'])
|
71 |
+
logging.info("Predictions generated successfully.")
|
72 |
+
|
73 |
return forecast_df
|
74 |
|
75 |
def plot_eth(period):
|
76 |
+
# Limit the data to the last 500 points for faster processing
|
77 |
data, predict_steps, freq = fetch_eth_price(period, past_data_limit=500)
|
78 |
+
|
79 |
+
if data is None or predict_steps is None or freq is None:
|
80 |
+
logging.error("Failed to fetch data or invalid period selected.")
|
81 |
+
return go.Figure().update_layout(title="Error: No data available")
|
82 |
+
|
83 |
forecast_df = make_predictions(data, predict_steps, freq)
|
84 |
|
85 |
+
if forecast_df is None or forecast_df.empty:
|
86 |
+
logging.error("Prediction dataframe is empty or None.")
|
87 |
+
return go.Figure().update_layout(title="Error: Prediction failed")
|
88 |
+
|
89 |
fig = go.Figure()
|
90 |
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='ETH Price'))
|
91 |
fig.add_trace(go.Scatter(x=forecast_df.index, y=forecast_df['Prediction'], mode='lines', name='Prediction', line=dict(dash='dash')))
|
92 |
fig.update_layout(title=f"ETH Price and Predictions ({period})", xaxis_title="Date", yaxis_title="Price (USD)")
|
93 |
+
|
94 |
+
logging.info("Plot updated with predictions.")
|
95 |
|
96 |
return fig
|
97 |
|