Spaces:
Sleeping
Sleeping
File size: 4,653 Bytes
a97cd9f |
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 |
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from datetime import datetime, timedelta
st.set_page_config(layout="wide", page_title="Business Analytics Dashboard Tutorial")
# Sample business data generation
def generate_sales_data():
dates = pd.date_range(start='2024-01-01', end='2024-12-31', freq='D')
np.random.seed(42)
df = pd.DataFrame({
'Date': dates,
'Sales': np.random.normal(1000, 200, len(dates)),
'Region': np.random.choice(['North', 'South', 'East', 'West'], len(dates)),
'Product': np.random.choice(['Electronics', 'Clothing', 'Food', 'Books'], len(dates)),
'Customer_Type': np.random.choice(['Retail', 'Wholesale'], len(dates)),
})
df['Profit'] = df['Sales'] * np.random.uniform(0.15, 0.25, len(df))
return df
# Main Navigation
st.title("📊 Business Analytics & Data Analysis Tutorial")
# Generate sample data
df_sales = generate_sales_data()
# Dashboard filters
col1, col2, col3 = st.columns(3)
with col1:
selected_region = st.multiselect(
"Select Region",
df_sales['Region'].unique(),
default=df_sales['Region'].unique()[0]
)
with col2:
date_range = st.date_input(
"Select Date Range",
value=(df_sales['Date'].min(), df_sales['Date'].max())
)
with col3:
product_type = st.selectbox(
"Select Product",
['All'] + list(df_sales['Product'].unique())
)
# Filter data based on selections
mask = (df_sales['Region'].isin(selected_region)) & \
(df_sales['Date'] >= pd.Timestamp(date_range[0])) & \
(df_sales['Date'] <= pd.Timestamp(date_range[1]))
if product_type != 'All':
mask &= (df_sales['Product'] == product_type)
filtered_df = df_sales[mask]
# KPI Metrics
st.subheader("Key Performance Indicators")
kpi1, kpi2, kpi3, kpi4 = st.columns(4)
with kpi1:
st.metric(
"Total Sales",
f"${filtered_df['Sales'].sum():,.0f}",
f"{((filtered_df['Sales'].sum() / df_sales['Sales'].sum()) - 1) * 100:.1f}%"
)
with kpi2:
st.metric(
"Average Daily Sales",
f"${filtered_df['Sales'].mean():,.0f}",
f"{((filtered_df['Sales'].mean() / df_sales['Sales'].mean()) - 1) * 100:.1f}%"
)
with kpi3:
st.metric(
"Total Profit",
f"${filtered_df['Profit'].sum():,.0f}",
f"{((filtered_df['Profit'].sum() / df_sales['Profit'].sum()) - 1) * 100:.1f}%"
)
with kpi4:
st.metric(
"Profit Margin",
f"{(filtered_df['Profit'].sum() / filtered_df['Sales'].sum() * 100):.1f}%"
)
# Sales Trends
st.subheader("Sales Trends Analysis")
daily_sales = filtered_df.groupby('Date')[['Sales', 'Profit']].sum().reset_index()
# Create the figure ensuring dates are in datetime format
fig = go.Figure()
fig.add_trace(go.Scatter(
x=daily_sales['Date'].dt.strftime('%Y-%m-%d'), # Convert to string format
y=daily_sales['Sales'],
name='Sales',
line=dict(color='blue')
))
fig.add_trace(go.Scatter(
x=daily_sales['Date'].dt.strftime('%Y-%m-%d'), # Convert to string format
y=daily_sales['Profit'],
name='Profit',
line=dict(color='green')
))
fig.update_layout(
title='Daily Sales and Profit Trends',
xaxis_title='Date',
yaxis_title='Amount ($)',
xaxis=dict(
type='category', # Use category type for x-axis
tickangle=45
)
)
st.plotly_chart(fig, use_container_width=True)
# Regional Analysis
st.subheader("Regional Performance")
regional_data = filtered_df.groupby('Region').agg({
'Sales': 'sum',
'Profit': 'sum'
}).reset_index()
fig_region = go.Figure(data=[
go.Bar(name='Sales', x=regional_data['Region'], y=regional_data['Sales']),
go.Bar(name='Profit', x=regional_data['Region'], y=regional_data['Profit'])
])
fig_region.update_layout(
barmode='group',
title='Sales and Profit by Region'
)
st.plotly_chart(fig_region, use_container_width=True)
# Product Analysis
if product_type == 'All':
st.subheader("Product Performance")
product_data = filtered_df.groupby('Product').agg({
'Sales': 'sum',
'Profit': 'sum'
}).reset_index()
fig_product = go.Figure(data=[
go.Bar(name='Sales', x=product_data['Product'], y=product_data['Sales']),
go.Bar(name='Profit', x=product_data['Product'], y=product_data['Profit'])
])
fig_product.update_layout(
barmode='group',
title='Sales and Profit by Product'
)
st.plotly_chart(fig_product, use_container_width=True)
# Footer
st.markdown("---")
st.markdown(f"Dashboard last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") |