File size: 7,412 Bytes
f0a1298 a0a868f 4a19aa3 a0a868f 2d23850 29ce758 b68ebe5 2d23850 b68ebe5 ee50dda c236d96 997ea01 c236d96 b68ebe5 c236d96 b68ebe5 c236d96 b68ebe5 c236d96 b68ebe5 c236d96 997ea01 c236d96 b68ebe5 2d23850 b68ebe5 c236d96 2d23850 b68ebe5 0db0671 c236d96 b68ebe5 997ea01 b68ebe5 c236d96 b68ebe5 c09736c 094e580 d42c419 094e580 d48d925 094e580 2d23850 094e580 2d23850 094e580 2d23850 094e580 2d23850 094e580 b68ebe5 997ea01 70dcc90 63fbba9 3e93ec0 c09736c 26ee1f1 3e93ec0 2d23850 3e93ec0 d48d925 2d23850 3e93ec0 094e580 a99f595 997ea01 26ee1f1 997ea01 26ee1f1 997ea01 26ee1f1 997ea01 26ee1f1 997ea01 26ee1f1 997ea01 3e93ec0 997ea01 3e93ec0 997ea01 26ee1f1 997ea01 3e93ec0 c236d96 997ea01 b68ebe5 29ce758 |
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 |
import gradio as gr
from fpdf import FPDF
import tempfile
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
import uuid
# Função para formatar moeda manualmente em formato brasileiro
def formatar_moeda(valor):
return f"R$ {valor:,.2f}".replace(",", "v").replace(".", ",").replace("v", ".")
# Função para calcular ROI e gerar gráfico
def calcular_roi(valor_imovel, investimento_proprio, aluguel, anos, selic, desconto_aluguel, valorizacao, tipo_financiamento):
valor_imovel = float(valor_imovel)
investimento_proprio = float(investimento_proprio)
aluguel = float(aluguel)
anos = int(anos)
selic = float(selic)
desconto_aluguel = float(desconto_aluguel)
valorizacao = float(valorizacao)
# Para valorização do imóvel, limitar a 10 anos
anos_valorizacao = min(anos, 10)
financiado = valor_imovel - investimento_proprio
monthly_rate = (selic / 100) / 12
months = anos * 12
if tipo_financiamento == "Price":
parcela = (financiado * monthly_rate * (1 + monthly_rate) ** months) / ((1 + monthly_rate) ** months - 1)
parcelas = [parcela] * months
else: # SAC
amortizacao = financiado / months
parcelas = [(amortizacao + (financiado - amortizacao * i) * monthly_rate) for i in range(months)]
receita_mensal_liquida = aluguel * (1 - desconto_aluguel / 100)
receita_anual = receita_mensal_liquida * 12
parcela_media_anual = sum(parcelas[:12])
lucro_anual = receita_anual - parcela_media_anual
roi_anual = (lucro_anual / investimento_proprio) * 100
roi_mensal = (receita_mensal_liquida - parcelas[0]) / investimento_proprio * 100
roi_acumulado = []
saldo = 0
for ano in range(1, anos + 1):
saldo += receita_anual - sum(parcelas[(ano - 1) * 12: ano * 12])
roi_acumulado.append((saldo / investimento_proprio) * 100)
valor_futuro_imovel = valor_imovel * ((1 + valorizacao / 100) ** anos_valorizacao)
ganho_total = saldo + (valor_futuro_imovel - valor_imovel)
anos_array = list(range(1, anos + 1))
plt.figure(figsize=(8, 5))
plt.plot(anos_array, roi_acumulado, marker='o', label="ROI Acumulado (%)")
plt.title('Crescimento do ROI ao longo dos anos')
plt.xlabel('Ano')
plt.ylabel('ROI (%)')
plt.grid(True)
plt.tight_layout()
plt.legend()
graph_path_png = os.path.join(tempfile.gettempdir(), f'roi_plot_{uuid.uuid4().hex}.png')
plt.savefig(graph_path_png)
plt.close()
tabela_valorizacao = "\nAno\tValor do Imóvel"
for ano in range(1, anos_valorizacao + 1):
valor_ano = valor_imovel * ((1 + valorizacao / 100) ** ano)
tabela_valorizacao += f"\n{ano}\t{formatar_moeda(valor_ano)}"
resultados = f"""
Simulação realizada em: {datetime.now().strftime('%d/%m/%Y')}
Valor do Imóvel: {formatar_moeda(valor_imovel)}
Investimento Próprio: {formatar_moeda(investimento_proprio)}
Valor Financiado: {formatar_moeda(financiado)}
Tipo de Financiamento: {tipo_financiamento}
Parcela Mensal Inicial Estimada: {formatar_moeda(parcelas[0])}
Receita Líquida Anual: {formatar_moeda(receita_anual)}
Lucro Anual: {formatar_moeda(lucro_anual)}
ROI Anual: {roi_anual:.2f}%
ROI Mensal: {roi_mensal:.2f}%
Valor Futuro do Imóvel: {formatar_moeda(valor_futuro_imovel)}
Ganho Total Estimado: {formatar_moeda(ganho_total)}
Tabela de Valorização do Imóvel:
{tabela_valorizacao}
"""
explicacao = """
---
Explicações e Fórmulas Utilizadas:
1. Financiamento Price (Sistema Francês de Amortização):
PMT = P x [i x (1 + i)^n] / [(1 + i)^n - 1]
Onde:
- P: valor financiado
- i: taxa de juros mensal
- n: número total de parcelas
2. Financiamento SAC (Sistema de Amortização Constante):
A = P / n
Parcela mensal = A + juros sobre saldo devedor
3. ROI Mensal (%):
ROI mensal = [(Receita mensal líquida - PMT) / Investimento] × 100
4. ROI Anual (%):
ROI anual = [(Receita anual líquida - Total parcelas no ano) / Investimento] × 100
5. Valorização do Imóvel:
Valor Futuro = Valor Inicial × (1 + taxa)^anos (máx. 10 anos)
---
"""
return resultados + explicacao, graph_path_png, roi_anual, roi_mensal
def gerar_pdf(valor_imovel, investimento_proprio, aluguel, anos, selic, desconto_aluguel, valorizacao, tipo_financiamento):
try:
resultados, graph_path, roi_anual, roi_mensal = calcular_roi(valor_imovel, investimento_proprio, aluguel, anos, selic, desconto_aluguel, valorizacao, tipo_financiamento)
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.set_margins(15, 20, 15)
pdf.add_page()
pdf.set_font("Arial", 'B', 14)
pdf.cell(0, 10, "Relatório de Simulação de ROI de Aluguel", ln=True, align='C')
pdf.set_font("Arial", '', 10)
pdf.cell(0, 10, f"Data: {datetime.now().strftime('%d/%m/%Y')}", ln=True, align='C')
pdf.ln(10)
pdf.set_font("Arial", size=10)
for linha in resultados.strip().split("\n"):
if linha.strip():
linha_latin1 = linha.encode('latin-1', errors='ignore').decode('latin-1')
pdf.multi_cell(0, 6, linha_latin1)
if graph_path and os.path.exists(graph_path):
pdf.add_page()
pdf.image(graph_path, x=15, w=180)
temp_pdf_path = os.path.join(tempfile.gettempdir(), f"roi_relatorio_{uuid.uuid4().hex}.pdf")
pdf.output(temp_pdf_path)
return temp_pdf_path
except Exception as e:
print("Erro ao gerar PDF:", e)
return None
with gr.Blocks() as demo:
with gr.Row():
valor_imovel = gr.Slider(label="Valor do Imóvel", minimum=50000, maximum=2000000, step=1000, value=500000)
investimento_proprio = gr.Slider(label="Investimento Próprio", minimum=10000, maximum=1000000, step=1000, value=100000)
with gr.Row():
aluguel = gr.Slider(label="Valor do Aluguel", minimum=500, maximum=10000, step=50, value=2500)
anos = gr.Slider(label="Prazo (anos)", minimum=1, maximum=35, step=1, value=30)
with gr.Row():
selic = gr.Slider(label="Taxa SELIC (%)", minimum=2.0, maximum=20.0, step=0.1, value=10.75)
desconto_aluguel = gr.Slider(label="Desconto sobre o aluguel (%)", minimum=0, maximum=50, step=1, value=10)
valorizacao = gr.Slider(label="Valorização do imóvel ao ano (%)", minimum=0, maximum=20, step=0.5, value=5)
tipo_financiamento = gr.Radio(["SAC", "Price"], label="Tipo de Financiamento", value="SAC")
botao_calcular = gr.Button("Calcular ROI")
saida_texto = gr.Textbox(label="Resultado da Simulação", lines=25)
saida_imagem = gr.Image(label="Gráfico ROI")
botao_pdf = gr.Button("Gerar Relatório em PDF")
saida_pdf = gr.File(label="Download do Relatório")
saida_roi = gr.Number(visible=False)
saida_parcela = gr.Number(visible=False)
botao_calcular.click(
calcular_roi,
inputs=[valor_imovel, investimento_proprio, aluguel, anos, selic, desconto_aluguel, valorizacao, tipo_financiamento],
outputs=[saida_texto, saida_imagem, saida_roi, saida_parcela]
)
botao_pdf.click(
gerar_pdf,
inputs=[valor_imovel, investimento_proprio, aluguel, anos, selic, desconto_aluguel, valorizacao, tipo_financiamento],
outputs=saida_pdf
)
demo.launch()
|