Rehman1603's picture
Update app.py
a83cfe4 verified
raw
history blame
6.67 kB
import gradio as gr
import pandas as pd
from prophet import Prophet
import plotly.graph_objs as go
import numpy as np
# Function to replace null values with average
def replace_null_with_avg_values(df, column_name):
df[column_name] = pd.to_numeric(df[column_name], errors='coerce')
avg_value = round(df[column_name].mean(), 1)
df[column_name].fillna(avg_value, inplace=True)
# Load and process the data
broiler_data = pd.read_csv('Broiler market price.csv')
replace_null_with_avg_values(broiler_data, 'DOC')
replace_null_with_avg_values(broiler_data, 'Farm Rate')
replace_null_with_avg_values(broiler_data, 'Open')
replace_null_with_avg_values(broiler_data, 'Close')
broiler_data['Date'] = pd.to_datetime(broiler_data['Date'])
# Prepare dataframes for Prophet models
farm_rate_df = broiler_data[['Date', 'Farm Rate', 'DOC']].rename(columns={'Date': 'ds', 'Farm Rate': 'y', 'DOC': 'DOC'})
open_rate_df = broiler_data[['Date', 'Open', 'DOC']].rename(columns={'Date': 'ds', 'Open': 'y', 'DOC': 'DOC'})
close_rate_df = broiler_data[['Date', 'Close', 'DOC']].rename(columns={'Date': 'ds', 'Close': 'y', 'DOC': 'DOC'})
# Initialize Prophet models
farm_rate_model = Prophet(growth='linear', yearly_seasonality=True, daily_seasonality=True)
open_rate_model = Prophet(growth='linear', yearly_seasonality=True, daily_seasonality=True)
close_rate_model = Prophet(growth='linear', yearly_seasonality=True, daily_seasonality=True)
# Add DOC regressor and holidays
farm_rate_model.add_regressor('DOC')
open_rate_model.add_regressor('DOC')
close_rate_model.add_regressor('DOC')
farm_rate_model.add_country_holidays(country_name='PAK')
open_rate_model.add_country_holidays(country_name='PAK')
close_rate_model.add_country_holidays(country_name='PAK')
# Fit the models
farm_rate_model.fit(farm_rate_df)
open_rate_model.fit(open_rate_df)
close_rate_model.fit(close_rate_df)
# Function to generate predictions based on DOC range and selected days
def predict_values(start_doc, end_doc, days_option):
# Generate future dataframes
farm_future_rate = farm_rate_model.make_future_dataframe(periods=days_option, freq='D')
open_future_rate = open_rate_model.make_future_dataframe(periods=days_option, freq='D')
close_future_rate = close_rate_model.make_future_dataframe(periods=days_option, freq='D')
# Generate DOC values within the specified range
doc_values = np.linspace(start_doc, end_doc, num=days_option) # Adjusted line
# Assign the generated DOC values to the future dataframes
farm_future_rate['DOC'] = doc_values
open_future_rate['DOC'] = doc_values
close_future_rate['DOC'] = doc_values
# Make predictions
farm_forecast_rate = farm_rate_model.predict(farm_future_rate)
open_forecast_rate = open_rate_model.predict(open_future_rate)
close_forecast_rate = close_rate_model.predict(close_future_rate)
# Filter to get only the future predictions (last `days_option` days)
farm_output = farm_forecast_rate[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(days_option).copy()
farm_output['DOC'] = farm_future_rate['DOC'].tail(days_option)
open_output = open_forecast_rate[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(days_option).copy()
open_output['DOC'] = open_future_rate['DOC'].tail(days_option)
close_output = close_forecast_rate[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(days_option).copy()
close_output['DOC'] = close_future_rate['DOC'].tail(days_option)
# Round float values to two decimal places
farm_output[['yhat', 'yhat_lower', 'yhat_upper']] = farm_output[['yhat', 'yhat_lower', 'yhat_upper']].round(2)
open_output[['yhat', 'yhat_lower', 'yhat_upper']] = open_output[['yhat', 'yhat_lower', 'yhat_upper']].round(2)
close_output[['yhat', 'yhat_lower', 'yhat_upper']] = close_output[['yhat', 'yhat_lower', 'yhat_upper']].round(2)
# Create Plotly graphs
fig_farm = go.Figure()
fig_farm.add_trace(go.Scatter(x=farm_forecast_rate['ds'], y=farm_forecast_rate['yhat'], mode='lines+markers', name='Farm Rate Prediction'))
fig_farm.update_layout(title='Farm Rate Predictions over Time', xaxis_title='Date', yaxis_title='Predicted Farm Rate')
fig_open = go.Figure()
fig_open.add_trace(go.Scatter(x=open_forecast_rate['ds'], y=open_forecast_rate['yhat'], mode='lines+markers', name='Open Rate Prediction'))
fig_open.update_layout(title='Open Rate Predictions over Time', xaxis_title='Date', yaxis_title='Predicted Open Rate')
fig_close = go.Figure()
fig_close.add_trace(go.Scatter(x=close_forecast_rate['ds'], y=close_forecast_rate['yhat'], mode='lines+markers', name='Close Rate Prediction'))
fig_close.update_layout(title='Close Rate Predictions over Time', xaxis_title='Date', yaxis_title='Predicted Close Rate')
return farm_output, open_output, close_output, fig_farm, fig_open, fig_close
# Define Gradio interface
def interface(start_doc, end_doc, days_option):
# Check if a valid selection is made
if days_option is None:
return "Please select a valid option for days.", None, None, None, None, None
days_map = {'7 days': 7, '10 days': 10, '15 days': 15,'40 days':40}
days_selected = days_map.get(days_option, 7) # Default to 7 days if no valid option is provided
results_farm, results_open, results_close, plot_farm, plot_open, plot_close = predict_values(start_doc, end_doc, days_selected)
return results_farm, results_open, results_close, plot_farm, plot_open, plot_close
# Create Gradio inputs and outputs
start_doc_input = gr.components.Number(label="Start DOC Value")
end_doc_input = gr.components.Number(label="End DOC Value")
days_dropdown = gr.components.Dropdown(choices=['7 days', '10 days', '15 days','40 days'], label="Select Number of Days",value='7 days')
# Define output components
output_table_farm = gr.components.Dataframe(label="Predicted Farm Rate Values")
output_table_open = gr.components.Dataframe(label="Predicted Open Rate Values")
output_table_close = gr.components.Dataframe(label="Predicted Close Rate Values")
output_plot_farm = gr.components.Plot(label="Farm Rate Predictions")
output_plot_open = gr.components.Plot(label="Open Rate Predictions")
output_plot_close = gr.components.Plot(label="Close Rate Predictions")
# Set up Gradio interface
gr.Interface(
fn=interface,
inputs=[start_doc_input, end_doc_input, days_dropdown],
outputs=[output_table_farm, output_table_open, output_table_close, output_plot_farm, output_plot_open, output_plot_close],
title="Farm Rate Prediction Tool",
description="Enter DOC range and select the number of days to generate predictions and plot."
).launch(debug=True)