handex commited on
Commit
1fd3f8d
Β·
verified Β·
1 Parent(s): 39960a6

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +75 -32
src/streamlit_app.py CHANGED
@@ -1,40 +1,83 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
 
 
 
 
 
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
 
 
 
 
 
 
 
 
18
 
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
 
 
 
 
 
 
 
 
 
 
22
 
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
 
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
 
5
+ # 1. Page Configuration
6
+ st.set_page_config(page_title="Store Sales Forecast", page_icon="πŸ›’", layout="wide")
 
 
 
 
7
 
8
+ # 2. Title and Description
9
+ st.title("πŸ›’ Store Sales Forecasting Dashboard")
10
+ st.markdown("""
11
+ This application visualizes the 16-day future sales predictions for retail stores in Ecuador.
12
+ The forecasts are generated using an **XGBoost** machine learning model trained on historical data,
13
+ incorporating features like seasonality, oil prices, and holidays.
14
+ """)
15
 
16
+ # 3. Load Data Function (Cached for performance)
17
+ @st.cache_data
18
+ def load_data():
19
+ # Load the CSV file we prepared earlier
20
+ df = pd.read_csv("dashboard_data.csv")
21
+
22
+ # Ensure date column is in datetime format
23
+ if 'date' in df.columns:
24
+ df['date'] = pd.to_datetime(df['date'])
25
+ return df
26
 
27
+ try:
28
+ df = load_data()
29
+
30
+ # --- SIDEBAR (FILTERS) ---
31
+ st.sidebar.header("Filter Options")
32
+
33
+ # Store Selector
34
+ if 'store_nbr' in df.columns:
35
+ store_list = sorted(df['store_nbr'].unique())
36
+ selected_store = st.sidebar.selectbox("Select Store Number", store_list)
37
+ else:
38
+ st.error("Column 'store_nbr' not found in dataset.")
39
+ st.stop()
40
 
41
+ # Family Selector
42
+ # Note: If you decoded labels back to text, this will show text.
43
+ # If not, it will show the encoded ID numbers.
44
+ if 'family' in df.columns:
45
+ family_list = sorted(df['family'].unique())
46
+ selected_family = st.sidebar.selectbox("Select Product Category (Family)", family_list)
47
+
48
+ # --- MAIN CONTENT ---
49
+
50
+ # Filter data based on user selection
51
+ filtered_data = df[(df['store_nbr'] == selected_store) & (df['family'] == selected_family)]
52
+
53
+ # Sort by date for proper plotting
54
+ if 'date' in filtered_data.columns:
55
+ filtered_data = filtered_data.sort_values('date')
56
+
57
+ # Plot Chart using Plotly
58
+ st.subheader(f"πŸ“… Forecast for Store #{selected_store} - Category: {selected_family}")
59
+
60
+ fig = px.line(filtered_data, x='date', y='Predicted_Sales',
61
+ title='16-Day Sales Prediction Trend',
62
+ labels={'Predicted_Sales': 'Predicted Sales Volume', 'date': 'Date'},
63
+ markers=True)
64
+
65
+ # Customize chart appearance
66
+ fig.update_layout(line_color='#00CC96', hovermode="x unified")
67
+ st.plotly_chart(fig, use_container_width=True)
68
+
69
+ # Show Data Table
70
+ with st.expander("View Detailed Forecast Data"):
71
+ st.dataframe(filtered_data[['id', 'date', 'store_nbr', 'family', 'Predicted_Sales']])
72
+
73
+ else:
74
+ st.warning("Date column is missing. Cannot plot the graph.")
75
 
76
+ except FileNotFoundError:
77
+ st.error("Error: 'dashboard_data.csv' not found. Please upload the file to Hugging Face Files.")
78
+ except Exception as e:
79
+ st.error(f"An unexpected error occurred: {e}")
 
 
80
 
81
+ # Footer / Credits
82
+ st.markdown("---")
83
+ st.markdown("Created with ❀️ using **Streamlit** and **XGBoost**.")