File size: 7,890 Bytes
4b68381
 
c318f99
 
be5a04c
fba8193
018decc
4b68381
18438e9
 
17249dc
df022b3
3910b68
df022b3
 
 
 
3910b68
df022b3
3910b68
df022b3
 
 
 
 
 
3910b68
df022b3
 
 
a268f6c
 
 
 
 
 
 
 
 
 
 
3910b68
a8d856c
cfc693b
3910b68
bd326b8
c318f99
4b68381
a8d856c
da0d4b5
 
d2e8577
fba8193
098ca40
d2e8577
 
576a621
ad5d544
 
098ca40
b654e25
 
 
 
 
 
 
 
 
 
 
 
ad5d544
b654e25
ad5d544
b654e25
ad5d544
098ca40
b654e25
ad5d544
b654e25
098ca40
a2fbaf9
 
 
 
 
 
 
 
 
 
 
d283271
a2fbaf9
 
 
 
9f3b801
d283271
9f3b801
a2fbaf9
ad5d544
a2fbaf9
 
098ca40
78b5466
1cee5ae
f17ebf3
78b5466
6761cfe
78b5466
bdd90e4
 
78b5466
bdd90e4
78b5466
 
bdd90e4
 
 
 
78b5466
2864c62
 
 
8b09f68
67830d9
 
2864c62
 
 
67830d9
 
7b357aa
67830d9
14a3d68
 
 
 
2864c62
 
 
78b5466
8b09f68
67830d9
bdd90e4
 
78b5466
 
bdd90e4
2864c62
7d074fa
8b09f68
ad44ac7
7d074fa
78b5466
8b09f68
 
 
 
 
 
 
 
 
18438e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bec769c
18438e9
 
 
 
bec769c
 
78b5466
1cee5ae
78b5466
 
4eb045d
 
 
 
 
 
 
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import streamlit as st
import pandas as pd
import numpy as np

#st.set_page_config(layout="wide")

df = pd.read_csv('last_results_5.csv')

temp_data = pd.read_csv('temp_data(2).csv')

image1 = 'images/rs_pmpa.PNG'

title_html = """
    <style>
        @font-face {
            font-family: 'Quicksand';
            src: url('font/Quicksand-VariableFont_wght.ttf') format('truetype');
        }
        body {
            font-family: 'Quicksand', sans-serif;
        }
        .custom-title {
            color: darkgreen;
            font-size: 30px;
            font-weight: bold;
        }
    </style>
    <span class='custom-title'>PREVISÕES DE RECEITAS</span>
"""

# Set a fixed width for the sidebar
st.markdown(
    """
    <style>
        .sidebar .sidebar-content {
            width: 300px;
        }
    </style>
    """,
    unsafe_allow_html=True
)

with st.sidebar:
    st.image(image1, use_column_width=True)
    st.markdown(title_html, unsafe_allow_html=True)
    selected_instituicao = st.selectbox('Seleciona Instituição', df['Instituição'].unique())
    selected_conta = st.selectbox('Seleciona Conta', df['Conta'].unique())

# Filter the DataFrame based on selected values
filtered_df = df[(df['Instituição'] == selected_instituicao) & (df['Conta'] == selected_conta)]

#col1, col2, col3 = st.columns(3) # This divides the page into three equal parts

# Set custom width for columns
col1_width = 400
col2_width = 400
col1, col2 = st.columns([col1_width, col2_width])

# Display the Forecasts values in the first column
col1.header('Valores previstos')

if not filtered_df.empty:
    data_string = filtered_df['Forecasts'].iloc[0]

    # Split the string into lines
    lines = data_string.split('\n')

    # Iterate through the lines and extract the values
    for line in lines[:-2]:
        period, value = line.split()
        num_float = float(value)
        monetary_value = f'R$ {num_float:,.2f}'  # Adding commas for thousands separator
        col1.write(f"Período {period}: {monetary_value}")
else:
    col1.warning('No data available for the selected filters.')

# Display the Forecasts values as line plots in the second column
col2.header('Gráfico com previsões')

if not filtered_df.empty:
    data_string = filtered_df['Forecasts'].iloc[0]

    # Create a list to store data for each period
    data = []

    # Split the string into lines
    lines = data_string.split('\n')

    # Iterate through the lines and extract the values
    for line in lines[:-2]:
        period, value = line.split()
        num_float = float(value)
        monetary_value = f'R$ {num_float:,.2f}'  # Adding commas for thousands separator
        data.append({'Period': int(period), 'Monetary Value': num_float})

    # Create a DataFrame from the list
    chart_data = pd.DataFrame(data)

    # Sort the DataFrame by 'Period'
    chart_data = chart_data.sort_values(by='Period')

    # Display line chart with "period" on X-axis and "Monetary Value" on Y-axis
    col2.line_chart(chart_data.set_index('Period'))

else:
    col2.warning('No data available for the selected filters.')

# Display the table in the third column
#col3 = st.columns(1)  # You can use st.columns(1) to create a single column layout

#col3.header('Resultados')
if not filtered_df.empty:
    # Filter the DataFrame for the selected institution
    tab_df = df[df['Instituição'] == selected_instituicao]

    # Create an empty list to store data
    data = []

    # Iterate through each unique 'Conta' in the filtered DataFrame
    for conta in tab_df['Conta'].unique():
        # Filter the DataFrame for the current 'Conta'
        conta_df = tab_df[tab_df['Conta'] == conta]

        # Initialize a variable to store the sum for the current 'Conta'
        conta_sum = 0.0

        # Take the first 'Modelo' for simplicity
        modelo = conta_df['Modelo'].iloc[0]

        # Iterate over each row in the filtered DataFrame for the current 'Conta'
        for _, row in conta_df.iterrows():
            lines = row['Forecasts'].split('\n')
            for line in lines[:-1]:  # Skip the summary line
                if line.strip():
                    parts = line.split()
                    value = parts[-1]
                    try:
                        conta_sum += float(value)
                    except ValueError:
                        print(f"Skipping line unable to convert to float: {line}")

        # Format the sum as a monetary value
        monetary_value = f'R$ {conta_sum:,.2f}'

        # Append the data to the list
        data.append({'Conta': conta, 'Modelo': modelo, 'Valor Monetário': monetary_value})

    # Convert the list to a DataFrame
    table_data = pd.DataFrame(data)

    # Calculate the grand total sum of all 'Conta' values
    total_sum = sum(float(row['Valor Monetário'].replace('R$ ', '').replace(',', '')) for row in data)

    # Append the "Total" row
    total_row = pd.DataFrame({'Conta': ['TOTAL (RLIT)'], 'Modelo': [''], 'Valor Monetário': [f'R$ {total_sum:,.2f}']})
    table_data = pd.concat([table_data, total_row], ignore_index=True)

    # Calculate and append the rows for "Saúde (12% da RLIT)" and "Educação (25% da RLIT)"
    saude_value = total_sum * 0.15
    educacao_value = total_sum * 0.25
    saude_row = pd.DataFrame({'Conta': ['Saúde (15% da RLIT)'], 'Modelo': [''], 'Valor Monetário': [f'R$ {saude_value:,.2f}']})
    educacao_row = pd.DataFrame({'Conta': ['Educação (25% da RLIT)'], 'Modelo': [''], 'Valor Monetário': [f'R$ {educacao_value:,.2f}']})

    # Append these rows to the table data
    table_data = pd.concat([table_data, saude_row, educacao_row], ignore_index=True)

    # Convert 'Data_Completa' to datetime format to ensure correct processing
    temp_data['Data_Completa'] = pd.to_datetime(temp_data['Data_Completa'])

    # Assuming 'Data_Completa' is sorted, if not, you should sort it.
    # temp_data = temp_data.sort_values(by='Data_Completa', ascending=False)

    # Initialize an empty list to store data including the 'Último ano' sums
    data_with_last_year = []

    # Iterate over each unique 'Instituição' and 'Conta' combination in 'df'
    for instituicao in df['Instituição'].unique():
        for conta in df[df['Instituição'] == instituicao]['Conta'].unique():
            # Filter temp_data for the current 'Instituição' and 'Conta'
            filtered_temp = temp_data[(temp_data['Instituição'] == instituicao) & (temp_data['Conta'] == conta)]

            # Get the last 12 periods of 'Data_Completa'
            last_12_periods = filtered_temp.nlargest(12, 'Data_Completa')

            # Calculate the sum of 'Valor' for these periods
            last_year_sum = last_12_periods['Valor'].sum()

            # Append this information to the data list
            data_with_last_year.append({
                'Instituição': instituicao,
                'Conta': conta,
                'Último ano': last_year_sum
            })

    # Convert the list to a DataFrame
    last_year_data = pd.DataFrame(data_with_last_year)

    # Merge this DataFrame with your existing table data to add the 'Último ano' column
    # Assuming 'table_data' is your existing DataFrame that you want to add the column to
    # You might need to adjust column names or merge keys based on your actual data structure
    table_data = table_data.merge(last_year_data, on=['Instituição', 'Conta'], how='left')


    # Display the table
    st.table(table_data)

else:
    col3.warning('No data available for the selected filters.')


st.markdown("""
    <b>Observação:</b> Previsões realizadas com dados extraídos do Relatório Resumido de Execução Orçamentária (RREO) até o 6º bimestre de 2023 no Sistema de Informações Contábeis e Fiscais do Setor Público Brasileiro (SICONFI). 
    [Link](https://siconfi.tesouro.gov.br/)
    """, unsafe_allow_html=True)