Spaces:
Sleeping
Sleeping
Анастасия
commited on
Commit
·
bc2783e
1
Parent(s):
3b29e59
- .DS_Store +0 -0
- pages/2_💲 _Прогноз_акций. Prophet.py +2 -2
- pages/3_🪙_Прогноз_Bitcoin USD. BiLSTM.py +83 -65
.DS_Store
CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
|
|
pages/2_💲 _Прогноз_акций. Prophet.py
CHANGED
@@ -118,8 +118,8 @@ def ticker(data, holidays_df, text1, text2, k):
|
|
118 |
future = future[~future['ds'].isin(holidays_df['ds'])]
|
119 |
forecast_test = model.predict(future)
|
120 |
# Создаем фрейм для прогноза на +14 дней после последней даты
|
121 |
-
future_14_days = model.make_future_dataframe(periods=
|
122 |
-
future_14_days['ds'] = pd.date_range(start=last_date + pd.DateOffset(1), periods=
|
123 |
forecast_14_days = model.predict(future_14_days)
|
124 |
|
125 |
# Отрисовка графика
|
|
|
118 |
future = future[~future['ds'].isin(holidays_df['ds'])]
|
119 |
forecast_test = model.predict(future)
|
120 |
# Создаем фрейм для прогноза на +14 дней после последней даты
|
121 |
+
future_14_days = model.make_future_dataframe(periods=period, freq='B', include_history=False)
|
122 |
+
future_14_days['ds'] = pd.date_range(start=last_date + pd.DateOffset(1), periods=period, freq='B')
|
123 |
forecast_14_days = model.predict(future_14_days)
|
124 |
|
125 |
# Отрисовка графика
|
pages/3_🪙_Прогноз_Bitcoin USD. BiLSTM.py
CHANGED
@@ -5,12 +5,12 @@ import numpy as np
|
|
5 |
import matplotlib.pyplot as plt
|
6 |
import torch
|
7 |
import torch.nn as nn
|
8 |
-
import torch.optim as optim
|
9 |
from datetime import date, datetime, timedelta
|
10 |
from model.BiLSTM_model import BiLSTM
|
11 |
from sklearn.metrics import mean_squared_error
|
12 |
from sklearn.preprocessing import MinMaxScaler
|
13 |
from datetime import timedelta
|
|
|
14 |
|
15 |
st.set_page_config(layout='wide', initial_sidebar_state='expanded')
|
16 |
st.set_option('deprecation.showPyplotGlobalUse', False)
|
@@ -69,7 +69,6 @@ num_layers = 3
|
|
69 |
output_size = 1
|
70 |
model = BiLSTM(input_size, hidden_size, num_layers, output_size)
|
71 |
criterion = nn.MSELoss()
|
72 |
-
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
73 |
|
74 |
model = BiLSTM(1, 128, 3, 1)
|
75 |
model.load_state_dict(torch.load('model/model_weights.pth'))
|
@@ -89,81 +88,100 @@ with torch.no_grad():
|
|
89 |
test_weighted_mape = weighted_mape(test_predictions, y_test, weights)
|
90 |
|
91 |
# st.write(f'Test Loss: {test_loss.item():.4f}')
|
92 |
-
st.write(f'Test RMSE: {test_rmse:.4f}')
|
93 |
-
st.write(f'Test MAPE: {test_mape:.4f}%')
|
94 |
-
st.write(f'Test Weighted MAPE: {test_weighted_mape:.4f}%')
|
95 |
-
|
96 |
-
# Предсказания на тестовых данных
|
97 |
-
with torch.no_grad():
|
98 |
-
test_predictions = model(X_test)
|
99 |
-
adjusted_future_predictions = scaler.inverse_transform(test_predictions.cpu().numpy())
|
100 |
-
|
101 |
-
# st.write(adjusted_future_predictions)
|
102 |
-
# df_predictions = pd.DataFrame({'Predictions': adjusted_future_predictions.flatten()})
|
103 |
-
# df_predictions['Predictions'] = df.iloc[:, 0].values
|
104 |
-
# sum_test = pd.concat([df['Date'][train_size:], df_predictions], axis=1)
|
105 |
-
# st.write(sum_test)
|
106 |
-
# # adjusted_future_predictions = pd.DataFrame({'Date': df['Date'][train_size:].reset_index(), 'Predictions': adjusted_future_predictions})
|
107 |
-
# # st.write(adjusted_future_predictions)
|
108 |
-
# # pd.concat(df['Date'][train_size:], adjusted_future_predictions)
|
109 |
-
filtered_df = df
|
110 |
-
|
111 |
-
# Прогнозы с учетом трендов
|
112 |
-
trend_first_day = adjusted_future_predictions[0] - filtered_df['Adj Close'].iloc[-1]
|
113 |
-
trend_14_days = adjusted_future_predictions[-1] - adjusted_future_predictions[0]
|
114 |
-
adjusted_future_predictions = [filtered_df['Adj Close'].iloc[-1] + trend_first_day + (trend_14_days / 14) * i for i in range(14)]
|
115 |
-
|
116 |
-
# Вычисление даты, которая находится на 3 месяца назад
|
117 |
-
start_date = datetime.strptime(latest_date, '%Y-%m-%d') - timedelta(days=90)
|
118 |
-
|
119 |
-
# Преобразование строк столбца 'Date' в объекты datetime
|
120 |
-
df['Date'] = pd.to_datetime(df['Date'])
|
121 |
-
|
122 |
-
# Фильтрация данных за последние 3 месяца
|
123 |
-
filtered_df = df[(df['Date'] >= start_date) & (df['Date'] <= latest_date)]
|
124 |
|
125 |
# Генерация дат для будущих предсказаний
|
126 |
-
future_dates = [
|
127 |
-
|
128 |
# Расчет тренда на первый день
|
129 |
-
trend_first_day =
|
130 |
-
|
131 |
-
|
132 |
-
trend_14_days = adjusted_future_predictions[-1] - adjusted_future_predictions[0]
|
133 |
-
|
134 |
# Прогнозы с учетом трендов
|
135 |
-
adjusted_future_predictions = [
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
future_dates = [df['Date'].values[-1] + np.timedelta64(i+1, 'D') for i in range(14)]
|
152 |
|
153 |
# Расчет тренда на первый день
|
154 |
-
trend_first_day = adjusted_future_predictions[0] -
|
155 |
|
156 |
# Расчет тренда на последний день
|
157 |
trend_last_day = adjusted_future_predictions[-1] - adjusted_future_predictions[0]
|
158 |
|
159 |
-
# Вывод прогнозов
|
160 |
-
print("Прогноз на 14 дней вперед:")
|
161 |
-
for i, (date, pred) in enumerate(zip(future_dates, adjusted_future_predictions)):
|
162 |
-
print(f"День {i+1} ({date}): Прогноз: {float(pred):.2f}")
|
163 |
-
|
164 |
# Вывод тренда на первый и последний день
|
165 |
trend_first_day_text = "Рост" if trend_first_day > 0 else "Падение" if trend_first_day < 0 else "Нет тренда"
|
166 |
trend_last_day_text = "Рост" if trend_last_day > 0 else "Падение" if trend_last_day < 0 else "Нет тренда"
|
167 |
|
168 |
-
st.
|
169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import matplotlib.pyplot as plt
|
6 |
import torch
|
7 |
import torch.nn as nn
|
|
|
8 |
from datetime import date, datetime, timedelta
|
9 |
from model.BiLSTM_model import BiLSTM
|
10 |
from sklearn.metrics import mean_squared_error
|
11 |
from sklearn.preprocessing import MinMaxScaler
|
12 |
from datetime import timedelta
|
13 |
+
import plotly.graph_objects as go
|
14 |
|
15 |
st.set_page_config(layout='wide', initial_sidebar_state='expanded')
|
16 |
st.set_option('deprecation.showPyplotGlobalUse', False)
|
|
|
69 |
output_size = 1
|
70 |
model = BiLSTM(input_size, hidden_size, num_layers, output_size)
|
71 |
criterion = nn.MSELoss()
|
|
|
72 |
|
73 |
model = BiLSTM(1, 128, 3, 1)
|
74 |
model.load_state_dict(torch.load('model/model_weights.pth'))
|
|
|
88 |
test_weighted_mape = weighted_mape(test_predictions, y_test, weights)
|
89 |
|
90 |
# st.write(f'Test Loss: {test_loss.item():.4f}')
|
91 |
+
# st.write(f'Test RMSE: {test_rmse:.4f}')
|
92 |
+
# st.write(f'Test MAPE: {test_mape:.4f}%')
|
93 |
+
# st.write(f'Test Weighted MAPE: {test_weighted_mape:.4f}%')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
|
95 |
# Генерация дат для будущих предсказаний
|
96 |
+
future_dates = [df['Date'].values[-1] + np.timedelta64(i+1, 'D') for i in range(period)]
|
|
|
97 |
# Расчет тренда на первый день
|
98 |
+
trend_first_day = test_predictions[0] - df['Adj Close'].iloc[-1]
|
99 |
+
# Расчет тренда на последний день
|
100 |
+
trend_last_day = test_predictions[-1] - test_predictions[0]
|
|
|
|
|
101 |
# Прогнозы с учетом трендов
|
102 |
+
adjusted_future_predictions = [df['Adj Close'].iloc[-1] + trend_first_day + (trend_last_day / period) * i for i in range(period)]
|
103 |
+
|
104 |
+
adjusted_future_pred = pd.Series([x.item() for x in adjusted_future_predictions])
|
105 |
+
|
106 |
+
# Форматирование каждой даты в нужный формат
|
107 |
+
formatted_dates = np.datetime_as_string(future_dates)
|
108 |
+
|
109 |
+
fig = go.Figure()
|
110 |
+
fig.add_trace(go.Scatter(x=df['Date'],
|
111 |
+
y=df['Adj Close'],
|
112 |
+
mode='lines',
|
113 |
+
name='Актуальные данные',
|
114 |
+
line=dict(color='blue', width=2)))
|
115 |
+
|
116 |
+
fig.add_trace(go.Scatter(x=formatted_dates,
|
117 |
+
y=adjusted_future_pred,
|
118 |
+
mode='lines+markers',
|
119 |
+
name='Прогноз будущее',
|
120 |
+
line=dict(color='red', width=2, dash='dash')))
|
121 |
+
|
122 |
+
fig.update_layout(title=f'Прогноз по Bitcoin на {period} дней',
|
123 |
+
xaxis_title='Дата',
|
124 |
+
yaxis_title='Цена закрытия',
|
125 |
+
xaxis=dict(tickangle=45),
|
126 |
+
# xaxis_range=[datetime(2023, 12, 25), datetime(2024, 2, 13)],
|
127 |
+
showlegend=True)
|
128 |
+
|
129 |
+
st.plotly_chart(fig, use_container_width=True)
|
130 |
+
|
131 |
+
fig = go.Figure()
|
132 |
+
fig.add_trace(go.Scatter(x=df['Date'],
|
133 |
+
y=df['Adj Close'],
|
134 |
+
mode='lines',
|
135 |
+
name='Актуальные данные',
|
136 |
+
line=dict(color='blue', width=2)))
|
137 |
+
|
138 |
+
fig.add_trace(go.Scatter(x=formatted_dates,
|
139 |
+
y=adjusted_future_pred,
|
140 |
+
mode='lines+markers',
|
141 |
+
name='Прогноз будущее',
|
142 |
+
line=dict(color='red', width=2, dash='dash')))
|
143 |
+
|
144 |
+
fig.update_layout(title=f'Прогноз по Bitcoin на {period} дней (в интервале месяца)',
|
145 |
+
xaxis_title='Дата',
|
146 |
+
yaxis_title='Цена закрытия',
|
147 |
+
xaxis=dict(tickangle=45),
|
148 |
+
# xaxis_range=[datetime(2023, 12, 25), datetime(2024, 2, 13)],
|
149 |
+
xaxis_range=[datetime.strptime(latest_date, '%Y-%m-%d') - timedelta(days=12), \
|
150 |
+
datetime.strptime(latest_date, '%Y-%m-%d') + timedelta(days=18)],
|
151 |
+
showlegend=True)
|
152 |
+
|
153 |
+
st.plotly_chart(fig, use_container_width=True)
|
154 |
+
|
155 |
+
# Генерация дат для будущих педсказаний
|
156 |
future_dates = [df['Date'].values[-1] + np.timedelta64(i+1, 'D') for i in range(14)]
|
157 |
|
158 |
# Расчет тренда на первый день
|
159 |
+
trend_first_day = adjusted_future_predictions[0] - df['Adj Close'].iloc[-1]
|
160 |
|
161 |
# Расчет тренда на последний день
|
162 |
trend_last_day = adjusted_future_predictions[-1] - adjusted_future_predictions[0]
|
163 |
|
|
|
|
|
|
|
|
|
|
|
164 |
# Вывод тренда на первый и последний день
|
165 |
trend_first_day_text = "Рост" if trend_first_day > 0 else "Падение" if trend_first_day < 0 else "Нет тренда"
|
166 |
trend_last_day_text = "Рост" if trend_last_day > 0 else "Падение" if trend_last_day < 0 else "Нет тренда"
|
167 |
|
168 |
+
check = st.checkbox('Результаты прогноза Bitcoin')
|
169 |
+
if check:
|
170 |
+
col1, col2 = st.columns([1, 1])
|
171 |
+
with col1:
|
172 |
+
st.write("**Информация.** \
|
173 |
+
Прогноз составлен для будущего периода с возможностью выбора до 14 дней с указанием тенденции дельнейшего развития.")
|
174 |
+
st.markdown("**Метрики для тестовой выборки:**")
|
175 |
+
st.write(f"RMSE: {test_rmse:.2f}")
|
176 |
+
st.write(f"MAPE: {test_mape:.2f}%")
|
177 |
+
st.write(f"Weighted MAPE: {test_weighted_mape:.2f}%")
|
178 |
+
# Оценка тренда на первый день
|
179 |
+
st.write(f'Тенденция на первый день: {trend_first_day_text}')
|
180 |
+
# Оценка тренда на период прогноза
|
181 |
+
st.write(f'Тенденция на период прогноза: {trend_last_day_text}')
|
182 |
+
with col2:
|
183 |
+
results = pd.DataFrame({
|
184 |
+
'Дата': future_dates,
|
185 |
+
'Прогноз': adjusted_future_pred.values.round(2)
|
186 |
+
})
|
187 |
+
st.dataframe(results.set_index('Дата'))
|