Calculadora DCA
Simule o retorno de investimento com aporte periódico (preço médio).
Perguntas Frequentes
Implementação de Código
from dataclasses import dataclass
from typing import List
@dataclass
class DCAResult:
period: int
contribution: float
balance: float
total_invested: float
gain_loss: float
gain_loss_pct: float
def dca_simulator(
initial: float,
periodic: float,
annual_return: float,
years: float,
frequency: int = 12 # per year
) -> List[DCAResult]:
"""
Simulate dollar-cost averaging investment.
Parameters:
initial - lump-sum initial investment
periodic - periodic contribution amount
annual_return - expected annual return rate (e.g. 0.07 for 7%)
years - investment duration in years
frequency - contributions per year (12=monthly, 52=weekly)
"""
periodic_rate = annual_return / frequency
periods = int(years * frequency)
balance = initial
total_invested = initial
results = []
for t in range(1, periods + 1):
balance = balance * (1 + periodic_rate) + periodic
total_invested += periodic
gain = balance - total_invested
results.append(DCAResult(
period=t,
contribution=periodic,
balance=balance,
total_invested=total_invested,
gain_loss=gain,
gain_loss_pct=gain / total_invested * 100
))
return results
# Example: $5,000 initial + $500/month at 7% for 30 years
results = dca_simulator(5000, 500, 0.07, 30, 12)
final = results[-1]
print(f"Final balance: ${final.balance:>12,.2f}")
print(f"Total invested: ${final.total_invested:>12,.2f}")
print(f"Total gain: ${final.gain_loss:>12,.2f}")
print(f"Return on invest: {final.gain_loss_pct:>10.1f}%")
# Yearly summary
print("\nYear | Balance | Invested | Gain/Loss")
for i in range(11, len(results) + 1, 12):
r = results[i - 1]
yr = i // 12
print(f"{yr:4d} | ${r.balance:>10,.2f} | ${r.total_invested:>10,.2f} | ${r.gain_loss:>10,.2f}")
Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.