🛠️ToolsShed

Calculadora TIR

Calcula la Tasa Interna de Retorno (TIR) para una serie de flujos de caja.

Future Cash Flows

Year 1
Year 2
Year 3
Year 4

Preguntas Frecuentes

Implementación de Código

def npv(rate: float, cash_flows: list) -> float:
    """Net Present Value at given rate."""
    return sum(cf / (1 + rate) ** t for t, cf in enumerate(cash_flows))

def irr(cash_flows: list, max_iter: int = 1000, tol: float = 1e-7) -> float | None:
    """Internal Rate of Return via Newton-Raphson iteration."""
    # Check sign change
    positives = any(cf > 0 for cf in cash_flows)
    negatives = any(cf < 0 for cf in cash_flows)
    if not (positives and negatives):
        return None

    rate = 0.1  # initial guess
    for _ in range(max_iter):
        f = npv(rate, cash_flows)
        # Derivative: d/dr NPV = sum(-t * cf / (1+r)^(t+1))
        df = sum(-t * cf / (1 + rate) ** (t + 1) for t, cf in enumerate(cash_flows))
        if df == 0:
            break
        new_rate = rate - f / df
        if abs(new_rate - rate) < tol:
            return new_rate
        rate = new_rate
    return None

# Example: invest $1000, receive $300, $400, $500 over 3 years
cash_flows = [-1000, 300, 400, 500]
result = irr(cash_flows)
if result is not None:
    print(f"IRR = {result * 100:.2f}%")
    print(f"NPV at IRR ≈ {npv(result, cash_flows):.6f}")  # should be ~0

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.