Anushree2000 commited on
Commit
80d8569
Β·
verified Β·
1 Parent(s): 1b44a2c

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +345 -0
app.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ st.set_page_config(page_title="E-Commerce Pricing Optimization", layout="wide")
2
+ !pip install -r requirements.txt
3
+
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ # Set random seed for reproducibility
9
+ np.random.seed(42)
10
+
11
+ # Generate synthetic data for an e-commerce store
12
+ num_products = 100 # Number of products
13
+
14
+ # Product categories
15
+ categories = ["Electronics", "Clothing", "Home & Kitchen", "Beauty", "Sports"]
16
+ product_names = [f"Product_{i+1}" for i in range(num_products)]
17
+ category_data = np.random.choice(categories, num_products)
18
+
19
+ # Base price range per category
20
+ price_ranges = {
21
+ "Electronics": (50, 500),
22
+ "Clothing": (10, 100),
23
+ "Home & Kitchen": (20, 300),
24
+ "Beauty": (5, 50),
25
+ "Sports": (15, 200),
26
+ }
27
+
28
+ # Generate base prices based on category
29
+ base_prices = [np.random.uniform(*price_ranges[cat]) for cat in category_data]
30
+
31
+ # Competitor pricing (fluctuating around base price)
32
+ competitor_prices = [price * np.random.uniform(0.9, 1.1) for price in base_prices]
33
+
34
+ # Seasonal demand factor (scale between 0.5 and 1.5)
35
+ seasonality = np.random.uniform(0.5, 1.5, num_products)
36
+
37
+ # Customer demand (influenced by price and seasonality)
38
+ demand = [(200 / price) * season * np.random.uniform(0.8, 1.2) for price, season in zip(base_prices, seasonality)]
39
+
40
+ # Assemble dataset
41
+ ecommerce_data = pd.DataFrame({
42
+ "Product": product_names,
43
+ "Category": category_data,
44
+ "Base_Price": base_prices,
45
+ "Competitor_Price": competitor_prices,
46
+ "Seasonality_Factor": seasonality,
47
+ "Demand": demand
48
+ })
49
+
50
+ # Display the first few rows of the dataset
51
+ ecommerce_data.head()
52
+
53
+
54
+ import matplotlib.pyplot as plt
55
+ import seaborn as sns
56
+
57
+ # Set Seaborn style
58
+ sns.set_style("whitegrid")
59
+
60
+ # Create subplots
61
+ fig, axes = plt.subplots(2, 2, figsize=(14, 10))
62
+
63
+ # 1. Price Distribution Across Categories
64
+ sns.boxplot(x="Category", y="Base_Price", data=ecommerce_data, ax=axes[0, 0], palette="Set2")
65
+ axes[0, 0].set_title("Price Distribution Across Categories")
66
+ axes[0, 0].set_xlabel("Category")
67
+ axes[0, 0].set_ylabel("Base Price")
68
+ axes[0, 0].tick_params(axis='x', rotation=30)
69
+
70
+ # 2. Competitor Price vs. Base Price
71
+ sns.scatterplot(x="Base_Price", y="Competitor_Price", data=ecommerce_data, ax=axes[0, 1], color="blue", alpha=0.7)
72
+ axes[0, 1].set_title("Competitor Price vs. Base Price")
73
+ axes[0, 1].set_xlabel("Base Price")
74
+ axes[0, 1].set_ylabel("Competitor Price")
75
+
76
+ # 3. Seasonality Impact on Demand
77
+ sns.scatterplot(x="Seasonality_Factor", y="Demand", data=ecommerce_data, ax=axes[1, 0], color="green", alpha=0.7)
78
+ axes[1, 0].set_title("Seasonality Impact on Demand")
79
+ axes[1, 0].set_xlabel("Seasonality Factor")
80
+ axes[1, 0].set_ylabel("Demand")
81
+
82
+ # 4. Price vs. Demand Relationship
83
+ sns.scatterplot(x="Base_Price", y="Demand", data=ecommerce_data, ax=axes[1, 1], color="red", alpha=0.7)
84
+ axes[1, 1].set_title("Price vs. Demand Relationship")
85
+ axes[1, 1].set_xlabel("Base Price")
86
+ axes[1, 1].set_ylabel("Demand")
87
+
88
+ # Adjust layout and show plot
89
+ plt.tight_layout()
90
+ plt.show()
91
+
92
+
93
+ import streamlit as st
94
+ import pandas as pd
95
+ import matplotlib.pyplot as plt
96
+ import seaborn as sns
97
+
98
+ # Load the synthetic dataset (Replace this with actual dataset loading)
99
+ @st.cache_data
100
+ def load_data():
101
+ return ecommerce_data # Use the generated dataset from previous steps
102
+
103
+ data = load_data()
104
+
105
+ # Streamlit UI Configuration
106
+
107
+ # Sidebar Navigation
108
+ st.sidebar.title("Navigation")
109
+ page = st.sidebar.selectbox("Choose a Page", ["Introduction", "Visualizations", "Solution Implementation"])
110
+
111
+ if page == "Introduction":
112
+ st.title("E-Commerce Pricing Optimization")
113
+ st.write("""
114
+ **Business Problem:**
115
+ - E-commerce companies struggle to set optimal prices that maximize revenue while staying competitive.
116
+ - Prices need to adjust dynamically based on demand, competitor pricing, and seasonal trends.
117
+
118
+ **Solution Approach:**
119
+ - Use **Multi-Armed Bandits** for adaptive pricing strategy.
120
+ - Apply **Bayesian Networks** to predict customer demand based on price.
121
+ - Use **Multi-Criteria Decision Making (AHP)** to decide the best price based on multiple factors.
122
+ """)
123
+
124
+ elif page == "Visualizations":
125
+ st.title("Data Visualizations")
126
+
127
+ # Plot 1: Price Distribution Across Categories
128
+ st.subheader("Price Distribution Across Categories")
129
+ fig, ax = plt.subplots()
130
+ sns.boxplot(x="Category", y="Base_Price", data=data, ax=ax, palette="Set2")
131
+ plt.xticks(rotation=30)
132
+ st.pyplot(fig)
133
+
134
+ # Plot 2: Competitor Price vs. Base Price
135
+ st.subheader("Competitor Price vs. Base Price")
136
+ fig, ax = plt.subplots()
137
+ sns.scatterplot(x="Base_Price", y="Competitor_Price", data=data, color="blue", alpha=0.7, ax=ax)
138
+ st.pyplot(fig)
139
+
140
+ # Plot 3: Seasonality Impact on Demand
141
+ st.subheader("Seasonality Impact on Demand")
142
+ fig, ax = plt.subplots()
143
+ sns.scatterplot(x="Seasonality_Factor", y="Demand", data=data, color="green", alpha=0.7, ax=ax)
144
+ st.pyplot(fig)
145
+
146
+ # Plot 4: Price vs. Demand Relationship
147
+ st.subheader("Price vs. Demand Relationship")
148
+ fig, ax = plt.subplots()
149
+ sns.scatterplot(x="Base_Price", y="Demand", data=data, color="red", alpha=0.7, ax=ax)
150
+ st.pyplot(fig)
151
+
152
+ elif page == "Solution Implementation":
153
+ st.title("Solution Implementation")
154
+ st.write("""
155
+ **Concepts Used:**
156
+ - **Multi-Armed Bandits**: To continuously optimize pricing strategy.
157
+ - **Bayesian Networks**: To model demand uncertainty based on price changes.
158
+ - **Multi-Criteria Decision Making (AHP)**: To balance revenue, demand, and competitiveness.
159
+
160
+ **Next Steps:**
161
+ - Implement these models and test them in a real-world simulation.
162
+ - Analyze results and fine-tune the pricing strategy dynamically.
163
+ """)
164
+
165
+
166
+ !pip install streamlit
167
+ !pip install pyngrok
168
+
169
+
170
+ %%writefile app.py
171
+ import streamlit as st
172
+
173
+ # Streamlit UI
174
+ st.title("Streamlit in Google Colab")
175
+ st.write("This is a test application running inside Google Colab using ngrok.")
176
+
177
+
178
+ !streamlit run app.py &>/dev/null &
179
+
180
+
181
+ !pip install pyngrok
182
+ from pyngrok import ngrok
183
+
184
+ # Set your authtoken
185
+ ngrok.set_auth_token("2uGfZ1H2caVAA1COFKWVy39k5yG_736rTtX96fqtuDL6Ej2e9") # Replace YOUR_AUTHTOKEN with your actual authtoken
186
+
187
+ # Kill any running process on port 8501 (optional)
188
+ !kill -9 $(lsof -t -i:8501)
189
+
190
+ # Start ngrok tunnel
191
+ # The port is defined in the addr argument
192
+ public_url = ngrok.connect(addr="8501")
193
+ print("Access Streamlit at:", public_url)
194
+
195
+ !pip install streamlit pyngrok
196
+
197
+
198
+ !kill -9 $(lsof -t -i:8501)
199
+
200
+
201
+ %%writefile app.py
202
+ import streamlit as st
203
+ import matplotlib.pyplot as plt
204
+ import numpy as np
205
+ from sklearn.linear_model import LinearRegression
206
+ from sklearn.cluster import KMeans
207
+ import pandas as pd
208
+
209
+ # App Title
210
+ st.title("Business Performance Analysis")
211
+
212
+ # Sidebar Navigation
213
+ st.sidebar.header("Navigation")
214
+ page = st.sidebar.selectbox("Select a Page", ["Introduction", "Visualizations", "Solution", "Forecasting", "Customer Segmentation", "Expense Optimization", "Goal Tracker"])
215
+
216
+ # Page 1: Introduction
217
+ if page == "Introduction":
218
+ st.header("πŸ“Œ Introduction")
219
+ st.markdown("""
220
+ ## Understanding the Business Problem
221
+ Businesses today face significant challenges in optimizing **profitability, reducing costs, and maximizing customer value**.
222
+ Here are three key business issues:
223
+
224
+ 1️⃣ **Revenue and Profitability Issues**
225
+ - Unpredictable revenue impacts long-term growth.
226
+ - High operational costs reduce net profit margins.
227
+
228
+ 2️⃣ **Customer Retention & Engagement**
229
+ - Businesses struggle to understand customer behavior.
230
+ - Acquiring new customers is costlier than retaining existing ones.
231
+
232
+ 3️⃣ **Data-Driven Decision Making**
233
+ - Many businesses lack real-time insights.
234
+ - Without proper data analysis, decisions are based on intuition rather than facts.
235
+
236
+ ### πŸ” Our Key Approaches
237
+ - **Revenue & Cost Analysis**
238
+ - **Data Visualization for Business Insights**
239
+ - **Strategic Business Solutions**
240
+ - **Forecasting Future Trends**
241
+ - **Competitor Benchmarking**
242
+ - **Customer Segmentation**
243
+ - **Expense Optimization**
244
+ - **Goal Tracking & Business Strategy**
245
+ """)
246
+
247
+ # Page 2: Visualizations
248
+ elif page == "Visualizations":
249
+ st.header("πŸ“Š Business Data Visualizations")
250
+ st.subheader("πŸ“ˆ Revenue vs Costs")
251
+ revenue = st.sidebar.number_input("Monthly Revenue ($)", min_value=0, value=10000)
252
+ costs = st.sidebar.number_input("Monthly Costs ($)", min_value=0, value=5000)
253
+ fig, ax = plt.subplots()
254
+ ax.bar(["Revenue", "Costs"], [revenue, costs], color=['green', 'red'])
255
+ st.pyplot(fig)
256
+
257
+
258
+
259
+ # Page 3: Solution
260
+ elif page == "Solution":
261
+ st.header("πŸ“ˆ Business Solution & Insights")
262
+ st.subheader("πŸ“Š Key Business Metrics")
263
+ # Define revenue and costs globally so they can be accessed on multiple pages
264
+ revenues = st.sidebar.number_input("Monthly Revenue ($)", min_value=0, value=10000)
265
+ costs = st.sidebar.number_input("Monthly Costs ($)", min_value=0, value=5000)
266
+
267
+ # Calculate profit using global revenue and costs
268
+ profit = revenues - costs
269
+
270
+ # Display the result
271
+ st.metric(label="Total Profit ($)", value=f"${profit:,.2f}")
272
+
273
+
274
+ # Page 4: Forecasting
275
+ elif page == "Forecasting":
276
+ st.header("πŸ“ˆ Future Revenue Prediction")
277
+ months = np.array([1, 2, 3, 4, 5, 6]).reshape(-1, 1)
278
+ revenue_data = np.array([8000, 8500, 9000, 9400, 10000, 10500])
279
+ model = LinearRegression()
280
+ model.fit(months, revenue_data)
281
+ future_months = np.array([7, 8, 9]).reshape(-1, 1)
282
+ predicted_revenue = model.predict(future_months)
283
+ st.line_chart(np.append(revenue_data, predicted_revenue))
284
+
285
+ # Page 5: Customer Segmentation
286
+ elif page == "Customer Segmentation":
287
+ st.header("πŸ›’ Customer Segmentation")
288
+ customer_data = pd.DataFrame({
289
+ 'revenue': [200, 500, 800, 1200, 1500, 300],
290
+ 'purchases': [2, 5, 8, 12, 15, 3]
291
+ })
292
+ kmeans = KMeans(n_clusters=3)
293
+ customer_data['segment'] = kmeans.fit_predict(customer_data)
294
+ st.scatter_chart(customer_data, x='revenue', y='purchases', color='segment')
295
+
296
+ # Page 6: Expense Optimization
297
+ elif page == "Expense Optimization":
298
+ st.header("πŸ’° Expense Optimization")
299
+ expense_categories = ["Marketing", "Salaries", "Infrastructure", "Miscellaneous"]
300
+ expenses = [3000, 5000, 2000, 1000]
301
+ fig, ax = plt.subplots()
302
+ ax.pie(expenses, labels=expense_categories, autopct='%1.1f%%', startangle=140)
303
+ st.pyplot(fig)
304
+
305
+ # Page 7: Goal Tracker
306
+ elif page == "Goal Tracker":
307
+ st.header("🎯 Business Goal Tracker")
308
+
309
+ # User inputs revenue goal
310
+ goal = st.number_input("Enter your revenue goal ($)", min_value=0)
311
+
312
+ # User inputs monthly revenue
313
+ revenue = st.sidebar.number_input("Monthly Revenue ($)", min_value=0, value=10000)
314
+
315
+ # Check if the goal is met
316
+ if goal < revenue:
317
+ st.warning("You have reached your revenue goal yet.")
318
+ else:
319
+ progress = (revenue / goal) * 100 if goal else 0
320
+ st.progress(progress / 100)
321
+ st.write(f"**Progress:** {progress:.2f}% of goal achieved")
322
+
323
+ !streamlit run app.py --server.port 8501 &>/dev/null &
324
+
325
+
326
+ from pyngrok import ngrok
327
+
328
+ # List all existing ngrok tunnels
329
+ tunnels = ngrok.get_tunnels()
330
+ # Check if there are any active tunnels before attempting to disconnect
331
+ if tunnels:
332
+ for tunnel in tunnels:
333
+ print("Disconnecting:", tunnel.public_url)
334
+ ngrok.disconnect(tunnel.public_url) # Disconnect each active tunnel
335
+ else:
336
+ print("No active tunnels found.")
337
+
338
+ # Start a new tunnel
339
+ public_url = ngrok.connect(addr="8501")
340
+ print("Access the Streamlit app at:", public_url)
341
+
342
+
343
+
344
+
345
+