-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
186 lines (141 loc) · 4.89 KB
/
app.py
File metadata and controls
186 lines (141 loc) · 4.89 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from xgboost import XGBRegressor
from sklearn.model_selection import train_test_split
from statsmodels.tsa.holtwinters import ExponentialSmoothing
import streamlit as st
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from statsmodels.tsa.holtwinters import ExponentialSmoothing
st.set_page_config(page_title="Superstore Analytics", layout="wide")
st.title("📊 Superstore Data Science Project")
st.markdown("""
This web app demonstrates:
- Profit prediction using Machine Learning
- Sales forecasting using Time Series analysis
""")
# Load data
df = pd.read_csv("data/Sample - Superstore.csv", encoding="latin1")
df['Order Date'] = pd.to_datetime(df['Order Date'])
menu = st.sidebar.selectbox(
"Select Option",
["Dataset Preview", "Profit Prediction", "Sales Forecast"]
)
# ================= Dataset Preview =================
if menu == "Dataset Preview":
st.subheader("Dataset Preview")
st.dataframe(df.head(20))
# ================= Profit Prediction =================
elif menu == "Profit Prediction":
st.subheader("🔮 Profit Prediction")
df_model = df.copy()
df_model['Year'] = df_model['Order Date'].dt.year
df_model['Month'] = df_model['Order Date'].dt.month
X = pd.get_dummies(
df_model[['Sales', 'Quantity', 'Discount', 'Year', 'Month', 'Category', 'Region']],
drop_first=True
)
y = df_model['Profit']
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X, y)
sales = st.number_input("Sales", value=500.0)
quantity = st.number_input("Quantity", value=2)
discount = st.slider("Discount", 0.0, 0.5, 0.1)
input_df = pd.DataFrame({
"Sales": [sales],
"Quantity": [quantity],
"Discount": [discount],
"Year": [2025],
"Month": [1],
"Category_Technology": [1],
"Region_West": [1]
})
input_df = input_df.reindex(columns=X.columns, fill_value=0)
if st.button("Predict Profit"):
prediction = model.predict(input_df)[0]
st.success(f"💰 Predicted Profit: {prediction:.2f}")
# ================= Sales Forecast =================
elif menu == "Sales Forecast":
st.subheader("📈 Sales Forecast")
monthly_sales = (
df
.set_index('Order Date')
.resample('ME')['Sales']
.sum()
)
model = ExponentialSmoothing(
monthly_sales,
trend='add',
seasonal='add',
seasonal_periods=12
).fit()
forecast = model.forecast(6)
st.line_chart(pd.concat([monthly_sales, forecast]))
st.header("📂 Upload Your Dataset")
uploaded_file = st.file_uploader(
"Upload a CSV file (Sales data)",
type=["csv"]
)
if uploaded_file is not None:
df = pd.read_csv(uploaded_file, encoding="latin1")
st.subheader("Dataset Preview")
st.dataframe(df.head())
st.subheader("Select Columns")
date_col = st.selectbox("Select Date Column", df.columns)
sales_col = st.selectbox("Select Sales Column", df.columns)
profit_col = st.selectbox(
"Select Profit Column (optional)",
["None"] + list(df.columns)
)
df[date_col] = pd.to_datetime(df[date_col], errors="coerce")
df = df.dropna(subset=[date_col, sales_col])
df = df.sort_values(date_col)
monthly_sales = (
df
.set_index(date_col)
.resample("M")[sales_col]
.sum()
)
st.subheader("📈 Sales Forecast")
try:
model_ts = ExponentialSmoothing(
monthly_sales,
trend="add",
seasonal="add",
seasonal_periods=12
).fit()
forecast = model_ts.forecast(6)
fig, ax = plt.subplots()
ax.plot(monthly_sales, label="Actual Sales")
ax.plot(forecast, label="Forecast", linestyle="--")
ax.legend()
st.pyplot(fig)
except Exception as e:
st.error("Not enough data for forecasting.")
if profit_col != "None":
st.subheader("💰 Profit Prediction (XGBoost)")
df_ml = df.dropna(subset=[profit_col])
df_ml["Year"] = df_ml[date_col].dt.year
df_ml["Month"] = df_ml[date_col].dt.month
X = df_ml[[sales_col, "Year", "Month"]]
y = df_ml[profit_col]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = XGBRegressor(
n_estimators=300,
learning_rate=0.05,
max_depth=5,
random_state=42
)
model.fit(X_train, y_train)
sales_input = st.number_input("Enter Sales", value=float(X[sales_col].mean()))
input_df = pd.DataFrame({
sales_col: [sales_input],
"Year": [2025],
"Month": [1]
})
pred_profit = model.predict(input_df)[0]
st.success(f"Predicted Profit: {pred_profit:.2f}")