import pandas as pd import numpy as np import tensorflow as tf import random import matplotlib.pyplot as plt import gradio as gr from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout from tensorflow.keras.callbacks import EarlyStopping def create_dataset(data, time_step=1): X, y = [], [] for i in range(len(data) - time_step - 1): a = data[i:(i + time_step), :] X.append(a) y.append(data[i + time_step, :]) return np.array(X), np.array(y) def predict_future(model, initial_data, time_step, num_months): predictions = [] current_data = initial_data[-time_step:] for _ in range(num_months * 30): current_data_reshaped = current_data.reshape(1, time_step, current_data.shape[1]) next_prediction = model.predict(current_data_reshaped) predictions.append(next_prediction[0]) current_data = np.append(current_data[1:], next_prediction, axis=0) return np.array(predictions) def generate_plots(file): seed = 65 tf.random.set_seed(seed) np.random.seed(seed) random.seed(seed) # Чтение данных из Excel файла data = pd.read_excel(file) data.dropna(inplace=True) data = data[['EUR_RUB', 'GBP_RUB', 'USD_RUB']] values = data.values scaler = MinMaxScaler() scaled_values = scaler.fit_transform(values) time_step = 30 X, y = create_dataset(scaled_values, time_step) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], X_train.shape[2]) X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2]) model = Sequential() model.add(LSTM(256, return_sequences=True, input_shape=(X_train.shape[1], X_train.shape[2]))) model.add(Dropout(0.3)) model.add(LSTM(128, return_sequences=True)) model.add(Dropout(0.3)) model.add(LSTM(64, return_sequences=False)) model.add(Dropout(0.3)) model.add(Dense(3)) model.compile(optimizer='adam', loss='mean_squared_error') early_stopping = EarlyStopping(monitor='val_loss', patience=15) model.fit(X_train, y_train, epochs=100, batch_size=82, validation_data=(X_test, y_test), callbacks=[early_stopping]) num_months_to_predict = 6 future_predictions = predict_future(model, scaled_values[-time_step:], time_step, num_months_to_predict) future_predictions_rescaled = scaler.inverse_transform(future_predictions) monthly_eur = np.mean(future_predictions_rescaled[:, 0].reshape(-1, 30), axis=1) monthly_gbp = np.mean(future_predictions_rescaled[:, 1].reshape(-1, 30), axis=1) monthly_usd_rub = np.mean(future_predictions_rescaled[:, 2].reshape(-1, 30), axis=1) start_date = pd.to_datetime("30.06.2024", dayfirst=True) # Начальная дата date_range = pd.date_range(start=start_date, periods=len(monthly_eur), freq='ME') plt.figure(figsize=(15, 10)) plt.subplot(3, 1, 1) plt.plot(date_range, monthly_usd_rub, label='Курс Доллара к Рублю', color='red', marker='o') plt.title('Прогноз курса доллара к Рублю на 6 месяцев') plt.xlabel('Месяца') plt.ylabel('Цена Доллара в Рублях') plt.legend() plt.subplot(3, 1, 2) plt.plot(date_range, monthly_eur, label='Курс Евро к Рублю', color='blue', marker='o') plt.title('Прогноз курса Евро к Рублю на 6 месяцев') plt.xlabel('Месяца') plt.ylabel('Цена Евро в Рублях') plt.legend() plt.subplot(3, 1, 3) plt.plot(date_range, monthly_gbp, label='Курс Фунтов Стерлингов к Рублю', color='green', marker='o') plt.title('Прогноз курс Фунтов Стерлингов к Рублю на 6 месяцев') plt.xlabel('Месяца') plt.ylabel('Цена Фунтов Стерлингов в Рублях') plt.legend() plt.tight_layout() plot_file_path = "predictions.png" plt.savefig(plot_file_path) return plot_file_path def get_currency_values(file, date_input): data = pd.read_excel(file) data.dropna(inplace=True) data['Date'] = pd.to_datetime(data['Date'], dayfirst=True) date = pd.to_datetime(date_input, dayfirst=True) row = data[data['Date'] == date] if not row.empty: values = row[['EUR_RUB', 'GBP_RUB', 'USD_RUB']].values.flatten() return f"На {date_input}: USD/RUB: {values[2]}, EUR/RUB: {values[0]}, GBP/RUB: {values[1]}" else: return f"Данные на {date_input} не найдены." app1 = gr.Interface( fn=get_currency_values, inputs=[gr.File(label="Загрузите файл Excel"), gr.Text(label="Введите дату (дд.мм.гггг):")], outputs=gr.Text(label="Результаты валют") ) app2 = gr.Interface( fn=generate_plots, inputs=gr.File(label="Загрузите файл Excel"), outputs=gr.Image(type="filepath", label="Графики прогнозов"), ) demo = gr.TabbedInterface([app1, app2], ["Вывод цены за дату", "Предсказания на 6 месяцев"]) demo.launch()