Debug School

ashley
ashley

Posted on

APR vs APY in Code: Converting Compounding Frequencies Without Loss of Precision

In financial software, mixing up Annual Percentage Rate (APR) and Annual Percentage Yield (APY) is a frequent source of logic bugs. APR represents nominal interest without compounding, whereas APY measures the true annual return taking compounding frequency into account.

Deriving APY from APR

For a nominal rate $r$ compounded $m$ times per year:

APY = ((1 + r / m) ** m) - 1

For continuous compounding ($m \to \infty$):

APY_continuous = exp(r) - 1

Converting APY Back to Nominal APR

To determine the nominal periodic rate required to achieve a target APY:

r = m * (((1 + APY) ** (1 / m)) - 1)

Python Implementation

import math

def apr_to_apy(apr: float, comp_freq: int) -> float:
    if comp_freq < 0:
        raise ValueError("Compounding frequency must be >= 0.")
    if comp_freq == 0:
        return math.expm1(apr)
    return math.pow(1.0 + apr / comp_freq, comp_freq) - 1.0

def apy_to_apr(apy: float, comp_freq: int) -> float:
    if comp_freq <= 0:
        raise ValueError("Compounding frequency must be > 0.")
    return comp_freq * (math.pow(1.0 + apy, 1.0 / comp_freq) - 1.0)
Enter fullscreen mode Exit fullscreen mode

Verification and Simulation

To convert between APR and APY across different compounding schedules, try the APY calculator at Miryori.


Disclosure: The author leads content at Miryori, the free online calculator suite linked above. Educational arithmetic only, not financial advice.

Top comments (0)