File size: 4,863 Bytes
b0e7b5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# external libraries
import streamlit as st
import pandas as pd
import numpy as np
import os
import datetime

from config import Config

config = vars(Config)

def main():

    # variables
    if "state" not in st.session_state:
        st.session_state["state"] = True
        st.session_state["predictions_df"] = pd.DataFrame()

    st.set_page_config(
        layout="centered",  # Can be "centered" or "wide". In the future also "dashboard", etc.
        initial_sidebar_state="auto",  # Can be "auto", "expanded", "collapsed"
        page_title=config['MAIN_TITLE'],  # String or None. Strings get appended with "• Streamlit". 
        page_icon=config['ICON_PATH'],  # String, anything supported by st.image, or None.
    )

    col1, col2, col3 = st.columns(3)
    col1.write(' ')
    col2.image(config['ICON_PATH'])
    col3.write(' ')

    st.markdown(f"<h1 style='text-align: center;'>{config['MAIN_TITLE']}</h1>", unsafe_allow_html=True)
    st.markdown(f"<h3 style='text-align: center;'>{config['SUB_TITLE']}</h3>", unsafe_allow_html=True)

    if st.session_state["state"]:

        dates = get_forecasting_horizon(config['FORECAST_START_DATE'],config['FORECAST_END_DATE'])
    
        col1, col2= st.columns([100,1])
        input_date = col1.slider(
        "Forecast Interval", dates[0].date(), dates[-1].date(),
        value=(dates[0].date(),dates[0].date() + datetime.timedelta(weeks=12)),
        step=datetime.timedelta(weeks=4))

        col1, col2, col3 , col4, col5 = st.columns(5)
        with col3 :
            center_button = st.button(config['FORECAST_BUTTON_TEXT'], on_click=predict, args=(input_date,))


        if not st.session_state["predictions_df"].empty:

            pid = st.selectbox(config['LINE_PLOT_SELECTBOX_TEXT'],st.session_state["predictions_df"]['product_id'].unique())

            st.table(st.session_state["predictions_df"].loc[st.session_state["predictions_df"]['product_id'] == pid,['product_id','date','demand']][:10])

            st.write(f"Monthly demand for the product {pid}")
            st.line_chart(st.session_state["predictions_df"].loc[st.session_state["predictions_df"]['product_id'] == pid,:], 
                          x="date", y="demand", use_container_width=True)
            
            category = st.selectbox(config['BAR_PLOT_SELECTBOX_TEXT'],['product_application',
                                                                        'product_marketing_name',
                                                                        'product_main_family',
                                                                        'planning_method_latest'])

            st.write(f'Average demand by category "{category}"')
            st.bar_chart(st.session_state["predictions_df"].loc[st.session_state["predictions_df"]['product_id'] == pid,:].groupby(category)['demand'].mean())

            input_save = st.checkbox(config['SAVE_CHECKBOX_TEXT'])
            confirm_params = {
                    'input_save':input_save
            }

            confirm = st.button(config['SAVE_BUTTON_TEXT'], on_click=save, args=(confirm_params,))
            if confirm:
                st.success(config['SAVE_BUTTON_SUCCESS_TEXT'])

            



def get_forecasting_horizon(start_date, end_date):
    horizon = pd.date_range(start_date,
                            end_date, 
                            freq='MS')
    return horizon

# saving results
def save(params):

    dir = 'demand_predictions'
    if not os.path.exists(f'{dir}'):
        os.makedirs(f'{dir}')

    if params['input_save']:
        today = datetime.datetime.today().strftime("%d-%m-%Y")
        st.session_state["predictions_df"].to_excel(f'{dir}/predictions_{today}.xlsx', index=False)


# forecasting
def predict(input_date):

    data = {
        'product_id': [f'P{1}' for i in range(5)],
        'date':['2022-01-01','2022-02-01','2022-03-01','2022-04-01','2022-05-01'],
        'demand': np.random.randint(1, 100, size=5),
        'product_application': ['A','A','A','B','B']
    }

    data2 = {
        'product_id': [f'P{2}' for i in range(5)],
        'date':['2022-01-01','2022-02-01','2022-03-01','2022-04-01','2022-05-01'],
        'demand': np.random.randint(1, 100, size=5),
        'product_application': ['A','A','A','B','B']
    }

    df1 = pd.DataFrame(data)
    df2 = pd.DataFrame(data2)

    # Concatenate the two DataFrames vertically
    combined_df = pd.concat([df1, df2], ignore_index=True)


    forecast_start_date = input_date[0].strftime("%Y-%m-%d")
    forecast_end_date = input_date[1].strftime("%Y-%m-%d")
    print(forecast_start_date, forecast_end_date)

    st.session_state["predictions_df"] = combined_df

if __name__ == "__main__":
    main()