Rahma94/data_bender
0
1import streamlit as st2import pandas as pd3import numpy as np4import pickle5import matplotlib.pyplot as plt6from PIL import Image7from datetime import datetime, timedelta8from dateutil.relativedelta import relativedelta9 10# Load dataset11df = pd.read_csv('pro.csv')12 13# Convert the 1st column of the dataset into index14sales = df.set_index('Date')['Ship Quantity']15 16# Load model & scaler17with open('model.pkl', 'rb') as file1:18 model_lr = pickle.load(file1)19 20with open('scaler.pkl', 'rb') as file2:21 scaler = pickle.load(file2)22 23 24# Form for month input25 26def run():27 28 st.write('# Bend the Data')29 st.write('###### Enter the number of month and see how much product manufactured by then.')30 31 with st.form('forecastMonth'):32 month = st.number_input('Months (from December 2022)', min_value = 0, value = 4)33 34 # Submit button35 submitted = st.form_submit_button('Forecast') 36 37 # Function to predict38 def forecasting(month):39 sales_forecast = sales.copy()40 window = 441 for i in range(month):42 X = sales_forecast[-window:].values.reshape(1, -1)43 X_scaled = scaler.transform(X)44 45 last_month_str = sales_forecast.index[-1]46 last_month = datetime.strptime(last_month_str, '%y-%m')47 48 # Increment the month, handling overflow49 new_month = last_month + relativedelta(months=1) # Increment by 1 month50 51 # Predict and round the sales value52 predicted_sales = round(model_lr.predict(X_scaled)[0])53 54 # Add a new row with the predicted sales and the new index55 new_row = pd.Series([predicted_sales], index=[new_month.strftime('%y-%m')], name='sales')56 sales_forecast = sales_forecast._append(new_row)57 58 # Create a DateTime index using the 'Date' column59 sales_forecast.index = pd.to_datetime(sales_forecast.index, format='%y-%m')60 61 # Drop the 'Date' column62 sales_forecast = sales_forecast.drop(columns=['Date'])63 64 return sales_forecast65 66 # If submit button is pressed67 if submitted:68 fig = plt.figure(figsize=(20,5))69 sales_forecast = forecasting(month)70 sales_forecast.index = sales_forecast.index.strftime('%y-%m') # Convert Periods to strings71 sales_forecast.plot(color='blue', label='forecast', figsize=(20, 5))72 73 # Convert PeriodIndex to strings74 sales.index = sales.index.astype(str)75 sales.plot(color='red', label='real')76 77 plt.legend()78 plt.show()79 st.pyplot(fig)80 81 st.write(sales_forecast)82 83if __name__ == '__main__':84 run()85 