EdwinHB commited on
Commit
27b0e2e
·
verified ·
1 Parent(s): b160851

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +103 -0
main.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from prophet import Prophet
4
+ import matplotlib.pyplot as plt
5
+
6
+ def forecast_sales(file):
7
+ # Load the sales data
8
+ sales_data = pd.read_csv(file.name)
9
+
10
+ # Convert date column to datetime
11
+ sales_data['date'] = pd.to_datetime(sales_data['date'])
12
+
13
+ # Prepare the data for Prophet with additional regressors
14
+ prophet_data = sales_data[['date', 'sales', 'orders', 'goog_upper_spend', 'fb_upper', 'search_spend', 'brand_spend', 'shopping_spend', 'fb_spend', 'pinterest_spend', 'tiktok', 'RTB_Spend', 'venta_buen_fin', 'venta_hot_sale']].rename(columns={'date': 'ds', 'sales': 'y'})
15
+
16
+ # Fill missing values with the mean of the respective columns
17
+ prophet_data.fillna(prophet_data.mean(), inplace=True)
18
+
19
+ # Initialize the Prophet model with additional regressors
20
+ model = Prophet()
21
+
22
+ # Add additional regressors
23
+ regressors = ['orders', 'goog_upper_spend', 'fb_upper', 'search_spend', 'brand_spend', 'shopping_spend', 'fb_spend', 'pinterest_spend', 'tiktok', 'RTB_Spend', 'venta_buen_fin', 'venta_hot_sale']
24
+ for regressor in regressors:
25
+ model.add_regressor(regressor)
26
+
27
+ # Fit the model
28
+ model.fit(prophet_data)
29
+
30
+ # Create a dataframe for future dates with additional regressors
31
+ future = model.make_future_dataframe(periods=30)
32
+ future = future.merge(sales_data[['date'] + regressors].set_index('date'), left_on='ds', right_index=True, how='left')
33
+ future.fillna(future.mean(), inplace=True)
34
+
35
+ # Predict the future sales
36
+ forecast = model.predict(future)
37
+
38
+ # Plot the forecast
39
+ fig1, ax1 = plt.subplots()
40
+ model.plot(forecast, ax=ax1)
41
+ ax1.set_title('Sales Forecast with Additional Regressors')
42
+ ax1.set_xlabel('Date')
43
+ ax1.set_ylabel('Sales')
44
+
45
+ # Merge the forecasted sales with the actual sales data for comparison
46
+ comparison_df = pd.merge(forecast[['ds', 'yhat']], prophet_data, left_on='ds', right_on='ds', how='left')
47
+ comparison_df.rename(columns={'yhat': 'forecasted_sales', 'y': 'actual_sales'}, inplace=True)
48
+
49
+ # Resample the comparison dataframe to monthly frequency and calculate the mean sales for each month
50
+ monthly_comparison_df = comparison_df.resample('M', on='ds').mean()
51
+
52
+ # Filter the monthly comparison dataframe to show only the last 12 months
53
+ last_12_months_df = monthly_comparison_df.tail(12)
54
+
55
+ # Calculate the percentage difference between actual and forecasted sales for the last 12 months
56
+ last_12_months_df['percentage_difference'] = ((last_12_months_df['actual_sales'] - last_12_months_df['forecasted_sales']) / last_12_months_df['actual_sales']) * 100
57
+
58
+ # Drop rows with NaN values in 'actual_sales'
59
+ last_12_months_df = last_12_months_df.dropna(subset=['actual_sales'])
60
+
61
+ # Plot the monthly comparison with bar charts and the percentage difference on top
62
+ fig2, ax2 = plt.subplots(figsize=(14, 7))
63
+ bar_width = 15 # Set the bar width
64
+
65
+ # Plot actual sales bars
66
+ bars_actual = ax2.bar(last_12_months_df.index, last_12_months_df['actual_sales'],
67
+ width=bar_width, label='Actual Sales', color='black', alpha=0.7)
68
+
69
+ # Plot forecasted sales bars
70
+ bars_forecasted = ax2.bar(last_12_months_df.index + pd.DateOffset(days=15),
71
+ last_12_months_df['forecasted_sales'], width=bar_width,
72
+ label='Forecasted Sales', color='blue', alpha=0.7)
73
+
74
+ # Add the percentage difference on top of the bars
75
+ for bar, diff in zip(bars_actual, last_12_months_df['percentage_difference']):
76
+ height = bar.get_height()
77
+ ax2.text(bar.get_x() + bar.get_width() / 2.0, height, f'{diff:.2f}%', ha='center', va='bottom', color='red')
78
+
79
+ ax2.set_title('Monthly Actual vs Forecasted Sales with Percentage Difference (Last 12 Months)')
80
+ ax2.set_xlabel('Date')
81
+ ax2.set_ylabel('Sales')
82
+ ax2.legend()
83
+
84
+ # Save the comparison dataframe to a CSV
85
+ last_12_months_df.to_csv('forecast_comparison.csv')
86
+
87
+ return fig1, fig2, 'forecast_comparison.csv'
88
+
89
+ # Define the Gradio interface
90
+ interface = gr.Interface(
91
+ fn=forecast_sales,
92
+ inputs=gr.File(label="Upload CSV File"),
93
+ outputs=[
94
+ gr.Plot(label="Sales Forecast"),
95
+ gr.Plot(label="Monthly Comparison"),
96
+ gr.File(label="Comparison CSV")
97
+ ],
98
+ title="Sales Forecasting with Prophet",
99
+ description="Upload a CSV file with sales data to forecast future sales and compare with actual sales."
100
+ )
101
+
102
+ # Launch the interface
103
+ interface.launch(debug=True)