ablon1 commited on
Commit
27df87d
·
verified ·
1 Parent(s): 3fa2031

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -0
app.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import gradio as gr
3
+ import numpy as np
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ from sklearn.linear_model import LinearRegression
7
+
8
+ # Dados históricos
9
+ anos = np.arange(2015, 2025)
10
+
11
+ valoresRCL = np.array([
12
+ 18461481002, 19881229932, 20719829099, 21742563018, 22503460737,
13
+ 25058903184, 28277263875, 29460072799, 33214094007, 36114673966
14
+ ]) / 1e9
15
+
16
+ valoresRT = np.array([
17
+ 25877008148, 26260519658, 21656374939, 22808686104, 23142025074,
18
+ 24871412313, 28451064067, 30984998453, 33361387405, 35629361262
19
+ ]) / 1e9
20
+
21
+ IGPM = np.array([10.54, 7.17, -0.52, 7.54, 7.30, 23.14, 17.78, 5.45, -3.18, 6.54]) / 100
22
+ PIB = np.array([-3.5, -3.3, 1.3, 1.8, 1.2, -3.3, 4.8, 3.0, 3.2, 3.4]) / 100
23
+
24
+ # Função principal
25
+ def simular(n_simulacoes, n_anos_futuros, taxa_isencao):
26
+ taxa_isencao = taxa_isencao / 100 # converter para proporção
27
+
28
+ # Modelo de regressão
29
+ delta_RCL = np.diff(valoresRCL)
30
+ delta_RT = np.diff(valoresRT)
31
+ X = np.column_stack((IGPM[1:], PIB[1:]))
32
+
33
+ modelo_RCL = LinearRegression().fit(X, delta_RCL)
34
+ modelo_RT = LinearRegression().fit(X, delta_RT)
35
+
36
+ # Simulação normal
37
+ mu_igpm, sigma_igpm = np.mean(IGPM), np.std(IGPM)
38
+ mu_pib, sigma_pib = np.mean(PIB), np.std(PIB)
39
+
40
+ anos_futuros = np.arange(2024, 2024 + n_anos_futuros + 1)
41
+
42
+ igpm_futuro = np.random.normal(mu_igpm, sigma_igpm, (n_simulacoes, n_anos_futuros))
43
+ pib_futuro = np.random.normal(mu_pib, sigma_pib, (n_simulacoes, n_anos_futuros))
44
+
45
+ simulacoes_RCL = np.zeros((n_simulacoes, n_anos_futuros + 1))
46
+ simulacoes_RT = np.zeros((n_simulacoes, n_anos_futuros + 1))
47
+ simulacoes_RCL[:, 0] = valoresRCL[-1]
48
+ simulacoes_RT[:, 0] = valoresRT[-1]
49
+
50
+ for t in range(1, n_anos_futuros + 1):
51
+ X_t = np.column_stack((igpm_futuro[:, t - 1], pib_futuro[:, t - 1]))
52
+ inc_RCL = modelo_RCL.predict(X_t)
53
+ inc_RT = modelo_RT.predict(X_t)
54
+ simulacoes_RCL[:, t] = (simulacoes_RCL[:, t - 1] + inc_RCL) * (1 - taxa_isencao)
55
+ simulacoes_RT[:, t] = (simulacoes_RT[:, t - 1] + inc_RT) * (1 - taxa_isencao)
56
+
57
+ # Estatísticas
58
+ media_RCL = np.mean(simulacoes_RCL, axis=0)
59
+ p10_RCL = np.percentile(simulacoes_RCL, 10, axis=0)
60
+ p90_RCL = np.percentile(simulacoes_RCL, 90, axis=0)
61
+
62
+ media_RT = np.mean(simulacoes_RT, axis=0)
63
+ p10_RT = np.percentile(simulacoes_RT, 10, axis=0)
64
+ p90_RT = np.percentile(simulacoes_RT, 90, axis=0)
65
+
66
+ # Probabilidade de queda
67
+ def prob_queda(sim):
68
+ probs = []
69
+ for t in range(1, n_anos_futuros + 1):
70
+ queda = sim[:, t] < sim[:, t - 1]
71
+ prob = np.mean(queda) * 100
72
+ probs.append(f"{anos_futuros[t]}: {prob:.2f}%")
73
+ return "\n".join(probs)
74
+
75
+ # Gráficos
76
+ def plot_grafico(y_hist, media, p10, p90, titulo):
77
+ fig, ax = plt.subplots(figsize=(8, 4))
78
+ ax.plot(anos, y_hist, label="Histórico", marker='o')
79
+ ax.plot(anos_futuros, media, label="Média Simulada")
80
+ ax.fill_between(anos_futuros, p10, p90, alpha=0.3, label="Faixa 10–90%")
81
+ ax.set_title(titulo)
82
+ ax.set_xlabel("Ano")
83
+ ax.set_ylabel("R$ bi")
84
+ ax.grid(True)
85
+ ax.legend()
86
+ return fig
87
+
88
+ fig_rcl = plot_grafico(valoresRCL, media_RCL, p10_RCL, p90_RCL, "Receita Corrente Líquida (RCL)")
89
+ fig_rt = plot_grafico(valoresRT, media_RT, p10_RT, p90_RT, "Receita Total (RT)")
90
+
91
+ # Tabela histórica
92
+ var_RT = [np.nan] + list(100 * np.diff(valoresRT) / valoresRT[:-1])
93
+ var_RCL = [np.nan] + list(100 * np.diff(valoresRCL) / valoresRCL[:-1])
94
+ df = pd.DataFrame({
95
+ "Ano": anos,
96
+ "RCL (bi R$)": np.round(valoresRCL, 2),
97
+ "Δ% RCL": np.round(var_RCL, 2),
98
+ "RT (bi R$)": np.round(valoresRT, 2),
99
+ "Δ% RT": np.round(var_RT, 2),
100
+ "IGPM (%)": np.round(IGPM * 100, 2),
101
+ "PIB (%)": np.round(PIB * 100, 2)
102
+ })
103
+
104
+ return (
105
+ fig_rcl,
106
+ fig_rt,
107
+ df,
108
+ prob_queda(simulacoes_RCL),
109
+ prob_queda(simulacoes_RT)
110
+ )
111
+
112
+ # Interface Gradio
113
+ demo = gr.Interface(
114
+ fn=simular,
115
+ inputs=[
116
+ gr.Slider(100, 5000, value=1000, step=100, label="Número de Simulações"),
117
+ gr.Slider(1, 10, value=5, step=1, label="Anos de Projeção"),
118
+ gr.Slider(0, 20, value=5, step=1, label="Taxa de Isenção Fiscal (%)")
119
+ ],
120
+ outputs=[
121
+ gr.Plot(label="Projeção RCL"),
122
+ gr.Plot(label="Projeção RT"),
123
+ gr.Dataframe(label="Tabela de Dados Históricos"),
124
+ gr.Textbox(label="Prob. Queda RCL"),
125
+ gr.Textbox(label="Prob. Queda RT")
126
+ ],
127
+ title="📊 Simulação Receita Pública - Monte Carlo",
128
+ description="Monte Carlo com distribuição normal baseada em IGPM e PIB históricos (2015–2024)."
129
+ )
130
+
131
+ if __name__ == "__main__":
132
+ demo.launch()