chest / app.py
farid678's picture
Create app.py
245e228 verified
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import load_model
import requests
import gradio as gr
# Load your pre-trained model
model = load_model('eurusdModel2.h5') # Update with your model's path
# Function to fetch the latest EUR/USD price from Free Forex API
def get_live_price():
url = 'https://api.exchangerate-api.com/v4/latest/EUR' # Free API URL
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return data['rates']['USD'] # Get the USD rate for EUR
else:
print("Failed to retrieve data:", response.status_code)
return None
# Function to prepare input data for prediction
def prepare_input(scaled_data, today_price):
time_step = 60 # Time steps - must match training
last_prices = scaled_data[-(time_step - 1):] # Retrieve last `time_step - 1` prices
# Scale today's price
scaler = MinMaxScaler(feature_range=(0, 1))
today_scaled = scaler.fit_transform([[today_price]])
# Combine historical and today's price
input_data = np.concatenate((last_prices, today_scaled), axis=0)
input_data = input_data.reshape(1, input_data.shape[0], 1) # Reshape for LSTM input
return input_data, scaler
# Prediction function for Gradio
def predict_eur_usd():
today_price = get_live_price()
if today_price is None:
return "Failed to retrieve the current price."
# Load historical data
historical_data = pd.read_csv('EUR_USD Historical Data.csv', parse_dates=['Date'], index_col='Date')
historical_data = historical_data[['Price']]
# Normalize the historical data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(historical_data)
# Prepare input for prediction
input_data, scaler = prepare_input(scaled_data, today_price)
# Make prediction for tomorrow
predicted_price = model.predict(input_data)
predicted_price = scaler.inverse_transform(predicted_price) # Inverse scaling to get actual price
return f"Today's Price: {today_price:.4f}, Predicted EUR/USD Price for Tomorrow: {predicted_price[0][0]:.4f}"
# Create a Gradio interface
iface = gr.Interface(
fn=predict_eur_usd,
inputs=[],
outputs="text",
title="EUR/USD Price Predictor",
description="Fetches the latest EUR/USD price and predicts the price for tomorrow."
)
# Launch the Gradio app
iface.launch()