Spaces:
Build error
Build error
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| import plotly.express as px | |
| import plotly.graph_objects as go | |
| # --- Dados --- | |
| meses = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'] | |
| dados_2024 = { | |
| 'Mes': meses, | |
| 'Papel_Papelao': [8047, 11287, 8184, 10183, 5699, 5830, 7465, 5600, 2960, 5175, 9656, 3960], | |
| 'Plastico': [6353, 8771, 6993, 8050, 4880, 5296, 5937, 4747, 2446, 4109, 7667, 3367], | |
| 'Metal': [1061, 2025, 1121, 1832, 716, 936, 1553, 904, 361, 630, 1904, 569], | |
| 'Vidro': [5248, 6929, 6014, 5821, 3697, 3655, 4950, 3360, 1580, 3261, 6173, 2357] | |
| } | |
| df_2024 = pd.DataFrame(dados_2024) | |
| dados_anuais = { | |
| 'Ano': [2022, 2023, 2024], | |
| 'Papel_Papelao': [18780, 58718, 84046], | |
| 'Plastico': [5340, 1041, 8279], | |
| 'Metal': [1300, 1737, 19955], | |
| 'Vidro': [0, 725, 1709] | |
| } | |
| df_anuais = pd.DataFrame(dados_anuais) | |
| precos = { | |
| 'Papel_Papelao': 0.50, | |
| 'Plastico': 0.80, | |
| 'Metal': 2.00, | |
| 'Vidro': 0.30 | |
| } | |
| # --- Estatísticas descritivas --- | |
| desc = df_2024.drop(columns='Mes').describe().T | |
| desc['Mediana'] = df_2024.drop(columns='Mes').median() | |
| desc = desc[['mean', 'Mediana', 'std', 'min', 'max']] | |
| desc.columns = ['Média', 'Mediana', 'Desvio Padrão', 'Mínimo', 'Máximo'] | |
| # --- Simulação de faturamento --- | |
| estatisticas = {} | |
| for material in precos.keys(): | |
| media = df_2024[material].mean() | |
| std = df_2024[material].std() | |
| estatisticas[material] = {'media': media, 'std': std} | |
| def simular_faturamento_anual(estats, precos, fator=1.0, n_sim=1000, seed=42): | |
| np.random.seed(seed) | |
| faturamentos = [] | |
| for _ in range(n_sim): | |
| total = 0 | |
| for material, stats in estats.items(): | |
| medias = stats['media'] * fator | |
| stds = stats['std'] | |
| quantidades = np.random.normal(medias, stds, 12) | |
| quantidades = np.clip(quantidades, 0, None) | |
| total += quantidades.sum() * precos[material] | |
| faturamentos.append(total) | |
| return np.array(faturamentos) | |
| cenarios = { | |
| 'Base': 1.0, | |
| 'Otimista': 1.15, | |
| 'Pessimista': 0.85 | |
| } | |
| simulacoes = {nome: simular_faturamento_anual(estatisticas, precos, fator=fator) for nome, fator in cenarios.items()} | |
| # --- Streamlit App --- | |
| st.title('Dashboard de Recicláveis e Faturamento') | |
| # Sidebar | |
| materiais_opcoes = ['Todos'] + list(precos.keys()) | |
| cenarios_opcoes = ['Todos', 'Otimista', 'Pessimista', 'Base'] | |
| material = st.sidebar.selectbox('Selecione o material', materiais_opcoes) | |
| cenario = st.sidebar.selectbox('Selecione o cenário de faturamento', cenarios_opcoes) | |
| # --- Gráficos organizados --- | |
| if material != 'Todos': | |
| # Evolução anual | |
| st.header(f'Evolução Anual de {material}') | |
| fig1 = px.bar(df_anuais, x='Ano', y=material, title=f'Evolução Anual de {material}', | |
| labels={'value': 'Quantidade (kg)', 'Ano': 'Ano'}, | |
| template='plotly_white', text_auto=True) | |
| fig1.update_layout(title_font_size=20, xaxis_title='Ano', yaxis_title='Quantidade (kg)') | |
| st.plotly_chart(fig1, use_container_width=True) | |
| # Evolução mensal | |
| st.header(f'Evolução Mensal de {material} em 2024') | |
| fig2 = px.line(df_2024, x='Mes', y=material, markers=True, title=f'Evolução Mensal de {material} em 2024', | |
| labels={'Mes': 'Mês', material: 'Quantidade (kg)'}, template='plotly_white') | |
| fig2.update_layout(title_font_size=20, xaxis_title='Mês', yaxis_title='Quantidade (kg)') | |
| st.plotly_chart(fig2, use_container_width=True) | |
| else: | |
| # Evolução anual de todos | |
| st.header('Evolução Anual de Todos os Materiais') | |
| df_anuais_melt = df_anuais.melt(id_vars='Ano', var_name='Material', value_name='Quantidade') | |
| fig1 = px.bar(df_anuais_melt, x='Ano', y='Quantidade', color='Material', barmode='group', | |
| title='Evolução Anual de Todos os Materiais', | |
| labels={'Quantidade': 'Quantidade (kg)', 'Ano': 'Ano'}, template='plotly_white', text_auto=True) | |
| fig1.update_layout(title_font_size=20, xaxis_title='Ano', yaxis_title='Quantidade (kg)') | |
| st.plotly_chart(fig1, use_container_width=True) | |
| # Evolução mensal de todos | |
| st.header('Evolução Mensal de Todos os Materiais em 2024') | |
| df_2024_melt = df_2024.melt(id_vars='Mes', var_name='Material', value_name='Quantidade') | |
| fig2 = px.line(df_2024_melt, x='Mes', y='Quantidade', color='Material', markers=True, | |
| title='Evolução Mensal de Todos os Materiais em 2024', | |
| labels={'Mes': 'Mês', 'Quantidade': 'Quantidade (kg)'}, template='plotly_white') | |
| fig2.update_layout(title_font_size=20, xaxis_title='Mês', yaxis_title='Quantidade (kg)') | |
| st.plotly_chart(fig2, use_container_width=True) | |
| # Estatísticas descritivas | |
| st.header('Estatísticas Descritivas (2024)') | |
| st.dataframe(desc.style.format('{:,.2f}')) | |
| # Boxplot | |
| st.header('Boxplot dos Materiais em 2024') | |
| fig3 = px.box(df_2024.melt(id_vars='Mes', var_name='Material', value_name='Quantidade'), | |
| x='Material', y='Quantidade', title='Boxplot dos Materiais em 2024', | |
| labels={'Quantidade': 'Quantidade (kg)'}, template='plotly_white') | |
| fig3.update_layout(title_font_size=20, xaxis_title='Material', yaxis_title='Quantidade (kg)') | |
| st.plotly_chart(fig3, use_container_width=True) | |
| # --- Simulação de faturamento --- | |
| st.header('Distribuição do Faturamento Anual Simulado') | |
| # Função para tabela resumo | |
| cores = {'Base': '#1f77b4', 'Otimista': '#2ca02c', 'Pessimista': '#d62728'} | |
| def tabela_resumo(simulacoes): | |
| dados = [] | |
| for nome in cenarios.keys(): | |
| media = simulacoes[nome].mean() | |
| std = simulacoes[nome].std() | |
| dados.append([nome, f"{media:,.2f}", f"{std:,.2f}"]) | |
| df_faturamento_anual = pd.DataFrame(dados, columns=['Cenário', 'Faturamento Anual Médio (R$)', 'Desvio Padrão (R$)']) | |
| return df_faturamento_anual | |
| def grafico_cenarios(simulacoes): | |
| fig = go.Figure() | |
| for nome in cenarios.keys(): | |
| fig.add_trace(go.Histogram( | |
| x=simulacoes[nome], | |
| name=nome, | |
| histnorm='probability density', | |
| opacity=0.5, | |
| nbinsx=30, | |
| marker_color=cores[nome], | |
| showlegend=True | |
| )) | |
| fig.add_vline(x=simulacoes[nome].mean(), line_dash='dash', line_color=cores[nome], | |
| annotation_text=f'Média {nome}', annotation_position='top right') | |
| fig.update_layout( | |
| barmode='overlay', | |
| title='Distribuição do Faturamento Anual Simulado (2024)', | |
| xaxis_title='Faturamento Total Anual (R$)', | |
| yaxis_title='Densidade', | |
| legend_title='Cenário', | |
| template='plotly_white', | |
| title_font_size=20 | |
| ) | |
| return fig | |
| if cenario != 'Todos' and material != 'Todos': | |
| dados = simular_faturamento_anual({material: estatisticas[material]}, {material: precos[material]}, fator=cenarios[cenario.capitalize()]) | |
| fig4 = px.histogram(dados, nbins=30, title=f'Distribuição do Faturamento Anual Simulado - {material} ({cenario.capitalize()})', | |
| labels={'value': 'Faturamento Anual (R$)'}, template='plotly_white') | |
| fig4.add_vline(x=dados.mean(), line_dash='dash', line_color='red', annotation_text='Média', annotation_position='top right') | |
| fig4.update_layout(title_font_size=20, xaxis_title='Faturamento Anual (R$)', yaxis_title='Frequência') | |
| st.plotly_chart(fig4, use_container_width=True) | |
| st.write(f"Média do faturamento anual ({cenario.capitalize()}): R$ {dados.mean():,.2f}") | |
| elif cenario == 'Todos' and material != 'Todos': | |
| # Tabela resumo | |
| simulacoes_mat = {cen: simular_faturamento_anual({material: estatisticas[material]}, {material: precos[material]}, fator=cenarios[cen]) for cen in cenarios} | |
| st.subheader('Resumo Estatístico dos Cenários') | |
| st.dataframe(tabela_resumo(simulacoes_mat)) | |
| # Gráfico de densidade | |
| st.plotly_chart(grafico_cenarios(simulacoes_mat), use_container_width=True) | |
| elif cenario != 'Todos' and material == 'Todos': | |
| # Consolidar faturamento de todos os materiais para o cenário selecionado | |
| dados = simular_faturamento_anual(estatisticas, precos, fator=cenarios[cenario.capitalize()]) | |
| fig4 = px.histogram(dados, nbins=30, | |
| title=f'Distribuição do Faturamento Anual Simulado - Todos Materiais ({cenario.capitalize()})', | |
| labels={'value': 'Faturamento Anual (R$)'}, template='plotly_white') | |
| fig4.add_vline(x=dados.mean(), line_dash='dash', line_color='red', annotation_text='Média', annotation_position='top right') | |
| fig4.update_layout(title_font_size=20, xaxis_title='Faturamento Anual (R$)', yaxis_title='Frequência') | |
| st.plotly_chart(fig4, use_container_width=True) | |
| st.write(f"Média do faturamento anual (Todos os Materiais, {cenario.capitalize()}): R$ {dados.mean():,.2f}") | |
| st.write(f"Desvio padrão: R$ {dados.std():,.2f}") | |
| else: # Todos cenários e todos materiais | |
| # Consolidar faturamento de todos os materiais para cada cenário | |
| simulacoes_totais = {cen: simular_faturamento_anual(estatisticas, precos, fator=cenarios[cen]) for cen in cenarios} | |
| st.subheader('Resumo Estatístico Consolidado dos Cenários (Todos os Materiais)') | |
| st.dataframe(tabela_resumo(simulacoes_totais)) | |
| st.plotly_chart(grafico_cenarios(simulacoes_totais), use_container_width=True) |