Spaces:
Runtime error
Runtime error
Commit
·
7f2805a
1
Parent(s):
4d79a0c
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
def
|
4 |
-
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
demo.launch()
|
|
|
1 |
+
pip install gradio
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
import tensorflow as tf
|
5 |
+
import random
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
import gradio as gr
|
8 |
+
from sklearn.model_selection import train_test_split
|
9 |
+
from sklearn.preprocessing import MinMaxScaler
|
10 |
+
from tensorflow.keras.models import Sequential
|
11 |
+
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
12 |
+
from tensorflow.keras.callbacks import EarlyStopping
|
13 |
|
14 |
+
def create_dataset(data, time_step=1):
|
15 |
+
X, y = [], []
|
16 |
+
for i in range(len(data) - time_step - 1):
|
17 |
+
a = data[i:(i + time_step), :]
|
18 |
+
X.append(a)
|
19 |
+
y.append(data[i + time_step, :])
|
20 |
+
return np.array(X), np.array(y)
|
21 |
|
22 |
+
def predict_future(model, initial_data, time_step, num_months):
|
23 |
+
predictions = []
|
24 |
+
current_data = initial_data[-time_step:]
|
25 |
+
|
26 |
+
for _ in range(num_months * 30):
|
27 |
+
current_data_reshaped = current_data.reshape(1, time_step, current_data.shape[1])
|
28 |
+
next_prediction = model.predict(current_data_reshaped)
|
29 |
+
predictions.append(next_prediction[0])
|
30 |
+
current_data = np.append(current_data[1:], next_prediction, axis=0)
|
31 |
+
|
32 |
+
return np.array(predictions)
|
33 |
+
|
34 |
+
def generate_plots(file):
|
35 |
+
seed = 65
|
36 |
+
tf.random.set_seed(seed)
|
37 |
+
np.random.seed(seed)
|
38 |
+
random.seed(seed)
|
39 |
+
|
40 |
+
# Чтение данных из Excel файла
|
41 |
+
data = pd.read_excel(file)
|
42 |
+
data.dropna(inplace=True)
|
43 |
+
data = data[['EUR_RUB', 'GBP_RUB', 'USD_RUB']]
|
44 |
+
|
45 |
+
values = data.values
|
46 |
+
scaler = MinMaxScaler()
|
47 |
+
scaled_values = scaler.fit_transform(values)
|
48 |
+
|
49 |
+
time_step = 30
|
50 |
+
X, y = create_dataset(scaled_values, time_step)
|
51 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
|
52 |
+
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], X_train.shape[2])
|
53 |
+
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2])
|
54 |
+
|
55 |
+
model = Sequential()
|
56 |
+
model.add(LSTM(256, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2])))
|
57 |
+
model.add(Dropout(0.3))
|
58 |
+
model.add(LSTM(128, return_sequences=True))
|
59 |
+
model.add(Dropout(0.3))
|
60 |
+
model.add(LSTM(64, return_sequences=False))
|
61 |
+
model.add(Dropout(0.3))
|
62 |
+
model.add(Dense(3))
|
63 |
+
model.compile(optimizer='adam', loss='mean_squared_error')
|
64 |
+
|
65 |
+
early_stopping = EarlyStopping(monitor='val_loss', patience=15)
|
66 |
+
model.fit(X_train, y_train, epochs=100, batch_size=82, validation_data=(X_test, y_test), callbacks=[early_stopping])
|
67 |
+
|
68 |
+
num_months_to_predict = 6
|
69 |
+
future_predictions = predict_future(model, scaled_values[-time_step:], time_step, num_months_to_predict)
|
70 |
+
future_predictions_rescaled = scaler.inverse_transform(future_predictions)
|
71 |
+
|
72 |
+
monthly_eur = np.mean(future_predictions_rescaled[:, 0].reshape(-1, 30), axis=1)
|
73 |
+
monthly_gbp = np.mean(future_predictions_rescaled[:, 1].reshape(-1, 30), axis=1)
|
74 |
+
monthly_usd_rub = np.mean(future_predictions_rescaled[:, 2].reshape(-1, 30), axis=1)
|
75 |
+
|
76 |
+
start_date = pd.to_datetime("30.06.2024", dayfirst=True) # Начальная дата
|
77 |
+
date_range = pd.date_range(start=start_date, periods=len(monthly_eur), freq='ME')
|
78 |
+
|
79 |
+
plt.figure(figsize=(15, 10))
|
80 |
+
|
81 |
+
plt.subplot(3, 1, 1)
|
82 |
+
plt.plot(date_range, monthly_usd_rub, label='Курс Доллара к Рублю', color='red', marker='o')
|
83 |
+
plt.title('Прогноз курса доллара к Рублю на 6 месяцев')
|
84 |
+
plt.xlabel('Месяца')
|
85 |
+
plt.ylabel('Цена Доллара в Рублях')
|
86 |
+
plt.legend()
|
87 |
+
|
88 |
+
plt.subplot(3, 1, 2)
|
89 |
+
plt.plot(date_range, monthly_eur, label='Курс Евро к Рублю', color='blue', marker='o')
|
90 |
+
plt.title('Прогноз курса Евро к Рублю на 6 месяцев')
|
91 |
+
plt.xlabel('Месяца')
|
92 |
+
plt.ylabel('Цена Евро в Рублях')
|
93 |
+
plt.legend()
|
94 |
+
|
95 |
+
plt.subplot(3, 1, 3)
|
96 |
+
plt.plot(date_range, monthly_gbp, label='Курс Фунтов Стерлингов к Рублю', color='green', marker='o')
|
97 |
+
plt.title('Прогноз курс Фунтов Стерлингов к Рублю на 6 месяцев')
|
98 |
+
plt.xlabel('Месяца')
|
99 |
+
plt.ylabel('Цена Фунтов Стерлингов в Рублях')
|
100 |
+
plt.legend()
|
101 |
+
|
102 |
+
plt.tight_layout()
|
103 |
+
|
104 |
+
plot_file_path = "predictions.png"
|
105 |
+
plt.savefig(plot_file_path)
|
106 |
+
|
107 |
+
return plot_file_path
|
108 |
+
|
109 |
+
|
110 |
+
def get_currency_values(file, date_input):
|
111 |
+
data = pd.read_excel(file)
|
112 |
+
data.dropna(inplace=True)
|
113 |
+
|
114 |
+
data['Date'] = pd.to_datetime(data['Date'], dayfirst=True)
|
115 |
+
|
116 |
+
date = pd.to_datetime(date_input, dayfirst=True)
|
117 |
+
row = data[data['Date'] == date]
|
118 |
+
|
119 |
+
if not row.empty:
|
120 |
+
values = row[['EUR_RUB', 'GBP_RUB', 'USD_RUB']].values.flatten()
|
121 |
+
return f"На {date_input}: USD/RUB: {values[2]}, EUR/RUB: {values[0]}, GBP/RUB: {values[1]}"
|
122 |
+
else:
|
123 |
+
return f"Данные на {date_input} не найдены."
|
124 |
+
|
125 |
+
|
126 |
+
app1 = gr.Interface(
|
127 |
+
fn=get_currency_values,
|
128 |
+
inputs=[gr.File(label="Загрузите файл Excel"), gr.Text(label="Введите дату (дд.мм.гггг):")],
|
129 |
+
outputs=gr.Text(label="Результаты валют")
|
130 |
+
)
|
131 |
+
|
132 |
+
app2 = gr.Interface(
|
133 |
+
fn=generate_plots,
|
134 |
+
inputs=gr.File(label="Загрузите файл Excel"),
|
135 |
+
outputs=gr.Image(type="filepath", label="Графики прогнозов"),
|
136 |
+
)
|
137 |
+
|
138 |
+
demo = gr.TabbedInterface([app1, app2], ["Вывод цены за дату", "Предсказания на 6 месяцев"])
|
139 |
demo.launch()
|