FKBaffour/Streamlit_App_for_Sales_Forecasting
4
1# Importing required Libraries2import streamlit as st3import pandas as pd4import numpy as np5import os, pickle6from sklearn import preprocessing7 8# Setting up page configuration and directory path9st.set_page_config(page_title="Sales Forecasting App", page_icon="🐞", layout="centered")10DIRPATH = os.path.dirname(os.path.realpath(__file__))11 12# Setting background image13import base6414def add_bg_from_local(image_file):15 with open(image_file, "rb") as image_file:16 encoded_string = base64.b64encode(image_file.read())17 st.markdown(18 f"""19 <style>20 .stApp {{21 background-image: url(data:{"jpg"};base64,{encoded_string.decode()});22 background-size: cover23 }}24 </style>25 """,26 unsafe_allow_html=True27 )28add_bg_from_local('background.jpg')29 30# Setting up logo31left1, mid, right1 = st.columns(3)32with mid:33 st.image("logo.jpg", use_column_width=True)34 35# Setting up Sidebar36social_acc = ['Data Field Description', 'EDA', 'About App']37social_acc_nav = st.sidebar.radio('**INFORMATION SECTION**', social_acc)38 39if social_acc_nav == 'Data Field Description':40 st.sidebar.markdown("<h2 style='text-align: center;'> Data Field Description </h2> ", unsafe_allow_html=True)41 st.sidebar.markdown("**Date:** The date you want to predict sales for")42 st.sidebar.markdown("**Family:** identifies the type of product sold")43 st.sidebar.markdown("**Onpromotion:** gives the total number of items in a product family that are being promoted at a store at a given date")44 st.sidebar.markdown("**Store Number:** identifies the store at which the products are sold")45 st.sidebar.markdown("**Holiday Locale:** provide information about the locale where holiday is celebrated")46 47elif social_acc_nav == 'EDA':48 st.sidebar.markdown("<h2 style='text-align: center;'> Exploratory Data Analysis </h2> ", unsafe_allow_html=True)49 st.sidebar.markdown('''---''')50 st.sidebar.markdown('''The exploratory data analysis of this project can be find in a Jupyter notebook from the linl below''')51 st.sidebar.markdown("[Open Notebook](https://github.com/Kyei-frank/Regression-Project-Store-Sales--Time-Series-Forecasting/blob/main/project_workflow.ipynb)")52 53elif social_acc_nav == 'About App':54 st.sidebar.markdown("<h2 style='text-align: center;'> Sales Forecasting App </h2> ", unsafe_allow_html=True)55 st.sidebar.markdown('''---''')56 st.sidebar.markdown("This App predicts the sales for product families sold at Favorita stores using regression model.")57 st.sidebar.markdown("")58 st.sidebar.markdown("[ Visit Github Repository for more information](https://github.com/Kyei-frank/Regression-Project-Store-Sales--Time-Series-Forecasting)")59 60# Loading Machine Learning Objects61@st.cache()62def load_saved_objects(file_path = 'ML_items'):63 # Function to load saved objects64 with open('ML_items', 'rb') as file:65 loaded_object = pickle.load(file)66 67 return loaded_object68 69# Instantiating ML_items70Loaded_object = load_saved_objects(file_path = 'ML_items')71pipeline, train_data, stores, holidays_event = Loaded_object['pipeline'], Loaded_object['train_data'], Loaded_object['stores'], Loaded_object['holidays_event']72 73# Setting Function for extracting Calendar features74@st.cache()75def getDateFeatures(df, date):76 df['date'] = pd.to_datetime(df['date'])77 df['month'] = df.date.dt.month78 df['day_of_month'] = df.date.dt.day79 df['day_of_year'] = df.date.dt.dayofyear80 df['week_of_year'] = df.date.dt.isocalendar().week81 df['day_of_week'] = df.date.dt.dayofweek82 df['year'] = df.date.dt.year83 df['is_weekend']= np.where(df['day_of_week'] > 4, 1, 0)84 df['is_month_start']= df.date.dt.is_month_start.astype(int)85 df['is_month_end']= df.date.dt.is_month_end.astype(int)86 df['quarter']= df.date.dt.quarter87 df['is_quarter_start']= df.date.dt.is_quarter_start.astype(int)88 df['is_quarter_end']= df.date.dt.is_quarter_end.astype(int)89 df['is_year_start']= df.date.dt.is_year_start.astype(int)90 91 return df92 93# Setting up variables for input data94@st.cache()95def setup(tmp_df_file):96 "Setup the required elements like files, models, global variables, etc"97 pd.DataFrame(98 dict(99 date=[],100 store_nbr=[],101 family=[],102 onpromotion=[],103 city=[],104 state=[],105 store_type=[],106 cluster=[],107 day_type=[],108 locale=[],109 locale_name=[],110 )111 ).to_csv(tmp_df_file, index=False)112 113# Setting up a file to save our input data114tmp_df_file = os.path.join(DIRPATH, "tmp", "data.csv")115setup(tmp_df_file)116 117# setting Title for forms118st.markdown("<h2 style='text-align: center;'> Sales Prediction </h2> ", unsafe_allow_html=True)119st.markdown("<h7 style='text-align: center;'> Fill in the details below and click on SUBMIT button to make a prediction for a specific date and item </h7> ", unsafe_allow_html=True)120 121# Creating columns for for input data(forms)122left_col, mid_col, right_col = st.columns(3)123 124# Developing forms to collect input data125with st.form(key="information", clear_on_submit=True):126 127 # Setting up input data for 1st column128 left_col.markdown("**PRODUCT DATA**")129 date = left_col.date_input("Prediction Date:")130 family = left_col.selectbox("Item family:", options= list(train_data["family"].unique()))131 onpromotion = left_col.selectbox("Onpromotion code:", options= set(train_data["onpromotion"].unique()))132 store_nbr = left_col.selectbox("Store Number:", options= set(stores["store_nbr"].unique()))133 134 # Setting up input data for 2nd column135 mid_col.markdown("**STORE DATA**")136 city = mid_col.selectbox("City:", options= set(stores["city"].unique()))137 state = mid_col.selectbox("State:", options= list(stores["state"].unique()))138 cluster = mid_col.selectbox("Store Cluster:", options= list(stores["cluster"].unique()))139 store_type = mid_col.radio("Store Type:", options= set(stores["store_type"].unique()), horizontal = True)140 141 # Setting up input data for 3rd column142 right_col.markdown("**ADDITIONAL DATA**")143 check= right_col.checkbox("Is it a Holiday or weekend?")144 if check:145 right_col.write('Fill the following information on Day Type')146 day_type = right_col.selectbox("Holiday:", options= ('Holiday','Special Day:Transfered/Additional Holiday','No Work/Weekend'))147 locale= right_col.selectbox("Holiday Locale:", options= list(holidays_event["locale"].unique()))148 locale_name= right_col.selectbox("Locale Name:", options= list(holidays_event["locale_name"].unique()))149 else:150 day_type = 'Workday'151 locale = 'National'152 locale_name= 'Ecuador'153 154 submitted = st.form_submit_button(label="Submit")155 156# Setting up background operations after submitting forms157if submitted:158 # Saving input data as csv file after submission159 pd.read_csv(tmp_df_file).append(160 dict(161 date = date,162 store_nbr = store_nbr,163 family=family,164 onpromotion= onpromotion,165 city=city,166 state=state,167 store_type=store_type,168 cluster=cluster,169 day_type=day_type,170 locale=locale,171 locale_name=locale_name172 ),173 ignore_index=True,174 ).to_csv(tmp_df_file, index=False)175 st.balloons()176 177 # Converting input data to a dataframe for prediction178 df = pd.read_csv(tmp_df_file)179 df= df.copy()180 181 # Getting date Features182 processed_data= getDateFeatures(df, 'date')183 processed_data= processed_data.drop(columns=['date'])184 185 # Making predictions186 prediction = pipeline.predict(processed_data)187 df['Sales']= prediction 188 189 # Displaying prediction results190 st.markdown('''---''')191 st.markdown("<h4 style='text-align: center;'> Prediction Results </h4> ", unsafe_allow_html=True)192 st.success(f"Predicted Sales: {prediction[-1]}")193 st.markdown('''---''')194 195 # Making expander to view all records196 expander = st.expander("See all records")197 with expander:198 df = pd.read_csv(tmp_df_file)199 df['Sales']= prediction200 st.dataframe(df)201 