---------------------------------------------------------------------- This is the API documentation for the perfinpy library. ---------------------------------------------------------------------- ## Income Foundations. Functions from the Income chapter. wealth_formula(median_income: 'ArrayLike', savings_rate: 'ArrayLike', annual_return: 'ArrayLike', years: 'ArrayLike') -> 'Numeric' Wealth from saving part of an income every year. The future value of saving `median_income * savings_rate` at the end of each year (contributions plus growth). From the [Income](https://mjfrigaard.github.io/fm-finance/income.html) chapter. Parameters ---------- median_income Yearly income. savings_rate Share of income saved, as a decimal. annual_return Yearly return, as a decimal. A 0% return gives the sum of the contributions. years Number of years. Returns ------- float or numpy.ndarray Ending balances. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. See Also -------- raise_invested_value : Monthly version for investing part of a raise. Examples -------- >>> from perfinpy import wealth_formula >>> # $45,000 income, 20% saved, 7% return, 30 years >>> wealth_formula(45000, savings_rate=0.20, annual_return=0.07, years=30) 850147.07 fixed_cost_ratio(fixed_costs: 'ArrayLike', take_home: 'ArrayLike') -> 'Numeric' Fixed costs as a percent of take home pay. From the [Income](https://mjfrigaard.github.io/fm-finance/income.html) chapter. Parameters ---------- fixed_costs Monthly fixed costs (rent, insurance, loan payments). take_home Monthly take home pay. Must be greater than 0. Returns ------- float or numpy.ndarray Percentages (`56.25` is 56.25%). Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `take_home` is not greater than 0. Examples -------- >>> from perfinpy import fixed_cost_ratio >>> fixed_cost_ratio(fixed_costs=1800, take_home=3200) 56.25 raise_invested_value(monthly_raise: 'ArrayLike', invest_share: 'ArrayLike', rate: 'ArrayLike', years: 'ArrayLike') -> 'Numeric' Future value of investing part of a raise. Invests `monthly_raise * invest_share` every month, compounded monthly. From the [Income](https://mjfrigaard.github.io/fm-finance/income.html) chapter. Parameters ---------- monthly_raise Monthly increase in take home pay. invest_share Share of the raise invested, as a decimal. rate Yearly return, as a decimal. years Number of years. Returns ------- float or numpy.ndarray Ending balances. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. See Also -------- wealth_formula : Yearly version for saving part of an income. Examples -------- >>> from perfinpy import raise_invested_value >>> # invest half of a $200/month raise at 7% for 30 years >>> raise_invested_value(200, invest_share=0.5, rate=0.07, years=30) 121997.09 ## Tracking Spending Foundations. Functions from the Tracking Spending chapter. apply_rules(df: 'pl.DataFrame', rules: 'pl.DataFrame') -> 'pl.DataFrame' Categorize transactions with keyword rules. Each row of `rules` holds a regular expression (`Pattern`) and the `Category` it assigns. Rules are tried in order and the first match wins; matching ignores case. Descriptions that match no rule get `"Other"`. From the [Tracking Spending](https://mjfrigaard.github.io/fm-finance/tracking_spending.html) chapter. Parameters ---------- df Transactions with a string `Description` column. rules Rules with string `Pattern` and `Category` columns. Returns ------- polars.DataFrame `df` with a `Category` column added (or replaced). Raises ------ TypeError If `df` or `rules` is not a polars DataFrame. ValueError If a required column is missing. Examples -------- >>> import polars as pl >>> from perfinpy import apply_rules >>> transactions = pl.DataFrame( ... {"Description": ["SAFEWAY #123", "NETFLIX.COM", "ATM FEE"]} ... ) >>> rules = pl.DataFrame( ... {"Pattern": ["safeway", "netflix"], ... "Category": ["Groceries", "Subscriptions"]} ... ) >>> apply_rules(transactions, rules)["Category"].to_list() ['Groceries', 'Subscriptions', 'Other'] subscription_opportunity_cost(monthly_cost: 'ArrayLike', years: 'ArrayLike', rate: 'ArrayLike' = 0.07) -> 'Numeric' What a subscription would grow to if invested instead. Treats the yearly cost (`monthly_cost * 12`) as a contribution made at the end of each year and grows it at `rate`. From the [Tracking Spending](https://mjfrigaard.github.io/fm-finance/tracking_spending.html) chapter. Parameters ---------- monthly_cost Monthly subscription price. years Number of years. rate Yearly return, as a decimal. Defaults to 0.07. Returns ------- float or numpy.ndarray Future values. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import subscription_opportunity_cost >>> # $15/month for 30 years at 7% >>> subscription_opportunity_cost(monthly_cost=15, years=30) 17002.94 ## Budgeting Foundations. Functions from the Budgeting chapter. percent_of_income(expense: 'ArrayLike', income: 'ArrayLike') -> 'Numeric' An expense as a percent of income. `expense` and `income` must cover the same period. From the [Budgeting](https://mjfrigaard.github.io/fm-finance/budgeting.html) chapter. Parameters ---------- expense Amount spent. income Income for the same period. Must be greater than 0. Returns ------- float or numpy.ndarray Percentages (`30` is 30%). Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `income` is not greater than 0. Examples -------- >>> from perfinpy import percent_of_income >>> percent_of_income(expense=1500, income=5000) 30.0 to_annual(amount: 'ArrayLike', period: "Literal['daily', 'weekly', 'monthly']" = 'daily') -> 'Numeric' Convert a daily, weekly, or monthly amount to a yearly amount. Uses 365 days, 52 weeks, and 12 months per year. From the [Budgeting](https://mjfrigaard.github.io/fm-finance/budgeting.html) chapter. Parameters ---------- amount Amount per `period`. period One of `"daily"`, `"weekly"`, or `"monthly"`. Returns ------- float or numpy.ndarray Yearly amounts. Raises ------ TypeError If `amount` is not numeric. ValueError If `amount` contains missing values, or `period` is not one of the choices. See Also -------- to_monthly : Convert to a monthly amount. Examples -------- >>> from perfinpy import to_annual >>> # $5 a day coffee >>> to_annual(amount=5, period="daily") 1825.0 to_monthly(amount: 'ArrayLike', period: "Literal['daily', 'weekly', 'annual']" = 'daily') -> 'Numeric' Convert a daily, weekly, or yearly amount to a monthly amount. Uses the book's rounded factors: 30.44 days and 4.33 weeks per month, so a round trip through `to_annual()` drifts slightly. From the [Budgeting](https://mjfrigaard.github.io/fm-finance/budgeting.html) chapter. Parameters ---------- amount Amount per `period`. period One of `"daily"`, `"weekly"`, or `"annual"`. Returns ------- float or numpy.ndarray Monthly amounts. Raises ------ TypeError If `amount` is not numeric. ValueError If `amount` contains missing values, or `period` is not one of the choices. See Also -------- to_annual : Convert to a yearly amount. Examples -------- >>> from perfinpy import to_monthly >>> # $150 a week in groceries >>> to_monthly(amount=150, period="weekly") 649.5 opportunity_cost(amount: 'ArrayLike', rate: 'ArrayLike', years: 'ArrayLike') -> 'Numeric' What an amount could grow to if invested instead of spent. Compounds `amount` once a year at `rate`. From the [Budgeting](https://mjfrigaard.github.io/fm-finance/budgeting.html) chapter. Parameters ---------- amount Amount spent today. rate Yearly return, as a decimal. years Number of years. Returns ------- float or numpy.ndarray Future values. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import opportunity_cost >>> # $25,000 saved on a car, invested at 7% for 30 years >>> opportunity_cost(amount=25000, rate=0.07, years=30) 190306.37 months_to_break_even(upfront_cost: 'ArrayLike', monthly_savings: 'ArrayLike') -> 'Numeric' Months until monthly savings cover an upfront cost. The result is not rounded. From the [Budgeting](https://mjfrigaard.github.io/fm-finance/budgeting.html) chapter. Parameters ---------- upfront_cost Cost paid today. monthly_savings Amount saved each month. Must be greater than 0. Returns ------- float or numpy.ndarray Months. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `monthly_savings` is not greater than 0. Examples -------- >>> from perfinpy import months_to_break_even >>> # $500 membership that saves $60 a month >>> months_to_break_even(upfront_cost=500, monthly_savings=60) 8.33 ## Managing Debt Foundations. Functions from the Managing Debt chapter. apr_to_apy(apr: 'ArrayLike', periods_per_year: 'ArrayLike' = 365) -> 'Numeric' Convert an APR to an annual percentage yield (APY). From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- apr Annual percentage rate, as a decimal. periods_per_year Compounding periods per year. Defaults to 365 (daily). Must be greater than 0. Returns ------- float or numpy.ndarray APYs, as decimals. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `periods_per_year` is not greater than 0. Examples -------- >>> from perfinpy import apr_to_apy >>> # 24% APR compounded daily >>> apr_to_apy(apr=0.24) 0.27114 months_to_payoff(balance: 'ArrayLike', monthly_payment: 'ArrayLike', apr: 'ArrayLike') -> 'Numeric' Months to pay off a balance with a fixed payment. Interest compounds monthly at `apr / 12`. The result is not rounded; the last payment is a partial one. From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- balance Current balance. Must be greater than 0. monthly_payment Fixed monthly payment. Must be greater than 0. apr Annual percentage rate, as a decimal. Returns ------- float or numpy.ndarray Months. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, `balance` or `monthly_payment` is not greater than 0, or the payment does not cover the first month's interest (the balance would never be paid off). Examples -------- >>> from perfinpy import months_to_payoff >>> # $5,000 balance, $100/month, 22% APR >>> months_to_payoff(balance=5000, monthly_payment=100, apr=0.22) 136.779 total_interest(monthly_payment: 'ArrayLike', n_months: 'ArrayLike', principal: 'ArrayLike') -> 'Numeric' Total interest paid over the life of a loan. All payments minus the amount borrowed. From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- monthly_payment Fixed monthly payment. n_months Number of payments. principal Amount borrowed. Returns ------- float or numpy.ndarray Interest paid. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import total_interest >>> # 6-year vs. 4-year car loan, $20,000 at 7% >>> total_interest(monthly_payment=[340.98, 478.92], n_months=[72, 48], ... principal=20000) array([4550.56, 2988.16]) loan_income_ratio(loan_total: 'ArrayLike', expected_salary: 'ArrayLike') -> 'Numeric' Total student loans as a multiple of expected starting salary. A ratio at or below 1 means you borrow no more than your first year's salary. From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- loan_total Total amount borrowed. expected_salary Expected yearly starting salary. Must be greater than 0. Returns ------- float or numpy.ndarray Ratios (`1.07` is 107% of salary). Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `expected_salary` is not greater than 0. Examples -------- >>> from perfinpy import loan_income_ratio >>> loan_income_ratio(loan_total=45000, expected_salary=42000) 1.0714 monthly_standard_payment(principal: 'ArrayLike', annual_rate: 'ArrayLike' = 0.065, years: 'ArrayLike' = 10) -> 'Numeric' Monthly payment on a standard student loan repayment plan. The same amortization formula as `mortgage_payment()`, with student loan defaults (6.5% over 10 years). From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- principal Amount borrowed. annual_rate Yearly interest rate, as a decimal. Defaults to 0.065. years Repayment term in years. Defaults to 10. Must be greater than 0. Returns ------- float or numpy.ndarray Monthly payments. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `years` is not greater than 0. See Also -------- mortgage_payment : The general amortization formula. Examples -------- >>> from perfinpy import monthly_standard_payment >>> monthly_standard_payment(principal=45000) 510.96 idr_monthly_payment(agi: 'ArrayLike', poverty_guideline: 'ArrayLike' = 15960, threshold_pct: 'ArrayLike' = 1.5, payment_rate: 'ArrayLike' = 0.1) -> 'Numeric' Income driven repayment (IDR) monthly payment. Discretionary income is adjusted gross income (AGI) above `threshold_pct` times the poverty guideline. The yearly payment is `payment_rate` of that, split into 12 months and rounded to cents. From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- agi Adjusted gross income. poverty_guideline Federal poverty guideline for the household size. Defaults to 15960 (one person). threshold_pct Multiple of the poverty guideline that is protected. Defaults to 1.5 (150%). payment_rate Share of discretionary income paid each year. Defaults to 0.10. Returns ------- float or numpy.ndarray Monthly payments. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import idr_monthly_payment >>> # IBR: $50,000 AGI, 150% threshold, 10% rate >>> idr_monthly_payment(agi=50000) 217.17 >>> # IBR for loans before July 2014: 15% rate >>> idr_monthly_payment(agi=50000, payment_rate=0.15) 325.75 dti_ratio(monthly_debt_payments: 'ArrayLike', gross_monthly_income: 'ArrayLike') -> 'Numeric' Debt to income ratio. Monthly debt payments as a percent of gross monthly income. From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- monthly_debt_payments Total monthly debt payments. gross_monthly_income Monthly income before taxes. Must be greater than 0. Returns ------- float or numpy.ndarray Percentages (`28.3` is 28.3%). Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `gross_monthly_income` is not greater than 0. Examples -------- >>> from perfinpy import dti_ratio >>> dti_ratio(monthly_debt_payments=1061, gross_monthly_income=3750) 28.29 payoff_vs_invest(loan_rate: 'float', expected_return: 'float') -> 'str' Pay off a debt or invest the difference. Compares a loan's interest rate with an expected investment return. From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- loan_rate The loan's yearly interest rate, as a decimal. A single number. expected_return Expected yearly investment return, as a decimal. A single number. Returns ------- str `"Pay off the debt"`, `"Invest the difference"`, or `"Roughly a wash; do both"`. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values or is not a single number. Examples -------- >>> from perfinpy import payoff_vs_invest >>> payoff_vs_invest(loan_rate=0.05, expected_return=0.07) 'Invest the difference' order_avalanche(debts: 'list[dict[str, Any]]') -> 'list[dict[str, Any]]' Order debts for the avalanche method (highest APR first). From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- debts A list of dicts, each with a numeric `apr` key. Returns ------- list of dict A new list, sorted by `apr` from highest to lowest. Ties keep their original order. Raises ------ TypeError If `debts` is not a list of dicts, or an `apr` is not numeric. ValueError If a debt has no `apr` key, or an `apr` is missing. See Also -------- order_snowball : Smallest balance first. Examples -------- >>> from perfinpy import order_avalanche >>> debts = [ ... {"name": "Card A", "balance": 1000, "apr": 0.18}, ... {"name": "Card B", "balance": 5000, "apr": 0.24}, ... {"name": "Card C", "balance": 2000, "apr": 0.15}, ... ] >>> [d["name"] for d in order_avalanche(debts)] ['Card B', 'Card A', 'Card C'] order_snowball(debts: 'list[dict[str, Any]]') -> 'list[dict[str, Any]]' Order debts for the snowball method (smallest balance first). From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- debts A list of dicts, each with a numeric `balance` key. Returns ------- list of dict A new list, sorted by `balance` from smallest to largest. Ties keep their original order. Raises ------ TypeError If `debts` is not a list of dicts, or a `balance` is not numeric. ValueError If a debt has no `balance` key, or a `balance` is missing. See Also -------- order_avalanche : Highest APR first. Examples -------- >>> from perfinpy import order_snowball >>> debts = [ ... {"name": "Card A", "balance": 1000, "apr": 0.18}, ... {"name": "Card B", "balance": 5000, "apr": 0.24}, ... {"name": "Card C", "balance": 2000, "apr": 0.15}, ... ] >>> [d["name"] for d in order_snowball(debts)] ['Card A', 'Card C', 'Card B'] credit_utilization(balance: 'ArrayLike', credit_limit: 'ArrayLike') -> 'Numeric' Credit utilization: a card balance as a percent of its limit. From the [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter. Parameters ---------- balance Card balance. credit_limit Credit limit. Must be greater than 0. Returns ------- float or numpy.ndarray Percentages (`30` is 30%). Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `credit_limit` is not greater than 0. Examples -------- >>> from perfinpy import credit_utilization >>> credit_utilization(balance=900, credit_limit=3000) 30.0 ## Emergency Fund Foundations. Functions from the Emergency Fund chapter. emergency_fund_target(monthly_expenses: 'ArrayLike', months: 'ArrayLike' = 3) -> 'Numeric' Emergency fund target. Essential monthly expenses times the number of months to cover. From the [Emergency Fund](https://mjfrigaard.github.io/fm-finance/emergency_fund.html) chapter. Parameters ---------- monthly_expenses Essential monthly expenses. months Months of expenses to cover. Defaults to 3. Returns ------- float or numpy.ndarray Target balances. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import emergency_fund_target >>> # 3-month and 6-month targets on $2,400/month >>> emergency_fund_target(monthly_expenses=2400, months=[3, 6]) array([ 7200., 14400.]) months_to_ef_goal(target: 'ArrayLike', current_balance: 'ArrayLike', monthly_contribution: 'ArrayLike') -> 'Whole' Months to reach an emergency fund target. Rounded up to whole months. Returns 0 when the fund is already at or above the target. From the [Emergency Fund](https://mjfrigaard.github.io/fm-finance/emergency_fund.html) chapter. Parameters ---------- target Target balance. current_balance Amount already saved. monthly_contribution Amount added each month. Must be greater than 0. Returns ------- int or numpy.ndarray Whole months. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `monthly_contribution` is not greater than 0. See Also -------- monthly_contribution_needed : Solve for the contribution instead. Examples -------- >>> from perfinpy import months_to_ef_goal >>> months_to_ef_goal(target=9600, current_balance=1200, ... monthly_contribution=400) 21 monthly_contribution_needed(target: 'ArrayLike', current_balance: 'ArrayLike', months: 'ArrayLike') -> 'Whole' Monthly contribution needed to reach an emergency fund target. Rounded up to whole dollars. Returns 0 when the fund is already at or above the target. From the [Emergency Fund](https://mjfrigaard.github.io/fm-finance/emergency_fund.html) chapter. Parameters ---------- target Target balance. current_balance Amount already saved. months Months to reach the target. Must be greater than 0. Returns ------- int or numpy.ndarray Whole dollars per month. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `months` is not greater than 0. See Also -------- months_to_ef_goal : Solve for the months instead. Examples -------- >>> from perfinpy import monthly_contribution_needed >>> monthly_contribution_needed(target=9600, current_balance=1200, months=18) 467 ef_growth(balance: 'ArrayLike', apy: 'ArrayLike', months: 'ArrayLike') -> 'Numeric' Emergency fund balance after earning interest. Grows `balance` at `apy` for `months / 12` years. From the [Emergency Fund](https://mjfrigaard.github.io/fm-finance/emergency_fund.html) chapter. Parameters ---------- balance Starting balance. apy Annual percentage yield, as a decimal. months Number of months. Returns ------- float or numpy.ndarray Ending balances. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import ef_growth >>> ef_growth(balance=9600, apy=0.04, months=12) 9984.0 ## Savings Strategies Savings. Functions from the Savings Strategies chapter. savings_rate(income: 'ArrayLike', spending: 'ArrayLike') -> 'Numeric' Savings rate: the percent of income not spent. From the [Savings Strategies](https://mjfrigaard.github.io/fm-finance/savings_strategies.html) chapter. Parameters ---------- income Income for the period. Must be greater than 0. spending Spending for the same period. Returns ------- float or numpy.ndarray Percentages (`15` is 15%). Negative when spending exceeds income. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `income` is not greater than 0. Examples -------- >>> from perfinpy import savings_rate >>> savings_rate(income=3200, spending=2720) 15.0 ## High-Yield Savings Accounts Savings. Functions from the High-Yield Savings Accounts chapter. hysa_balance(principal: 'ArrayLike', annual_apy: 'ArrayLike', years: 'ArrayLike' = 1) -> 'Numeric' High-yield savings account balance. Grows `principal` at `annual_apy` for `years`. From the [High-Yield Savings Accounts](https://mjfrigaard.github.io/fm-finance/high_yield_accounts.html) chapter. Parameters ---------- principal Starting balance. annual_apy Annual percentage yield, as a decimal. years Number of years. Defaults to 1. Returns ------- float or numpy.ndarray Ending balances. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import hysa_balance >>> # $9,600 at 4% APY after 1 and 5 years >>> hysa_balance(principal=9600, annual_apy=0.04, years=[1, 5]) array([ 9984. , 11679.86786304]) ## Automating Savings Savings. Functions from the Automating Savings chapter. monthly_savings(gross_monthly_income: 'ArrayLike', savings_rate: 'ArrayLike') -> 'Numeric' Monthly amount to pay yourself first. From the [Automating Savings](https://mjfrigaard.github.io/fm-finance/automating_savings.html) chapter. Parameters ---------- gross_monthly_income Monthly income before taxes. savings_rate Share of income saved, as a decimal. Returns ------- float or numpy.ndarray Monthly savings. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import monthly_savings >>> monthly_savings(gross_monthly_income=4000, savings_rate=0.20) 800.0 ## Investing Basics Investing. Functions from the Investing Basics chapter. future_value(present_value: 'ArrayLike', rate: 'ArrayLike', years: 'ArrayLike') -> 'Numeric' Future value of a single amount with yearly compounding. From the [Investing Basics](https://mjfrigaard.github.io/fm-finance/investing_basics.html) chapter. Parameters ---------- present_value Amount invested today. rate Yearly return, as a decimal. years Number of years. Returns ------- float or numpy.ndarray Future values. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. See Also -------- future_value_series : Future value of regular contributions. Examples -------- >>> from perfinpy import future_value >>> # $10,000 at 7% for 10 years >>> future_value(present_value=10000, rate=0.07, years=10) 19671.51 >>> # several horizons in one call >>> future_value(present_value=10000, rate=0.07, years=[5, 10, 20, 30]) array([14025.517307 , 19671.5135729 , 38696.84462486, 76122.55042662]) rule_of_72(annual_return_pct: 'ArrayLike') -> 'Numeric' Years for money to double, by the rule of 72. The one function in the package that takes a percent rather than a decimal (`7`, not `0.07`). From the [Investing Basics](https://mjfrigaard.github.io/fm-finance/investing_basics.html) chapter. Parameters ---------- annual_return_pct Yearly return, as a percent. Must be greater than 0. Returns ------- float or numpy.ndarray Years to double. Raises ------ TypeError If `annual_return_pct` is not numeric. ValueError If `annual_return_pct` contains missing values or is not greater than 0. Examples -------- >>> from perfinpy import rule_of_72 >>> rule_of_72(annual_return_pct=7) 10.28 future_value_series(contribution: 'ArrayLike', rate: 'ArrayLike', periods: 'ArrayLike') -> 'Numeric' Future value of a fixed contribution made every period. Contributions are made at the end of each period. `rate` is the rate per period, so a monthly series uses `annual_rate / 12`. A 0% rate gives the sum of the contributions. From the [Investing Basics](https://mjfrigaard.github.io/fm-finance/investing_basics.html) chapter. Parameters ---------- contribution Amount contributed each period. rate Return per period, as a decimal. periods Number of periods. Returns ------- float or numpy.ndarray Future values. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. See Also -------- future_value : Future value of a single amount. Examples -------- >>> from perfinpy import future_value_series >>> # $500/month for 30 years at 7% a year >>> future_value_series(contribution=500, rate=0.07 / 12, periods=30 * 12) 609985.49 real_return(nominal: 'ArrayLike', inflation: 'ArrayLike') -> 'Numeric' Real (inflation adjusted) return. From the [Investing Basics](https://mjfrigaard.github.io/fm-finance/investing_basics.html) chapter. Parameters ---------- nominal Nominal yearly return, as a decimal. inflation Yearly inflation rate, as a decimal. Returns ------- float or numpy.ndarray Real returns, as decimals. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import real_return >>> real_return(nominal=0.07, inflation=0.03) 0.03883 ## Retirement Accounts Investing. Functions from the Retirement Accounts chapter. employer_match(salary: 'ArrayLike', contribution_pct: 'ArrayLike', match_limit_pct: 'ArrayLike', match_rate: 'ArrayLike') -> 'Numeric' Yearly employer match on retirement contributions. The employer matches `match_rate` of your contributions, up to `match_limit_pct` of salary. From the [Retirement Accounts](https://mjfrigaard.github.io/fm-finance/retirement_accounts.html) chapter. Parameters ---------- salary Yearly salary. contribution_pct Share of salary you contribute, as a decimal. match_limit_pct Share of salary the employer matches up to, as a decimal. match_rate Share of each matched dollar the employer adds, as a decimal. Returns ------- float or numpy.ndarray Yearly employer contributions. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import employer_match >>> # $45,000 salary, 50% match on the first 6%, contributing 6% or 3% >>> employer_match(salary=45000, contribution_pct=[0.06, 0.03], ... match_limit_pct=0.06, match_rate=0.50) array([1350., 675.]) after_tax_value(contribution: 'ArrayLike', tax_rate: 'ArrayLike', rate: 'ArrayLike', years: 'ArrayLike') -> 'Numeric' After tax value of a retirement contribution. Taxes the contribution once at `tax_rate`, then grows it. With the same rate and return, it doesn't matter whether the tax comes first (Roth) or last (Traditional); only the tax rate does. From the [Retirement Accounts](https://mjfrigaard.github.io/fm-finance/retirement_accounts.html) chapter. Parameters ---------- contribution Amount contributed. tax_rate Tax rate applied, as a decimal. rate Yearly return, as a decimal. years Number of years. Returns ------- float or numpy.ndarray After tax values. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import after_tax_value >>> # Roth at 12% today vs. Traditional at 22% in retirement >>> after_tax_value(contribution=1000, tax_rate=[0.12, 0.22], rate=0.07, ... years=40) array([13177.5228985 , 11680.07711458]) ## Index Funds Investing. Functions from the Index Funds chapter. yearly_fee(balance: 'ArrayLike', expense_ratio: 'ArrayLike') -> 'Numeric' Yearly fund fee from an expense ratio. From the [Index Funds](https://mjfrigaard.github.io/fm-finance/index_funds.html) chapter. Parameters ---------- balance Amount invested. expense_ratio Yearly expense ratio, as a decimal (`0.0004` is 0.04%). Returns ------- float or numpy.ndarray Yearly fees. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import yearly_fee >>> # $10,000 in an index fund vs. an active fund >>> yearly_fee(balance=10000, expense_ratio=[0.0004, 0.01]) array([ 4., 100.]) future_value_after_fees(contribution: 'ArrayLike', annual_return: 'ArrayLike', expense_ratio: 'ArrayLike', years: 'ArrayLike') -> 'Numeric' Future value of monthly contributions after fund fees. Subtracts the expense ratio from the yearly return, then compounds monthly contributions. From the [Index Funds](https://mjfrigaard.github.io/fm-finance/index_funds.html) chapter. Parameters ---------- contribution Amount contributed each month. annual_return Yearly return before fees, as a decimal. expense_ratio Yearly expense ratio, as a decimal. years Number of years. Returns ------- float or numpy.ndarray Future values. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import future_value_after_fees >>> # $300/month for 40 years at 7%, index fund vs. active fund >>> future_value_after_fees(300, 0.07, [0.0004, 0.01], 40) array([778654.71, 597447.22]) ## Asset Allocation Investing. Functions from the Asset Allocation chapter. portfolio_return(stock_pct: 'ArrayLike | pl.Expr', stock_return: 'ArrayLike | pl.Expr', bond_return: 'ArrayLike | pl.Expr') -> 'Any' Return on a two fund (stock and bond) portfolio. A weighted average of the two returns. Also accepts polars expressions, so it works inside `with_columns()`. From the [Asset Allocation](https://mjfrigaard.github.io/fm-finance/asset_allocation.html) chapter. Parameters ---------- stock_pct Share of the portfolio in stocks, as a decimal. stock_return Yearly stock return, as a decimal. bond_return Yearly bond return, as a decimal. Returns ------- float, numpy.ndarray, or polars.Expr Portfolio returns, as decimals. A polars expression when any input is one. Raises ------ TypeError If an argument is not numeric (or a polars expression). ValueError If an argument contains missing values. Examples -------- >>> import polars as pl >>> from perfinpy import portfolio_return >>> # an 80/20 portfolio in an average year >>> portfolio_return(stock_pct=0.80, stock_return=0.10, bond_return=0.04) 0.088 >>> # 100/0, 80/20, and 60/40 in a bad year >>> pl.DataFrame({"stocks": [1.0, 0.8, 0.6]}).with_columns( ... bad=portfolio_return(pl.col("stocks"), -0.40, 0.0) ... )["bad"].round(2).to_list() [-0.4, -0.32, -0.24] rebalance_amount(target_pct: 'ArrayLike', total: 'ArrayLike', current_amount: 'ArrayLike') -> 'Numeric' Amount to buy (positive) or sell (negative) to reach a target. From the [Asset Allocation](https://mjfrigaard.github.io/fm-finance/asset_allocation.html) chapter. Parameters ---------- target_pct Target share of the portfolio, as a decimal. total Total portfolio value. current_amount Current value of the holding. Returns ------- float or numpy.ndarray Amounts to buy (positive) or sell (negative). Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import rebalance_amount >>> # $5,600 in stocks and $2,000 in bonds after a 30% stock drop >>> rebalance_amount(target_pct=0.80, total=5600 + 2000, current_amount=5600) 480.0 ## Taxes Taxes and insurance. Functions from the Taxes chapter. income_tax(income: 'float', deduction: 'float' = 16100) -> 'float' Federal income tax for a single filer (2026 brackets). Subtracts the deduction, then taxes each slice of taxable income at its bracket's rate. Uses the 2026 single filer brackets and standard deduction. From the [Taxes](https://mjfrigaard.github.io/fm-finance/taxes.html) chapter. Parameters ---------- income Yearly gross income. A single number. deduction Deduction subtracted before tax. Defaults to 16100 (the 2026 standard deduction). A single number. Returns ------- float Tax owed. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values or is not a single number. See Also -------- raise_kept : How much of a raise you keep after tax. Examples -------- >>> from perfinpy import income_tax >>> income_tax(income=45000) 3220.0 >>> # effective rate >>> income_tax(income=45000) / 45000 0.0715 raise_kept(old_income: 'float', raise_amount: 'float') -> 'float' How much of a raise you keep after federal income tax. The raise minus the extra tax it adds, using `income_tax()`. From the [Taxes](https://mjfrigaard.github.io/fm-finance/taxes.html) chapter. Parameters ---------- old_income Yearly gross income before the raise. A single number. raise_amount Size of the raise. A single number. Returns ------- float Amount of the raise kept after tax. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values or is not a single number. See Also -------- income_tax : The tax calculation used here. Examples -------- >>> from perfinpy import raise_kept >>> # $2,000 raise on a $66,000 salary >>> raise_kept(old_income=66000, raise_amount=2000) 1610.0 ## Insurance Taxes and insurance. Functions from the Insurance chapter. break_even_years(high_deductible: 'ArrayLike', low_deductible: 'ArrayLike', yearly_savings: 'ArrayLike') -> 'Numeric' Years of premium savings to cover a higher deductible. If you go longer than this between claims, the higher deductible comes out ahead. From the [Insurance](https://mjfrigaard.github.io/fm-finance/insurance.html) chapter. Parameters ---------- high_deductible The higher deductible. low_deductible The lower deductible. yearly_savings Yearly premium saved by choosing the higher deductible. Must be greater than 0. Returns ------- float or numpy.ndarray Years. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `yearly_savings` is not greater than 0. Examples -------- >>> from perfinpy import break_even_years >>> break_even_years(high_deductible=1000, low_deductible=500, ... yearly_savings=150) 3.33 plan_cost(monthly_premium: 'ArrayLike', medical_cost: 'ArrayLike', oop_max: 'ArrayLike', employer_hsa: 'ArrayLike' = 0) -> 'Numeric' Yearly cost of a health plan. Twelve premiums plus what you pay for care (capped at the out of pocket maximum), minus any employer HSA contribution. Use `float("inf")` for `medical_cost` to get the worst case year. From the [Insurance](https://mjfrigaard.github.io/fm-finance/insurance.html) chapter. Parameters ---------- monthly_premium Monthly premium. medical_cost Medical costs for the year. oop_max Out of pocket maximum. employer_hsa Employer HSA contribution. Defaults to 0. Returns ------- float or numpy.ndarray Yearly costs. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import plan_cost >>> # Plan A in a healthy year ($300 of care) and the worst year >>> plan_cost(100, [300, float("inf")], oop_max=3000) array([1500., 4200.]) >>> # Plan B, with a $500 employer HSA contribution >>> plan_cost(40, [300, float("inf")], oop_max=5000, employer_hsa=500) array([ 280., 4980.]) ## Financial Goals Planning. Functions from the Financial Goals chapter. monthly_for_goal(goal: 'ArrayLike', annual_rate: 'ArrayLike', months: 'ArrayLike') -> 'Numeric' Monthly saving needed to reach a goal. Solves the future value of a series for the contribution, compounding monthly at `annual_rate / 12`. A 0% rate gives `goal / months`. From the [Financial Goals](https://mjfrigaard.github.io/fm-finance/financial_goals.html) chapter. Parameters ---------- goal Amount needed. annual_rate Yearly return on savings, as a decimal. months Months until the goal. Must be greater than 0. Returns ------- float or numpy.ndarray Monthly contributions. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `months` is not greater than 0. Examples -------- >>> from perfinpy import monthly_for_goal >>> # $15,000 in 5 years at 4%, compared to no interest >>> monthly_for_goal(goal=15000, annual_rate=[0.04, 0], months=60) array([226.24783083, 250. ]) months_to_fund(goal: 'ArrayLike', monthly: 'ArrayLike') -> 'Whole' Whole months to fund a goal with no interest. From the [Financial Goals](https://mjfrigaard.github.io/fm-finance/financial_goals.html) chapter. Parameters ---------- goal Amount needed. monthly Amount saved each month. Must be greater than 0. Returns ------- int or numpy.ndarray Whole months, rounded up. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `monthly` is not greater than 0. Examples -------- >>> from perfinpy import months_to_fund >>> # one at a time: a $3,000 trip, then a $9,000 car, at $600/month >>> months_to_fund(3000, 600), months_to_fund(3000 + 9000, 600) (5, 20) ## Major Purchases Planning. Functions from the Major Purchases chapter. rent_buy_threshold(home_value: 'ArrayLike', unrecoverable_rate: 'ArrayLike' = 0.05) -> 'Numeric' Monthly rent that matches the unrecoverable cost of owning. The 5% rule: property tax, maintenance, and the cost of capital come to about 5% of the home's value each year. Rent below this monthly amount favors renting. From the [Major Purchases](https://mjfrigaard.github.io/fm-finance/major_purchases.html) chapter. Parameters ---------- home_value Price of the home. unrecoverable_rate Yearly unrecoverable cost, as a decimal. Defaults to 0.05. Returns ------- float or numpy.ndarray Monthly rent thresholds. Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values. Examples -------- >>> from perfinpy import rent_buy_threshold >>> rent_buy_threshold(home_value=500000) 2083.33 mortgage_payment(principal: 'ArrayLike', annual_rate: 'ArrayLike', years: 'ArrayLike') -> 'Numeric' Monthly payment on a fixed rate loan. The standard amortization formula with monthly compounding. A 0% rate gives `principal / (years * 12)`. From the [Major Purchases](https://mjfrigaard.github.io/fm-finance/major_purchases.html) chapter. Parameters ---------- principal Amount borrowed. annual_rate Yearly interest rate, as a decimal. years Loan term in years. Must be greater than 0. Returns ------- float or numpy.ndarray Monthly payments (principal and interest only). Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values, or `years` is not greater than 0. See Also -------- first_payment_split : Interest and principal in the first payment. monthly_standard_payment : Student loan defaults. Examples -------- >>> from perfinpy import mortgage_payment >>> # $480,000 loan at 6% over 30 years >>> mortgage_payment(principal=480000, annual_rate=0.06, years=30) 2877.84 first_payment_split(principal: 'float', annual_rate: 'float', years: 'float') -> 'dict[str, float]' Interest and principal in a loan's first monthly payment. From the [Major Purchases](https://mjfrigaard.github.io/fm-finance/major_purchases.html) chapter. Parameters ---------- principal Amount borrowed. A single number. annual_rate Yearly interest rate, as a decimal. A single number. years Loan term in years. A single number greater than 0. Returns ------- dict Keys `payment`, `interest`, `principal`, and `pct_interest` (the share of the payment that is interest, as a percent). Raises ------ TypeError If an argument is not numeric. ValueError If an argument contains missing values or is not a single number, or `years` is not greater than 0. See Also -------- mortgage_payment : The payment formula used here. Examples -------- >>> from perfinpy import first_payment_split >>> split = first_payment_split(principal=480000, annual_rate=0.06, years=30) >>> {k: round(v, 2) for k, v in split.items()} {'payment': 2877.84, 'interest': 2400.0, 'principal': 477.84, 'pct_interest': 83.4} ## Estate Planning Planning. Functions from the Estate Planning chapter. net_worth(assets: 'Mapping[str, float] | ArrayLike', debts: 'Mapping[str, float] | ArrayLike') -> 'float' Net worth: total assets minus total debts. From the [Estate Planning](https://mjfrigaard.github.io/fm-finance/estate_planning.html) chapter. Parameters ---------- assets Asset values, as a dict of name to amount or a sequence of amounts. debts Debt balances, as a dict of name to amount or a sequence of amounts. Returns ------- float Net worth. Raises ------ TypeError If a value is not numeric. ValueError If a value is missing. Examples -------- >>> from perfinpy import net_worth >>> assets = {"401k": 12000, "roth_ira": 6000, "savings": 8000, "car": 9000} >>> debts = {"car_loan": 6000, "credit_card": 1000} >>> net_worth(assets, debts) 28000.0 beneficiary_share(with_beneficiary: 'Mapping[str, float] | ArrayLike', without_beneficiary: 'Mapping[str, float] | ArrayLike') -> 'float' Share of assets that pass directly to a named beneficiary. Assets with a beneficiary (retirement accounts, life insurance, payable on death accounts) skip probate. From the [Estate Planning](https://mjfrigaard.github.io/fm-finance/estate_planning.html) chapter. Parameters ---------- with_beneficiary Values of assets with a named beneficiary, as a dict or a sequence. without_beneficiary Values of assets without one, as a dict or a sequence. Returns ------- float Share, as a decimal (`0.8875` is 88.75%). Raises ------ TypeError If a value is not numeric. ValueError If a value is missing, or total assets are not greater than 0. Examples -------- >>> from perfinpy import beneficiary_share >>> with_beneficiary = {"401k": 12000, "roth_ira": 6000, ... "life_insurance": 45000, "savings_pod": 8000} >>> beneficiary_share(with_beneficiary, {"car": 9000}) 0.8875 ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ## Get started ### Get started ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` `perfinpy` holds the Python functions from [Personal Finance: a field manual](https://mjfrigaard.github.io/fm-finance/). Each chapter of the book builds its calculations from scratch so you can see how the formula works. This package collects those same functions, documents them, and tests them, so you can use them without copying code out of the book. On this page I'll cover how to install `perfinpy` and the conventions every function follows. Then we'll take a short tour with one example from each part of the book. ## Installation `perfinpy` isn't on PyPI. Install the development version from GitHub: ```bash uv pip install git+https://github.com/mjfrigaard/perfinpy ``` `perfinpy` depends on `numpy` and `polars`. If you work in R, the same functions are in [perfinr](https://mjfrigaard.github.io/perfinr/). ## Conventions The functions keep the names, arguments, and defaults from the book, so code from a chapter runs unchanged after `from perfinpy import *`. A few rules hold across the whole package: | Rule | Example | |---|---| | Rates and returns are decimals | `0.07` is 7% | | The one exception is `rule_of_72()`, which takes a percent | `rule_of_72(7)` | | Ratio functions return percents | `percent_of_income(1500, 5000)` returns `30.0`, not `0.30` | | Two ratios stay decimals, as in the book | `loan_income_ratio()` (`1.07`) and `beneficiary_share()` (`0.8875`) | | Most functions accept arrays | `future_value(10000, 0.07, [10, 20])` returns a `numpy` array | | Single numbers in, a `float` out | `future_value(10000, 0.07, 10)` returns a `float` | | A few functions take single values only | `income_tax()`, `raise_kept()`, `payoff_vs_invest()`, `first_payment_split()` | | A 0% rate returns the no interest answer | `mortgage_payment(120000, 0, 30)` is `120000 / 360` | | Bad inputs raise an error | text raises `TypeError`; `nan`, or a zero where a divisor is needed, raises `ValueError` | Array inputs make it easy to compare options side by side. Here is the same \$10,000 at 7% over four horizons: ```{python} #| label: vectorized years = [5, 10, 20, 30] pl.DataFrame({ "years": years, "value": future_value(present_value=10000, rate=0.07, years=years), }) ``` When an input doesn't make sense, the function says which argument is wrong instead of returning `inf` or `nan`: ```{python} #| label: error #| error: true percent_of_income(expense=1500, income=0) ``` ## How the user guide maps to the book There is one page for each chapter of the book. Each one takes the chapter's examples (with the same numbers), shows the bar model, and then answers the question with perfinpy functions. ```{mermaid} %%| fig-width: 7 %%{init: {'theme': 'base', 'themeVariables': { 'fontFamily': 'monospace', "darkMode":false}}}%% flowchart TD Book(["Personal Finance: a field manual"]) subgraph Foundations["Foundations"] F1("Income") F2("Tracking Spending") F3("Budgeting") F4("Managing Debt") F5("Emergency Fund") end subgraph Savings["Savings"] S1("Savings Strategies") S2("High-Yield Savings Accounts") S3("Automating Savings") end subgraph Investing["Investing"] I1("Investing Basics") I2("Retirement Accounts") I3("Index Funds") I4("Asset Allocation") end subgraph TaxIns["Taxes and insurance"] T1("Taxes") T2("Insurance") end subgraph Planning["Planning"] P1("Financial Goals") P2("Major Purchases") P3("Estate Planning") end Book --> Foundations Book --> Savings Book --> Investing Book --> TaxIns Book --> Planning style Book fill:#FFFFFF,color:#000000,stroke:#333 style Foundations fill:#FFFFFF,color:#000000,stroke:#999 style Savings fill:#FFFFFF,color:#000000,stroke:#999 style Investing fill:#FFFFFF,color:#000000,stroke:#999 style TaxIns fill:#FFFFFF,color:#000000,stroke:#999 style Planning fill:#FFFFFF,color:#000000,stroke:#999 style F1 fill:#0072B2,color:#FFFFFF,rx:5,ry:5 style F2 fill:#0072B2,color:#FFFFFF,rx:5,ry:5 style F3 fill:#0072B2,color:#FFFFFF,rx:5,ry:5 style F4 fill:#0072B2,color:#FFFFFF,rx:5,ry:5 style F5 fill:#0072B2,color:#FFFFFF,rx:5,ry:5 style S1 fill:#009E73,color:#FFFFFF,rx:5,ry:5 style S2 fill:#009E73,color:#FFFFFF,rx:5,ry:5 style S3 fill:#009E73,color:#FFFFFF,rx:5,ry:5 style I1 fill:#56B4E9,color:#000000,rx:5,ry:5 style I2 fill:#56B4E9,color:#000000,rx:5,ry:5 style I3 fill:#56B4E9,color:#000000,rx:5,ry:5 style I4 fill:#56B4E9,color:#000000,rx:5,ry:5 style T1 fill:#E69F00,color:#000000,rx:5,ry:5 style T2 fill:#E69F00,color:#000000,rx:5,ry:5 style P1 fill:#D55E00,color:#FFFFFF,rx:5,ry:5 style P2 fill:#D55E00,color:#FFFFFF,rx:5,ry:5 style P3 fill:#D55E00,color:#FFFFFF,rx:5,ry:5 ``` ## A short tour Each example below uses the numbers from the book, so you can check the result against the chapter. ### Foundations Rent of \$1,500 on a \$5,000 monthly income: ```{python} #| label: tour-foundations rent_share = percent_of_income(expense=1500, income=5000) rent_share ``` Rent takes `{python} f"{rent_share:.0f}"`% of income. A \$5,000 credit card balance at 22% APR, paying \$100 a month: ```{python} #| label: tour-debt payoff = months_to_payoff(balance=5000, monthly_payment=100, apr=0.22) payoff ``` That is about `{python} f"{payoff / 12:.1f}"` years of payments. ### Savings Spending \$2,720 of a \$3,200 take home paycheck: ```{python} #| label: tour-savings savings_rate(income=3200, spending=2720) ``` ### Investing \$10,000 invested at 7% for 10 years: ```{python} #| label: tour-investing future_value(present_value=10000, rate=0.07, years=10) ``` ### Taxes and insurance 2026 federal income tax on a \$45,000 salary (single filer), and the effective rate: ```{python} #| label: tour-taxes tax = income_tax(income=45000) tax, tax / 45000 ``` The effective rate is `{python} f"{tax / 45000 * 100:.1f}"`%, well below the 12% top bracket this salary reaches. ### Planning The monthly payment on a \$480,000 mortgage at 6% over 30 years: ```{python} #| label: tour-planning mortgage_payment(principal=480000, annual_rate=0.06, years=30) ``` ## Recap perfinpy gives you the book's functions as a tested package. Rates go in as decimals, ratios come out as percents, and most functions accept arrays so you can compare options in one call. The chapter pages walk through each part of the book in the same order as the chapters. Foundations: * [Income](01-income.qmd) * [Tracking Spending](02-tracking-spending.qmd) * [Budgeting](03-budgeting.qmd) * [Managing Debt](04-managing-debt.qmd) * [Emergency Fund](05-emergency-fund.qmd) Savings: * [Savings Strategies](06-savings-strategies.qmd) * [High-Yield Savings Accounts](07-high-yield-accounts.qmd) * [Automating Savings](08-automating-savings.qmd) Investing: * [Investing Basics](09-investing-basics.qmd) * [Retirement Accounts](10-retirement-accounts.qmd) * [Index Funds](11-index-funds.qmd) * [Asset Allocation](12-asset-allocation.qmd) Taxes and insurance: * [Taxes](13-taxes.qmd) * [Insurance](14-insurance.qmd) Planning: * [Financial Goals](15-financial-goals.qmd) * [Major Purchases](16-major-purchases.qmd) * [Estate Planning](17-estate-planning.qmd) ## Foundations ### Income ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` A bigger paycheck only builds wealth if some of it stays put. The book's [Income](https://mjfrigaard.github.io/fm-finance/income.html) chapter turns that idea into three questions. How much does steady saving grow into? How much of each paycheck is committed before you spend a dollar? And what is a raise worth if you invest part of it? In this page I'll answer each one with `perfinpy`, using the same numbers as the chapter. | Function | Returns | Units | |---|---|---| | `wealth_formula()` | the balance after saving part of a yearly income every year | dollars; rates go in as decimals | | `fixed_cost_ratio()` | monthly fixed costs as a share of take home pay | percent (`55`, not `0.55`) | | `raise_invested_value()` | the balance after investing part of a monthly raise every month | dollars; rates go in as decimals | The units follow the package conventions described in [Get started](00-get-started.qmd): rates go in as decimals and ratios come out as percents. ## How much does steady saving grow into? The chapter builds on Scott Galloway's wealth formula (focus plus stoicism, time, and diversification multiplied together). To put numbers on it, the book uses a worker who earns about the 2025 median for full time workers. This worker saves a fixed share of income every year and invests it. The scenario below sets those inputs: ```{python} #| label: wealth-scenario income = 62400 save_pct = 0.15 annual_return = 0.08 wealth_years = 40 ``` This worker earns \$`{python} f"{income:,}"` a year and saves `{python} f"{save_pct * 100:.0f}"`% of it, which comes to \$`{python} f"{income * save_pct:,.0f}"` a year. Those savings earn `{python} f"{annual_return * 100:.0f}"`% a year for `{python} wealth_years` years. Each bar below is the balance at a checkpoint, split into the money put in and what it grew into. ![Money put in vs. growth at each checkpoint](assets/income-wealth-bar-model.png){fig-alt="Stacked bar chart of savings at years 10, 20, 30, and 40 from depositing $9,360 a year at 8%. Each bar splits into money put in (green, bottom) and growth (blue, top). The bar totals are $136k, $428k, $1,060k, and $2,425k. Growth is the smaller layer at year 10 and fills most of the bar by year 40."} The green layer rises in a straight line because it is one deposit per year. The blue layer is every deposit growing for the years it has left, and it is the part that takes over. `wealth_formula()` adds up all of those growing deposits in one call: ```{python} #| label: wealth-40 wealth_40 = wealth_formula( median_income=income, savings_rate=save_pct, annual_return=annual_return, years=wealth_years, ) wealth_40 ``` After `{python} wealth_years` years the balance is about \$`{python} f"{wealth_40:,.0f}"`. Only \$`{python} f"{income * save_pct * wealth_years:,.0f}"` of that is money the worker put in; the other \$`{python} f"{wealth_40 - income * save_pct * wealth_years:,.0f}"` is growth. ## How much of your paycheck is already spoken for? Fixed costs (rent, loan payments, insurance, utilities) are the bills you can't easily change from one month to the next. The book's example is a first job with these monthly numbers: ```{python} #| label: fixed-scenario fixed_costs = 1760 take_home = 3200 ceiling_pct = 60 ``` This paycheck brings in \$`{python} f"{take_home:,}"` of take home pay a month, and \$`{python} f"{fixed_costs:,}"` of it goes to fixed costs. The book suggests keeping fixed costs under `{python} ceiling_pct`% of take home pay, which is \$`{python} f"{take_home * ceiling_pct / 100:,.0f}"` here. The bar below cuts the paycheck into ten equal pieces and marks that ceiling. ![Take home pay split into fixed costs and flexible spending](assets/income-fixed-cost-bar-model.png){fig-alt="Bar model: one horizontal bar for $3,200 of take home pay, divided by white lines into ten $320 pieces. Fixed costs of $1,760 (vermillion) fill five and a half pieces, and flexible spending of $1,440 (light green) fills the rest. A dashed line marks the 60% ceiling at $1,920, just to the right of where fixed costs end."} `fixed_cost_ratio()` divides the fixed costs by take home pay and returns a percent: ```{python} #| label: fixed-ratio ratio = fixed_cost_ratio(fixed_costs=fixed_costs, take_home=take_home) ratio ``` Fixed costs take `{python} f"{ratio:g}"`% of this paycheck, under the `{python} ceiling_pct`% ceiling. That leaves \$`{python} f"{take_home * ceiling_pct / 100 - fixed_costs:,.0f}"` of room before a new commitment pushes the budget past it. The [Budgeting](03-budgeting.qmd) page picks up from here and splits the flexible part of the paycheck. ## What is a raise really worth? The chapter recommends splitting every raise: half goes to your lifestyle and half gets invested. The book's raise adds a fixed amount to monthly take home pay: ```{python} #| label: raise-scenario monthly_raise = 400 share = 0.5 raise_rate = 0.07 raise_years = 25 ``` A raise of \$`{python} f"{monthly_raise:,}"` a month split in half sends \$`{python} f"{monthly_raise * share:,.0f}"` a month into investments. That money earns `{python} f"{raise_rate * 100:.0f}"`% a year for `{python} raise_years` years. The bars below show the balance at each checkpoint. ![A monthly raise contribution invested at each checkpoint](assets/income-raise-value-bar-model.png){fig-alt="Stacked bar chart of $200 a month invested at a 7% annual return, at years 5, 10, 15, 20, and 25. Each bar splits into money put in (green, bottom) and growth (blue, top). The bar totals are $14k, $35k, $63k, $104k, and $162k. By year 25 the growth layer is larger than the money put in."} `raise_invested_value()` takes the whole raise and the share you invest, then compounds the contributions monthly: ```{python} #| label: raise-value raise_value = raise_invested_value( monthly_raise=monthly_raise, invest_share=share, rate=raise_rate, years=raise_years, ) raise_value ``` Half of the raise grows to about \$`{python} f"{raise_value:,.0f}"`. The contributions add up to \$`{python} f"{monthly_raise * share * 12 * raise_years:,.0f}"`, so growth adds about \$`{python} f"{raise_value - monthly_raise * share * 12 * raise_years:,.0f}"`. The [Investing Basics](09-investing-basics.qmd) page returns to this future value of contributions formula with `future_value_series()`. ## Variations Both growth functions accept arrays, so we can compare options in one call. The savings rate is the stoicism lever in Galloway's formula. The code below keeps the income, return, and horizon from the first section and changes only the share saved: ```{python} #| label: variations-savings-rate rates = [0.10, 0.15, 0.20] pl.DataFrame({ "savings_rate": rates, "yearly_savings": [income * r for r in rates], "wealth": wealth_formula( median_income=income, savings_rate=rates, annual_return=annual_return, years=wealth_years, ), }) ``` The same idea works for the raise. Here is the \$`{python} f"{monthly_raise:,}"` raise with a quarter, half, three quarters, and all of it invested: ```{python} #| label: variations-raise-share shares = [0.25, 0.50, 0.75, 1.0] pl.DataFrame({ "invest_share": shares, "per_month": [monthly_raise * s for s in shares], "value": raise_invested_value( monthly_raise=monthly_raise, invest_share=shares, rate=raise_rate, years=raise_years, ), }) ``` Both tables scale in a straight line with the share saved because the return and horizon don't change. The horizon is where the curve bends, as the bar models above show. ::: {.callout-warning title="Limits"} * `wealth_formula()` assumes one deposit at the end of every year, the same income every year (no raises), and the same return every year. It ignores taxes, fees, and inflation, so results are in future dollars. * `raise_invested_value()` makes the same assumptions with a deposit at the end of every month and monthly compounding. * A 0% return in either function gives the plain sum of the deposits instead of `nan`. * `fixed_cost_ratio()` raises a `ValueError` when `take_home` is 0 or negative. It doesn't decide which bills count as fixed, and the 60% ceiling is a guideline from the book, not an argument. * The growth functions reject text and `nan` but not negative values, so check the signs of your inputs. ::: ## Putting it together The worker from the fixed cost section gets the \$`{python} f"{monthly_raise:,}"` raise. Investing half is the easy part; the real question is where the lifestyle half goes. If it stays flexible (dinners, trips), fixed costs don't change. If it goes to a pricier apartment, fixed costs rise by the full lifestyle half. The code below compares the fixed cost ratio before the raise and under both choices: ```{python} #| label: together-ratio new_take_home = take_home + monthly_raise plans = pl.DataFrame({ "plan": [ "before the raise", "lifestyle half stays flexible", "lifestyle half goes to rent", ], "fixed_costs": [ float(fixed_costs), float(fixed_costs), fixed_costs + monthly_raise * (1 - share), ], "take_home": [take_home, new_take_home, new_take_home], }) plans = plans.with_columns( ratio=fixed_cost_ratio( fixed_costs=plans["fixed_costs"].to_numpy(), take_home=plans["take_home"].to_numpy(), ) ) plans ``` Keeping the lifestyle half flexible drops the ratio to `{python} f"{plans['ratio'][1]:.1f}"`%. Moving it into rent leaves the ratio at `{python} f"{plans['ratio'][2]:.1f}"`%, almost where it started, so the raise buys very little breathing room. This is the lifestyle inflation the chapter warns about: the upgrade becomes a permanent bill. The invested half grows the same way in both plans. The code below values it twice: once with monthly deposits, and once with a single deposit at the end of each year. The yearly version uses `wealth_formula()`, whose `median_income` argument accepts any yearly amount: ```{python} #| label: together-invest monthly_value = raise_invested_value( monthly_raise=monthly_raise, invest_share=share, rate=raise_rate, years=raise_years, ) yearly_value = wealth_formula( median_income=monthly_raise * 12, savings_rate=share, annual_return=raise_rate, years=raise_years, ) monthly_value, yearly_value ``` The same dollars come out about \$`{python} f"{monthly_value - yearly_value:,.0f}"` ahead when they're invested every month. Each monthly deposit starts growing sooner, which is one more reason to automate the transfer the day the raise arrives. ## Recap `wealth_formula()` and `raise_invested_value()` show how a steady deposit turns into a balance that is mostly growth. Time does more of the work than the deposits do. `fixed_cost_ratio()` tells you how much of each paycheck is committed before you spend anything, and returns a percent you can compare against the `{python} ceiling_pct`% ceiling. Together they make the chapter's advice measurable: keep fixed costs low, and invest part of every raise before your lifestyle absorbs it. * [Income](https://mjfrigaard.github.io/fm-finance/income.html) in Personal Finance: a field manual * Reference: `wealth_formula()`, `fixed_cost_ratio()`, `raise_invested_value()` * Next: [Tracking Spending](02-tracking-spending.qmd) ### Tracking Spending ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` A bank export tells you every dollar that left your account, but it doesn't tell you where your money went. To answer that, each transaction needs a category, and the small recurring charges need a second look. The [Tracking Spending](https://mjfrigaard.github.io/fm-finance/tracking_spending.html) chapter of the book covers both questions. In this page I'll answer them with two perfinpy functions. `apply_rules()` sorts transactions into buckets. `subscription_opportunity_cost()` shows what a subscription would have grown to if you had invested the money instead. | Function | Returns | Units | |---|---|---| | `apply_rules()` | the transactions with a `Category` column added | text categories; `"Other"` when nothing matches | | `subscription_opportunity_cost()` | what the yearly cost grows to if invested | dollars; `rate` is a decimal (`0.07` is 7%) | ## Where did the money go? The book starts with a January 2026 bank export. It has the three columns most banks include: `Date`, `Description`, and `Amount` (negative for money going out, positive for money coming in). The code below builds the same statement as a `polars` DataFrame: ```{python} #| label: bank-statement bank_statement = pl.DataFrame({ "Date": [ "2026-01-02", "2026-01-02", "2026-01-03", "2026-01-03", "2026-01-04", "2026-01-04", "2026-01-05", "2026-01-06", "2026-01-07", "2026-01-08", "2026-01-09", "2026-01-10", "2026-01-11", "2026-01-12", "2026-01-13", "2026-01-14", "2026-01-15", ], "Description": [ "Employer Payroll", "Rent", "Comcast Internet", "Trader Joe's", "Shell Gas", "Netflix", "Starbucks", "PG&E Electric", "AT&T Wireless", "Spotify", "Whole Foods", "Chipotle", "Geico Auto Insurance", "NYTimes Digital", "Shell Gas", "Costco", "24 Hour Fitness", ], "Amount": [ 2400.00, -1500.00, -75.00, -82.45, -45.20, -15.99, -6.75, -142.30, -85.00, -10.99, -64.12, -14.50, -125.00, -17.00, -42.80, -156.78, -39.99, ], }).with_columns(pl.col("Date").str.to_date()) ``` The statement has `{python} bank_statement.height` transactions and no `Category` column. To add one, we map each description to a bucket with a lookup table of keyword patterns. Each `Pattern` is a regular expression (a text search pattern), so `|` means "or" and one rule can cover several merchants: ```{python} #| label: rules rules = pl.DataFrame({ "Pattern": ["Payroll", "Rent", "Comcast|PG&E|AT&T", "Trader Joe|Whole Foods|Costco", "Shell", "Starbucks|Chipotle", "Netflix|Spotify|NYTimes|24 Hour Fitness", "Geico"], "Category": ["Income", "Housing", "Utilities", "Groceries", "Transportation", "Dining", "Subscriptions", "Insurance"], }) ``` `apply_rules()` checks the `{python} rules.height` rules in order against each description and keeps the first match. The table below shows each transaction next to the bucket it landed in: ```{python} #| label: categorize categorized = apply_rules(df=bank_statement, rules=rules) categorized.select("Description", "Amount", "Category") ``` Every transaction found a bucket, so nothing fell through to `"Other"`. With a `Category` column in place, the tracking questions from the book become one line of `polars`. The code below totals each category: ```{python} #| label: category-totals totals = categorized.group_by("Category").agg(pl.col("Amount").sum()).sort("Category") totals ``` ```{python} #| label: subs-total #| include: false subs_total = -totals.filter(pl.col("Category") == "Subscriptions")["Amount"][0] ``` Subscriptions took \$`{python} f"{subs_total:,.2f}"` in the first half of January. That total is small next to rent, but it repeats every month, which is why the next section looks at it more closely. ### When a transaction doesn't match New merchants show up every month. The book's rule is "when in doubt, Other." A transaction that matches no pattern lands in `"Other"` until you've seen it often enough to deserve its own rule. The code below runs two new transactions through the same rules: ```{python} #| label: unmatched new_transactions = pl.DataFrame({ "Description": ["Venmo Payment", "SPOTIFY FAMILY PLAN"], }) apply_rules(df=new_transactions, rules=rules) ``` The Venmo payment falls through to `"Other"`. The Spotify charge still lands in `"Subscriptions"` because `apply_rules()` ignores case, so `"Spotify"` matches `"SPOTIFY"`. ## What does a subscription really cost? A subscription's real cost is its opportunity cost: the money you give up by spending instead of investing. The book's example is a monthly subscription you don't really use, with the money invested instead at a real return (the return after inflation). The code below stores the book's inputs: ```{python} #| label: subscription-inputs monthly_cost = 20 years = 30 rate = 0.07 ``` Canceling the \$`{python} monthly_cost` a month subscription frees up \$`{python} f"{monthly_cost * 12:,}"` a year to invest at `{python} f"{rate * 100:.0f}"`% for `{python} years` years. The chart below shows what that money grows into at each checkpoint, split into the money you put in and the growth it earned. ![\$240 a year invested at 7% instead of a \$20/month subscription](assets/tracking-spending-subscription-bar-model.png){fig-alt="Stacked bar chart of $240 a year invested at 7%, with bars at years 1, 5, 10, 20, and 30. Each bar splits into money put in (bluish green, bottom) and growth (vermillion, top). The totals are $240, $1,380, $3,316, $9,839, and $22,671. Growth is a thin sliver at year 5, about equal to the money put in at year 20, and roughly twice the money put in at year 30."} Each bar adds another year's deposit to everything saved so far, and the whole pile grows by 7%. `subscription_opportunity_cost()` adds up every year's deposit and its growth in one step: ```{python} #| label: subscription-cost sub_cost = subscription_opportunity_cost( monthly_cost=monthly_cost, years=years, rate=rate, ) sub_cost ``` Over `{python} years` years you put in \$`{python} f"{monthly_cost * 12 * years:,}"`, and growth adds \$`{python} f"{sub_cost - monthly_cost * 12 * years:,.0f}"` on top of it. That "small" \$`{python} monthly_cost` a month is a \$`{python} f"{sub_cost:,.0f}"` decision. ## Comparing horizons `subscription_opportunity_cost()` accepts arrays, so one call can fill in every bar of the chart above. The code below puts the five checkpoints in a `pl.DataFrame` with the money put in and the growth: ```{python} #| label: subscription-years checkpoints = [1, 5, 10, 20, 30] horizons = pl.DataFrame({ "years": checkpoints, "put_in": [monthly_cost * 12 * y for y in checkpoints], "value": subscription_opportunity_cost(monthly_cost, checkpoints, rate).round(2), }).with_columns(growth=pl.col("value") - pl.col("put_in")) horizons ``` Growth is \$`{python} f"{horizons['growth'][1]:,.0f}"` after `{python} checkpoints[1]` years and \$`{python} f"{horizons['growth'][4]:,.0f}"` after `{python} checkpoints[4]`. Most of the cost of a subscription shows up late, which is exactly when you've stopped noticing the charge. ::: {.callout-warning title="Limits"} * `apply_rules()`: the first matching rule wins, so put specific patterns above general ones. Patterns are regular expressions with case ignored, so characters like `.`, `+`, and `(` have special meanings. The function only reads `Description`; a Netflix refund lands in `"Subscriptions"` just like the charge. An existing `Category` column is replaced. Both arguments must be `polars` DataFrames. * `subscription_opportunity_cost()`: it invests the yearly total once, at the end of each year, at one fixed rate. The book's \$267,000 figure for \$219 a month assumes monthly deposits, so it comes out higher than this function's result for the same inputs. The 7% default is a real return, so the result is in today's dollars. It does not reject negative costs. ::: ## Putting it together The book's monthly review ends with a subscription audit: list every recurring charge and decide whether it's worth the cost. The categorized statement already holds that list. The code below pulls the subscription rows and prices each one over the same horizon: ```{python} #| label: subscription-audit subs = categorized.filter(pl.col("Category") == "Subscriptions") monthly = -subs["Amount"] audit = pl.DataFrame({ "Description": subs["Description"], "monthly": monthly, "cost_30": subscription_opportunity_cost(monthly.to_numpy(), years=years).round(2), }) audit ``` These `{python} audit.height` subscriptions cost \$`{python} f"{audit['monthly'].sum():,.2f}"` a month, which adds up to \$`{python} f"{audit['cost_30'].sum():,.0f}"` over `{python} years` years. To put the monthly total in context, `percent_of_income()` from the [Budgeting](03-budgeting.qmd) page compares it with the paycheck on the statement: ```{python} #| label: subscription-share paycheck = categorized.filter(pl.col("Category") == "Income")["Amount"][0] subs_share = percent_of_income(expense=audit["monthly"].sum(), income=paycheck) subs_share ``` ```{python} #| label: gym-cost #| include: false gym_cost = audit.filter(pl.col("Description") == "24 Hour Fitness")["cost_30"][0] ``` Subscriptions take about `{python} f"{subs_share:.1f}"`% of the paycheck. As in the rest of perfinpy, the ratio comes out as a percent, not a decimal (see the conventions in [Get started](00-get-started.qmd)). The gym membership alone accounts for \$`{python} f"{gym_cost:,.0f}"` of the `{python} years` year total. That makes it the first one to check against the book's audit question: have you used it in the last 30 days? ## Recap `apply_rules()` turns a bank export into categorized spending with a small, stable table of keyword patterns, and anything new falls through to `"Other"`. `subscription_opportunity_cost()` puts a price on recurring charges by showing what the money would grow to if invested. Together they cover the recording side of personal finance, which feeds the allocation decisions in [Budgeting](03-budgeting.qmd). * [Tracking Spending](https://mjfrigaard.github.io/fm-finance/tracking_spending.html) in Personal Finance: a field manual * Reference: `apply_rules()`, `subscription_opportunity_cost()`, `percent_of_income()` * Next: [Budgeting](03-budgeting.qmd) ### Budgeting ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Most budgeting decisions come down to a handful of small calculations. You need to know how big a slice of your paycheck an expense takes and what a daily habit costs over a year. You also need to know what money spent today could have grown into, and how long an upfront purchase takes to pay for itself. The [Budgeting](https://mjfrigaard.github.io/fm-finance/budgeting.html) chapter of the book builds each of these from scratch. In this page I'll answer the same questions with `percent_of_income()`, `to_annual()`, `to_monthly()`, `opportunity_cost()`, and `months_to_break_even()`, using the chapter's numbers so you can check every result against the book. ## The budgeting functions All five functions accept arrays, and they follow the conventions in [Get started](00-get-started.qmd): rates go in as decimals and ratios come out as percents. | Function | Returns | Units | |---|---|---| | `percent_of_income()` | an expense as a share of income | percent (`30` is 30%) | | `to_annual()` | a daily, weekly, or monthly amount per year | dollars per year | | `to_monthly()` | a daily, weekly, or annual amount per month | dollars per month | | `opportunity_cost()` | what an amount could grow to if invested | dollars (`rate` is a decimal) | | `months_to_break_even()` | months until savings cover an upfront cost | months, not rounded | ## What share of income does an expense take? The chapter's first job example takes home \$3,200 a month and pays \$960 in rent. The question is how much of that paycheck rent claims. Think of the monthly take home pay as a single bar. Rent is one slice of it, and the rest of the bar is what's left for everything else: ![Rent (\$960) as a share of \$3,200 take home pay](assets/budgeting-pct-bar-model.png){fig-alt="Bar model: one horizontal bar for $3,200 of monthly take home pay, split into a vermillion slice labeled Rent $960 and a bluish green slice labeled Remaining $2,240. The rent slice covers just under a third of the bar."} `percent_of_income()` divides the width of the slice by the width of the whole bar, then multiplies by 100: ```{python} #| label: rent-share rent_share = percent_of_income(expense=960, income=3200) rent_share ``` Rent takes `{python} f"{rent_share:g}"`% of take home pay. The result is a percent, not a decimal, so `30` means 30% (see the conventions table in [Get started](00-get-started.qmd)). The expense and the income need to cover the same period. A monthly rent against a yearly salary gives a share that is off by a factor of 12. ## What does a small habit cost over a year? A \$5 daily coffee doesn't feel expensive, because you only ever pay \$5 at a time. The same habit looks very different at longer time scales: ![The same \$5 a day habit across four time periods](assets/budgeting-annual-bar-model.png){fig-alt="Bar chart of the same $5 a day coffee habit at four time scales: daily $5, weekly $35, monthly $152, and annual $1,825. The annual bar towers over the other three, which barely rise above zero."} Each bar is the one before it scaled by the number of periods it contains. `to_annual()` makes the daily to yearly jump in one step: ```{python} #| label: coffee-annual coffee_year = to_annual(amount=5, period="daily") coffee_year ``` The coffee habit costs \$`{python} f"{coffee_year:,.0f}"` a year. Suddenly it's a real number you can evaluate. ### Most budgets work in months `to_monthly()` goes in the other direction. It converts a daily, weekly, or annual amount to a monthly one, which is the unit most budgets use. Here is the coffee habit per month: ```{python} #| label: coffee-monthly coffee_month = to_monthly(amount=5, period="daily") coffee_month ``` Coffee runs \$`{python} f"{coffee_month:,.2f}"` a month, which matches the monthly bar above. The chapter's second example converts \$150 a week in groceries to a monthly amount: ```{python} #| label: groceries-monthly groceries_month = to_monthly(amount=150, period="weekly") groceries_month ``` Groceries come to \$`{python} f"{groceries_month:,.2f}"` a month. That is more than four weeks' worth, because a month holds about 4.33 weeks. ## What could the money have become? The chapter frames opportunity cost with a car. Buying a used one for \$15,000 instead of a new one for \$40,000 frees up \$25,000, which the chapter invests at 7% a year. Every dollar spent isn't just that dollar; it's what that dollar could have become. ![\$25,000 invested at 7%: value at each checkpoint](assets/budgeting-opp-cost-bar-model.png){fig-alt="Bar chart of $25,000 invested at 7% a year, with bluish green bars at year 0 ($25,000), year 5 ($35,064), year 10 ($49,179), year 20 ($96,742), and year 30 ($190,306). Each bar is taller than the last, and the gaps between them widen over time."} Each year multiplies the previous bar by 1.07. `opportunity_cost()` compounds the amount over the full horizon, with the rate as a decimal: ```{python} #| label: car-gap car_gap = opportunity_cost(amount=25000, rate=0.07, years=30) car_gap ``` After 30 years, the \$25,000 gap grows to about \$`{python} f"{car_gap:,.0f}"`. That's not a car payment difference; that's a retirement chapter. ## When does an upfront cost pay for itself? Some purchases cost money now to save money later: a membership, a better phone plan, or a used bike for commuting. The chapter's example is a \$500 membership that saves \$60 a month. ![\$60 a month in savings accumulating toward a \$500 upfront cost](assets/budgeting-break-even-bar-model.png){fig-alt="Bar chart of cumulative savings at $60 a month over 10 months, rising from $60 in month 1 to $600 in month 10, with a dashed vermillion line marking the $500 upfront cost. Months 1 through 8 are bluish green and sit below the line; months 9 and 10 are blue and rise above it."} Each month the cumulative savings bar grows by \$60, and break even is the first month that bar crosses the \$500 line. `months_to_break_even()` divides the upfront cost by the monthly savings: ```{python} #| label: membership import math be_months = months_to_break_even(upfront_cost=500, monthly_savings=60) be_months ``` The membership pays for itself after `{python} f"{be_months:.1f}"` months. The result isn't rounded. Use `math.ceil()` to find the first whole month you come out ahead: month `{python} math.ceil(be_months)`, the first bar above the line in the bar model. If you'll keep the membership longer than that, it's worth the upfront cost. ## Variations Array inputs let one call answer several versions of the same question. The chapter's periodic expenses are a good example. Setting aside one twelfth of each annual cost every month builds a sinking fund (money saved each month for a known future expense). `to_monthly()` converts every expense at once: ```{python} #| label: sinking-funds sinking = pl.DataFrame({ "expense": ["car insurance", "gifts", "car maintenance", "vacation"], "annual": [1200, 600, 1200, 2400], }) sinking = sinking.with_columns( monthly=to_monthly(amount=sinking["annual"].to_numpy(), period="annual") ) sinking ``` Together these periodic expenses need \$`{python} f"{sinking['monthly'].sum():,.0f}"` a month. When a bill arrives, the money is already there. ### One call compares every time horizon The same approach works for time horizons. Passing several values to `years` reproduces each checkpoint in the car bar model: ```{python} #| label: car-gap-horizons horizons = [0, 5, 10, 20, 30] pl.DataFrame({ "years": horizons, "value": opportunity_cost(amount=25000, rate=0.07, years=horizons), }) ``` ::: {.callout-warning title="Limits"} `to_monthly()` uses rounded factors (30.44 days and 4.33 weeks per month), while `to_annual()` uses 365 days and 52 weeks per year. A round trip through both functions drifts slightly. The weekly grocery bill gives a different yearly total depending on the path: ```{python} #| label: round-trip ( to_annual(amount=150, period="weekly"), to_annual(amount=groceries_month, period="monthly"), ) ``` A few other limits apply: * `to_annual()` accepts `"daily"`, `"weekly"`, or `"monthly"`, and `to_monthly()` accepts `"daily"`, `"weekly"`, or `"annual"`. Any other `period` raises a `ValueError`. * `opportunity_cost()` assumes the same return every year and ignores inflation, taxes, and fund fees. * `months_to_break_even()` assumes the savings are the same every month and ignores what the upfront cost could have earned if invested. * `percent_of_income()` and `months_to_break_even()` raise a `ValueError` when `income` or `monthly_savings` is zero or negative. ::: ## Putting it together Back to the \$3,200 first job budget. The sections above produced four monthly costs: rent, groceries, coffee, and sinking funds. `percent_of_income()` takes the whole column at once, so one call shows how much of the paycheck each category claims: ```{python} #| label: budget budget = pl.DataFrame({ "category": ["rent", "groceries", "coffee", "sinking funds"], "monthly": [960.0, groceries_month, coffee_month, sinking["monthly"].sum()], }) budget = budget.with_columns( percent=percent_of_income(expense=budget["monthly"].to_numpy(), income=3200).round(1) ) budget ``` ```{python} #| label: budget-total #| include: false budget_total = budget["monthly"].sum() budget_share = percent_of_income(expense=budget_total, income=3200) ``` These four categories take `{python} f"{budget_share:.1f}"`% of take home pay, which leaves \$`{python} f"{3200 - budget_total:,.2f}"` a month for investments, savings, and fun money. Coffee is the smallest line in the budget, but it's also the easiest to change. The code below invests one year of coffee money at 7% for 30 years instead: ```{python} #| label: coffee-invested coffee_invested = opportunity_cost(amount=coffee_year, rate=0.07, years=30) coffee_invested ``` One year of \$5 coffees could grow to about \$`{python} f"{coffee_invested:,.0f}"`. That doesn't mean you should give up coffee; it means the choice now has a price you can see. The [Tracking Spending](02-tracking-spending.qmd) page applies the same idea to recurring costs with `subscription_opportunity_cost()`. ## Recap Budgeting math is middle school math, and these five functions cover the calculations the chapter relies on most. `percent_of_income()` shows how big a slice each expense takes, `to_annual()` and `to_monthly()` put costs on the same time scale, and `opportunity_cost()` and `months_to_break_even()` put a price on spending decisions. Because each one accepts arrays, a single call can compare a whole budget, a list of periodic expenses, or several time horizons. * [Budgeting](https://mjfrigaard.github.io/fm-finance/budgeting.html) in Personal Finance: a field manual * Reference: `percent_of_income()`, `to_annual()`, `to_monthly()`, `opportunity_cost()`, `months_to_break_even()` * Next: [Managing Debt](04-managing-debt.qmd) ### Managing Debt ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Lenders quote whichever number makes a loan look cheapest, and they count on borrowers not running the math. The book's [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) chapter runs that math. It asks what a balance really costs, how much student debt a salary can carry, which ratios lenders check, and which debt to pay first. In this page I'll answer the same questions with perfinpy's 11 managing debt functions. Each example uses the chapter's numbers, so you can check every result against the book. ## The managing debt functions The functions follow the conventions in [Get started](00-get-started.qmd): rates go in as decimals and ratios come out as percents. The one exception to watch is `loan_income_ratio()`, which returns a plain ratio rather than a percent. | Function | Returns | Units | |---|---|---| | `apr_to_apy()` | the effective yearly rate of an APR | decimal (`0.27` is 27%) | | `months_to_payoff()` | months to clear a balance with a fixed payment | months, not rounded | | `total_interest()` | all payments minus the amount borrowed | dollars | | `loan_income_ratio()` | student loans relative to starting salary | ratio (`1` is one year of salary) | | `monthly_standard_payment()` | payment on a standard student loan plan | dollars per month | | `idr_monthly_payment()` | payment on an income driven repayment plan | dollars per month, rounded to cents | | `dti_ratio()` | debt payments as a share of gross income | percent (`28` is 28%) | | `payoff_vs_invest()` | whether to pay off a loan or invest | a single string | | `order_avalanche()` | debts sorted by APR, highest first | a list of dicts | | `order_snowball()` | debts sorted by balance, smallest first | a list of dicts | | `credit_utilization()` | a card balance as a share of the limit | percent (`30` is 30%) | ## What does a balance really cost? Every debt has a price, called the APR (annual percentage rate): the yearly cost of borrowing, shown as a percent of what you owe. The APR is only the starting point. Compounding, slow payments, and long terms all add to what you pay, and the three functions in this section measure each one. ### APR vs. APY The chapter's example is a credit card with a 24% APR that compounds daily, carrying a \$5,000 balance. Credit card companies quote the APR, but compounding (charging interest on interest you haven't paid yet) means the balance grows faster than the APR suggests. Both bars below represent one year of interest on the same balance. The shorter bar is what the APR implies; the taller bar is what you actually owe: ![APR cost vs. APY cost on a \$5,000 balance (24% APR, daily compounding)](assets/managing-debt-apr-apy-bar-model.png){fig-alt="Bar chart of one year of interest on a $5,000 balance. The bluish green APR cost bar, labeled stated, reaches $1,200. The vermillion APY cost bar, labeled actual, reaches $1,356, and a double headed arrow at its top marks the $156 difference as hidden cost."} The APY (annual percentage yield) is the effective yearly rate once compounding is included. `apr_to_apy()` converts one to the other, with `periods_per_year` defaulting to 365 for daily compounding: ```{python} #| label: apr-apy apy = apr_to_apy(apr=0.24) apy ``` A 24% APR compounded daily is really `{python} f"{apy * 100:.1f}"`% a year. On the \$5,000 balance, that gap is about \$`{python} f"{5000 * (apy - 0.24):,.0f}"` of interest the quoted rate never mentions. ### How long does a minimum payment take? The chapter's next example is a \$5,000 balance at 22% APR with a \$100 minimum payment. A \$100 payment sounds reasonable until you see how little of it reaches the balance. The principal is the amount you borrowed; interest is what the lender charges on top. ![Where a \$100 minimum payment actually goes](assets/managing-debt-min-payment-bar-model.png){fig-alt="Bar chart splitting a $100 payment into two bars. A tall vermillion bar shows $92 going to interest, and a short blue bar shows $8 going to principal reduction."} Only the principal slice shrinks the debt. As the balance falls, the interest slice shrinks too, so each payment retires a little more principal than the one before. `months_to_payoff()` accounts for that, compounding interest monthly at `apr / 12`: ```{python} #| label: min-payoff first_interest = 5000 * 0.22 / 12 card_months = months_to_payoff(balance=5000, monthly_payment=100, apr=0.22) first_interest, card_months ``` The first month's interest is about \$`{python} f"{first_interest:,.0f}"`, so only \$`{python} f"{100 - first_interest:,.0f}"` of the first payment touches the balance. Paying the minimum clears the card in about `{python} f"{card_months:.0f}"` months (`{python} f"{card_months / 12:.1f}"` years), and the payments add up to about \$`{python} f"{100 * card_months:,.0f}"` on a \$5,000 balance. Minimum payments are designed to keep you in debt for years. ### What does the loan term cost? An installment loan is one you repay in equal monthly payments, like a car loan or a mortgage. For these loans, total interest is the number that should drive the decision. The chapter's example is a \$20,000 used car loan at 7%. It runs either 6 years at \$340.98 a month or 4 years at \$478.92 a month. The amount borrowed is the same either way. The bars below stack the principal and interest layers, so the cost of the longer term is visible: ![\$20,000 car loan at 7%: principal vs. interest for 6 year and 4 year terms](assets/managing-debt-total-interest-bar-model.png){fig-alt="Two stacked bars of total paid on a $20,000 car loan. The 6-year loan stacks a $4,551 vermillion interest layer on a $20,000 bluish green principal layer. The 4-year loan stacks a thinner $2,988 interest layer on the same $20,000 of principal."} Subtract the principal from everything you pay and the interest layer is what's left. `total_interest()` accepts arrays, so both terms fit in one call: ```{python} #| label: total-interest car_interest = total_interest( monthly_payment=[340.98, 478.92], n_months=[72, 48], principal=20000, ) car_interest ``` The 6 year loan costs \$`{python} f"{car_interest[0]:,.2f}"` in interest, and the 4 year loan costs \$`{python} f"{car_interest[1]:,.2f}"`. Shortening the term saves \$`{python} f"{car_interest[0] - car_interest[1]:,.2f}"`, which is the math behind the 20/4/10 car rule (20% down, no more than 4 years, transportation under 10% of gross income). ## How much student debt can a salary carry? Student loans sit in a complicated middle ground. Education is an investment in your future earning potential, but only when the math works. The chapter gives two tools for checking it: the 1x rule before you borrow, and income driven repayment after. ### The 1x rule The 1x rule says total student debt at graduation should not exceed your expected first year salary. The chapter's example borrower has \$45,000 in loans and a \$42,000 starting salary, repaying on a standard 10 year plan at 6.5%. Picture what you borrowed and what your first job pays as two bars side by side. The rule says the loan bar shouldn't run past the salary bar: ![\$45,000 in student loans vs. a \$42,000 starting salary](assets/managing-debt-loan-income-bar-model.png){fig-alt="Two horizontal bars. The vermillion student loans bar is $45,000 and the bluish green starting salary bar is $42,000. A dashed vertical line at $42,000 marks the end of the salary bar, and the loan bar runs a little past it."} `loan_income_ratio()` divides the loan bar by the salary bar. `monthly_standard_payment()` then spreads the loan, plus interest, over 120 equal payments, with the 6.5% rate and 10 year term as defaults: ```{python} #| label: loan-income ratio = loan_income_ratio(loan_total=45000, expected_salary=42000) student_payment = monthly_standard_payment(principal=45000) ratio, student_payment ``` The ratio is `{python} f"{ratio:.2f}"`, so this borrower is a little over the 1x rule. The standard payment is about \$`{python} f"{student_payment:,.0f}"` a month, or roughly \$`{python} f"{student_payment / 45000:.4f}"` a month for every dollar borrowed. The 1x rule is a ceiling, not a target; lower earning majors often need a lower personal cap. ### Income driven repayment When the 1x rule is out of reach, federal income driven repayment (IDR) plans cap payments as a share of discretionary income. Discretionary income is your AGI (adjusted gross income, from your tax return) minus a protected multiple of the Federal Poverty Guideline. The chapter's example is a \$50,000 AGI under IBR. IBR protects 1.5 times the 2026 guideline (\$15,960) and charges 10% on whatever is left. Think of the AGI as one bar. The plan protects the first part of it, and the payment is a small slice of what's left: ![\$50,000 AGI under IBR: protected income, discretionary income, and the yearly payment](assets/managing-debt-idr-bar-model.png){fig-alt="A single horizontal bar for $50,000 of AGI, split into three segments. A light bluish green segment of $23,940 is protected income (1.5 times $15,960). A narrow vermillion segment of $2,606 a year is the payment (10% of discretionary income). A bluish green segment of $23,454 is the rest of discretionary income."} `idr_monthly_payment()` subtracts the protected part, takes the payment rate of what's left, and divides by 12. The defaults are the IBR terms for loans from July 2014 on; older IBR loans use a 15% rate: ```{python} #| label: idr-payment ibr = idr_monthly_payment(agi=50000) ibr_old = idr_monthly_payment(agi=50000, payment_rate=0.15) ibr, ibr_old ``` IBR comes to \$`{python} f"{ibr:,.2f}"` a month, and \$`{python} f"{ibr_old:,.2f}"` for loans made before July 2014. IDR plans change with Congress, the courts, and the Department of Education, so check current terms at [studentaid.gov](https://studentaid.gov/manage-loans/repayment/plans) before enrolling. ## What ratios do lenders check? Lenders don't just look at what you owe; they look at how much of your income and credit is already spoken for. These two ratios are what lenders calculate about you, so it pays to calculate them about yourself first. ### Debt to income ratio The chapter pictures a first job paying \$45,000 a year, or \$3,750 a month in gross income. Its debts are a \$511 student loan payment, a \$450 car payment, and \$100 in credit card minimums. Gross income is your pay before taxes, and the bar below splits it into what goes to debt and what's left: ![\$3,750 gross monthly income split into debt payments and remaining income](assets/managing-debt-dti-bar-model.png){fig-alt="A horizontal bar for $3,750 of gross monthly income. A vermillion segment of $1,061 (28%) is debt payments, and a bluish green segment of $2,689 (72%) is remaining income. A dashed line marks the 43% danger zone, to the right of where the debt segment ends."} DTI (debt to income) is just the debt slice as a share of the whole bar. `dti_ratio()` returns it as a percent: ```{python} #| label: dti debt_payments = {"student_loan": 511, "car": 450, "cards": 100} dti = dti_ratio( monthly_debt_payments=sum(debt_payments.values()), gross_monthly_income=45000 / 12, ) dti ``` The \$`{python} f"{sum(debt_payments.values()):,}"` in monthly debt payments take about `{python} f"{dti:.0f}"`% of gross income. The chapter calls 20% to 35% manageable but worth watching; above 43%, most mortgage lenders won't approve you. ### Credit utilization Credit utilization is how much of your available credit you're using. Credit scores penalize high utilization because using most of your available credit is a sign of money trouble. The chapter's example is a \$900 balance on a first card with a \$3,000 limit: ![\$900 balance against a \$3,000 credit limit: used vs. unused](assets/managing-debt-utilization-bar-model.png){fig-alt="A horizontal bar for a $3,000 credit limit. A vermillion segment of $900 (30%) is the used balance, and a light bluish green segment of $2,100 (70%) is unused credit. A blue dashed line marks the 10% ideal at $300, and a vermillion dashed line marks the 30% threshold, exactly where the used balance ends."} `credit_utilization()` divides the used slice by the whole limit and returns a percent: ```{python} #| label: utilization utilization = credit_utilization(balance=900, credit_limit=3000) utilization ``` The card sits at `{python} f"{utilization:g}"`% utilization, right at the threshold. Keep utilization under 30% on each card and across all cards; under 10% (a \$`{python} f"{3000 * 0.10:,.0f}"` balance on this card) is ideal. ## Which debt should you pay first? Not all debt is created equal. Attack it in order of damage potential. This section covers two versions of that decision. The first is whether extra money should go to a loan or to investments; the second is which of several debts to attack first. ### Pay off or invest? The chapter compares a 5% student loan against an expected 7% stock market return. The math slightly favors investing, but the bar model adds what the math alone misses: ![Guaranteed 5% debt payoff vs. expected 7% investment return](assets/managing-debt-payoff-invest-bar-model.png){fig-alt="Two bars of annual return. The blue pay off debt bar reaches 5% and is labeled certain. The taller bluish green invest bar reaches 7% and is labeled expected, not guaranteed."} `payoff_vs_invest()` compares the two rates (as decimals) and returns the option that wins on paper: ```{python} #| label: payoff-vs-invest loan_rate = 0.05 expected_return = 0.07 payoff_vs_invest(loan_rate=loan_rate, expected_return=expected_return) ``` Investing wins by about `{python} f"{(expected_return - loan_rate) * 100:.1f}"` percentage points a year. But the return from paying off the loan is guaranteed, and the investment return is not. A guaranteed 5% beats a probable 7% for many people psychologically, so run the math, then add your peace of mind premium. ### Avalanche vs. snowball The chapter's example has three credit cards: Card A (\$1,000 at 18%), Card B (\$5,000 at 24%), and Card C (\$2,000 at 15%). The avalanche method pays the highest APR first; the snowball method pays the smallest balance first. Both attack the same three debts, just in a different order: ![Avalanche order (highest APR first) vs. snowball order (smallest balance first)](assets/managing-debt-avalanche-snowball-bar-model.png){fig-alt="Two panels of bars showing the attack order for three cards. The avalanche panel goes Card B ($5,000 at 24%) first, Card A ($1,000 at 18%) second, and Card C ($2,000 at 15%) third. The snowball panel goes Card A first, Card C second, and Card B third."} Both functions take a list of debts (one dict per debt) and return a new, sorted list. `order_avalanche()` needs an `apr` key, and `order_snowball()` needs a `balance` key. Wrapping the result in `pl.DataFrame()` prints it as a table: ```{python} #| label: avalanche debts = [ {"name": "Card A", "balance": 1000, "apr": 0.18}, {"name": "Card B", "balance": 5000, "apr": 0.24}, {"name": "Card C", "balance": 2000, "apr": 0.15}, ] pl.DataFrame(order_avalanche(debts)) ``` ```{python} #| label: snowball pl.DataFrame(order_snowball(debts)) ``` Avalanche wins on paper because a dollar sent to the highest APR stops the most interest. The code below shows how much interest an extra \$100 stops next month on each card: ```{python} #| label: extra-payment extra_saved = {d["name"]: 100 * d["apr"] / 12 for d in debts} extra_saved ``` An extra \$100 on Card B stops \$`{python} f"{extra_saved['Card B']:.2f}"` of interest, compared with \$`{python} f"{extra_saved['Card A']:.2f}"` on Card A. Snowball pays off Card A first, which costs a little more but delivers a win sooner. If that quick win is the price of actually finishing, it's often worth it; if you're disciplined enough for avalanche, take the savings. ## Variations Most of these functions accept arrays, so one call can compare several versions of the same decision. Raising the credit card payment from the minimum shows how fast the payoff time and the interest fall: ```{python} #| label: vary-card-payment import math card_payment = [100, 150, 200, 300] card_payoff = months_to_payoff(balance=5000, monthly_payment=card_payment, apr=0.22) card_cost = total_interest( monthly_payment=card_payment, n_months=card_payoff, principal=5000 ) pl.DataFrame({"payment": card_payment, "months": card_payoff, "interest": card_cost}) ``` Doubling the payment from \$100 to \$200 cuts the interest from about \$`{python} f"{card_cost[0]:,.0f}"` to about \$`{python} f"{card_cost[2]:,.0f}"`, and the card is gone in `{python} math.ceil(card_payoff[2])` months instead of `{python} math.ceil(card_payoff[0])`. The car loan payments in the total interest example come from the same amortization formula that `monthly_standard_payment()` uses. Changing the rate to 7% and passing several terms reproduces them, along with the interest for each term: ```{python} #| label: vary-car-term car_years = [3, 4, 5, 6] car_payment = monthly_standard_payment( principal=20000, annual_rate=0.07, years=car_years ) pl.DataFrame({ "years": car_years, "payment": car_payment, "interest": total_interest( monthly_payment=car_payment, n_months=[y * 12 for y in car_years], principal=20000, ), }) ``` The IDR plans differ only in the protected multiple and the payment rate, so `idr_monthly_payment()` can compare them for the same \$50,000 AGI. SAVE protected 225% of the guideline and charged 5% on undergraduate loans before it ended in March 2026: ```{python} #| label: vary-idr-plans idr_plans = pl.DataFrame({ "plan": [ "IBR (loans from July 2014)", "IBR (loans before July 2014)", "SAVE (ended 2026)", ], "threshold_pct": [1.5, 1.5, 2.25], "payment_rate": [0.10, 0.15, 0.05], }) idr_plans.with_columns( monthly=idr_monthly_payment( agi=50000, threshold_pct=idr_plans["threshold_pct"].to_numpy(), payment_rate=idr_plans["payment_rate"].to_numpy(), ) ) ``` ## What these functions don't model ::: {.callout-warning title="Limits"} `months_to_payoff()` raises a `ValueError` when the payment doesn't cover the first month's interest, because the balance would never be paid off. A \$90 payment on the \$5,000 card at 22% falls short of the first month's interest: ```{python} #| label: payoff-error #| error: true months_to_payoff(balance=5000, monthly_payment=90, apr=0.22) ``` A few other limits apply: * `months_to_payoff()` and `apr_to_apy()` assume a constant rate and no new charges. The months aren't rounded, so the last payment is a partial one. * `total_interest()` uses whatever payment you give it. A payment rounded to cents gives a total that differs from the exact one by a few cents. * `idr_monthly_payment()` defaults to the 2026 poverty guideline for one person in the contiguous U.S. It doesn't cover RAP, which bases payments on total AGI instead of discretionary income. * `payoff_vs_invest()` takes single values only and compares the rates exactly as given. It ignores taxes and risk, and only identical rates count as a wash. * `order_avalanche()` and `order_snowball()` sort the debts; they don't simulate the payoff or total the interest under each method. ::: ## Putting it together Picture a first job paying \$45,000 a year, with \$45,000 in federal student loans, a car loan, and one credit card. The first question is whether the loans fit the 1x rule, and what repaying them costs on the standard plan versus IBR: ```{python} #| label: together-loans salary = 45000 standard = monthly_standard_payment(principal=45000) { "ratio": loan_income_ratio(loan_total=45000, expected_salary=salary), "standard": standard, "ibr": idr_monthly_payment(agi=salary), } ``` The loans sit exactly at the 1x ceiling, so the standard plan is affordable. Next, we can add the car loan (\$15,000 at 7%, \$450 a month) and the card (\$900 at 22%, \$100 a month, \$3,000 limit). Then we check the two ratios lenders use: ```{python} #| label: together-ratios first_job = [ {"name": "Student loan", "balance": 45000, "apr": 0.065, "payment": standard}, {"name": "Car loan", "balance": 15000, "apr": 0.07, "payment": 450}, {"name": "Credit card", "balance": 900, "apr": 0.22, "payment": 100}, ] first_job_dti = dti_ratio( monthly_debt_payments=sum(d["payment"] for d in first_job), gross_monthly_income=salary / 12, ) first_job_util = credit_utilization(balance=900, credit_limit=3000) {"dti": first_job_dti, "utilization": first_job_util} ``` DTI is about `{python} f"{first_job_dti:.0f}"`%, in the manageable range, but the card sits at the `{python} f"{first_job_util:g}"`% utilization threshold. Both ordering methods point at the same debt first: ```{python} #| label: together-avalanche pl.DataFrame(order_avalanche(first_job)) ``` ```{python} #| label: together-snowball pl.DataFrame(order_snowball(first_job)) ``` The card has both the highest APR and the smallest balance, so avalanche and snowball agree. The last step checks how long the card takes at \$100 a month. It also checks whether extra money should go to each debt or to investments expected to return 7%: ```{python} #| label: together-decide card_first_job = months_to_payoff(balance=900, monthly_payment=100, apr=0.22) ( card_first_job, payoff_vs_invest(loan_rate=0.22, expected_return=0.07), payoff_vs_invest(loan_rate=0.065, expected_return=0.07), ) ``` The card is gone in `{python} math.ceil(card_first_job)` months. After that, its \$100 can roll into the car loan. The student loan comparison is closer than the function's answer suggests. The edge is only `{python} f"{(0.07 - first_job[0]['apr']) * 100:.1f}"` percentage points, and the chapter treats loans above about 6% as worth paying down. The book's [Budgeting](https://mjfrigaard.github.io/fm-finance/budgeting.html#sec-foo-intro) chapter places these steps in the Financial Order of Operations. The [Emergency Fund](05-emergency-fund.qmd) page covers the reserve that comes after high interest debt. ## How `monthly_standard_payment()` works `monthly_standard_payment()` doesn't repeat the amortization formula. It passes its arguments to `mortgage_payment()` (from the [Major Purchases](16-major-purchases.qmd) page), which checks its inputs and calls an internal helper, `_annuity_factor()`: ```{python} #| label: call-stack #| eval: false from rich import print from rich.tree import Tree tree = Tree("monthly_standard_payment()") mortgage = tree.add("mortgage_payment()") mortgage.add("_as_numeric()") mortgage.add("_as_numeric()") mortgage.add("_as_positive()").add("_as_numeric()") mortgage.add("_annuity_factor()") print(tree) ``` ``` monthly_standard_payment() └── mortgage_payment() ├── _as_numeric() ├── _as_numeric() ├── _as_positive() │ └── _as_numeric() └── _annuity_factor() ``` `_annuity_factor()` is where the 0% case lives. Instead of dividing by zero, it returns the number of payments, so a 0% loan is just the principal split into equal pieces: ```{python} #| label: zero-rate monthly_standard_payment(principal=12000, annual_rate=0) ``` ## Recap Debt is a math problem dressed up in emotional clothing, and these 11 functions cover the math the chapter relies on. `apr_to_apy()`, `months_to_payoff()`, and `total_interest()` show what a balance really costs; `loan_income_ratio()`, `monthly_standard_payment()`, and `idr_monthly_payment()` size student loans against a salary. `dti_ratio()` and `credit_utilization()` return the percents lenders check, and `payoff_vs_invest()`, `order_avalanche()`, and `order_snowball()` decide where the next dollar goes. * [Managing Debt](https://mjfrigaard.github.io/fm-finance/managing_debt.html) in Personal Finance: a field manual * Reference: `apr_to_apy()`, `months_to_payoff()`, `total_interest()`, `loan_income_ratio()`, `monthly_standard_payment()`, `idr_monthly_payment()`, `dti_ratio()`, `payoff_vs_invest()`, `order_avalanche()`, `order_snowball()`, `credit_utilization()` * Next: [Emergency Fund](05-emergency-fund.qmd) ### Emergency Fund ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` An emergency fund is cash set aside so a car repair or a job loss doesn't end up on a credit card. Building one comes down to four questions. How big should the fund be, and how long will it take to fill? How much should you save each month to finish by a deadline, and what does the fund earn in a savings account? In this page I'll answer them with `emergency_fund_target()`, `months_to_ef_goal()`, `monthly_contribution_needed()`, and `ef_growth()`. The examples below use the numbers from the [Emergency Fund](https://mjfrigaard.github.io/fm-finance/emergency_fund.html) chapter of the book, where each formula is built from scratch. ## The emergency fund functions Each function answers one of the four questions: | Function | Returns | Units | |---|---|---| | `emergency_fund_target()` | target balance | dollars | | `months_to_ef_goal()` | months until the target is met, rounded up | whole months (`int`) | | `monthly_contribution_needed()` | monthly savings needed to meet a deadline, rounded up | whole dollars (`int`) | | `ef_growth()` | balance after interest | dollars | All four accept arrays. The `apy` argument in `ef_growth()` follows the decimal convention from [Get started](00-get-started.qmd), so `0.04` is 4%. ## How big should the fund be? The standard target is 3 to 6 months of essential expenses: housing, groceries, utilities, transportation, health insurance, and minimum debt payments. Dining out and subscriptions don't count, because those are the first things to go in a real emergency. The book's example is a first job with \$2,400 a month in essential expenses. Each bar below is the one before it plus one more month of expenses. ![Emergency fund target at \$2,400/month essential expenses](assets/emergency-fund-ef-target-bar-model.png){fig-alt="Bar chart of emergency fund targets for 1 to 6 months of $2,400 monthly expenses: $2,400, $4,800, $7,200, $9,600, $12,000, and $14,400. Each bar is one month of expenses taller than the one before it. The 1 and 2 month bars are light green, the 3 and 4 month bars are bluish green, and the 5 and 6 month bars are blue."} `emergency_fund_target()` multiplies monthly expenses by `months` (3 by default). The code below computes both ends of the standard range: ```{python} #| label: ef-target target_3 = emergency_fund_target(monthly_expenses=2400, months=3) target_6 = emergency_fund_target(monthly_expenses=2400, months=6) target_3, target_6 ``` The range runs from \$`{python} f"{target_3:,.0f}"` to \$`{python} f"{target_6:,.0f}"`. A stable salary with good insurance sits near the low end; variable income or dependents push toward the high end. The rest of the book's examples split the difference at 4 months: ```{python} #| label: ef-target-4 target = emergency_fund_target(monthly_expenses=2400, months=4) target ``` ## How long will it take to fill? Most people don't start from zero. Say \$1,200 is already saved toward the 4 month target, and \$400 goes into the fund each month. Think of the target as one bar. The saved part is already filled in, and the gap is cut into \$400 slices; counting the slices gives the number of months. ![A \$9,600 target with \$1,200 saved: the \$8,400 gap, filled \$400 at a time](assets/emergency-fund-ef-months-bar-model.png){fig-alt="Bar model: a single $9,600 bar. The first $1,200 is a blue block labeled already saved. The remaining $8,400 is a bluish green block divided into 21 equal $400 slices, labeled still needed."} `months_to_ef_goal()` subtracts the current balance from the target and divides the gap by the monthly contribution: ```{python} #| label: ef-months saved = 1200 months_needed = months_to_ef_goal( target=target, current_balance=saved, monthly_contribution=400, ) months_needed ``` The \$`{python} f"{target - saved:,.0f}"` gap takes `{python} months_needed` months, or about `{python} f"{months_needed / 12:.1f}"` years. The result is rounded up to whole months, because a partial month still means one more transfer. ## How much should you save to meet a deadline? Now flip the question. The target is still \$9,600 with \$1,200 saved, but the goal is to finish in 18 months. This time the number of slices is fixed at one per month. The question is how wide each slice has to be. ![The same \$8,400 gap, cut into 18 equal monthly slices](assets/emergency-fund-ef-contrib-bar-model.png){fig-alt="Bar model: a single $9,600 bar. The first $1,200 is a blue block labeled saved $1,200. The remaining $8,400 is split into 18 equal slices in alternating bluish green and light green, labeled 18 slices of about $467."} `monthly_contribution_needed()` divides the same gap by the number of months instead: ```{python} #| label: ef-contrib deadline = 18 contribution = monthly_contribution_needed( target=target, current_balance=saved, months=deadline, ) contribution ``` Saving \$`{python} contribution` a month closes the gap in `{python} deadline` months. The function rounds up to the next whole dollar, so the payments add up to \$`{python} f"{contribution * deadline:,}"`: enough to cover the gap with \$`{python} f"{contribution * deadline - (target - saved):,.0f}"` to spare. ## What does the fund earn while it sits? A high yield savings account (HYSA) pays interest on the fund. Savings accounts advertise an APY (annual percentage yield), which is what the money earns in a year with monthly compounding already included. A higher APY means the fund grows faster. The book's example leaves a full \$9,600 fund untouched for 12 months at 4% APY, close to what top HYSAs paid in late 2026. The bar below shows the balance after a year: the original deposit, plus a thin slice of interest on the end. ![\$9,600 at 4% APY for 12 months: your balance plus interest](assets/emergency-fund-ef-growth-bar-model.png){fig-alt="Bar model: a single bar after 12 months. A long bluish green block is the $9,600 balance, and a thin blue block on the end is $384 of interest, for a total just under $10,000."} `ef_growth()` multiplies the balance by `(1 + apy)` once per year, using a fraction of a year for partial periods: ```{python} #| label: ef-growth grown = ef_growth(balance=target, apy=0.04, months=12) grown ``` The fund grows to \$`{python} f"{grown:,.0f}"`, which is \$`{python} f"{grown - target:,.0f}"` of interest. That won't change the timeline much, but it can cover a small car repair without touching the fund itself. ## Variations The book's build chart compares three monthly contributions toward the same \$9,600 target, starting from an empty account. ![Months to reach a \$9,600 emergency fund at three contribution levels](assets/emergency-fund-ef-build-bar-model.png){fig-alt="Bar chart of months to reach a $9,600 target (4 months of $2,400 essential expenses) at three monthly contributions: 48 months at $200, 24 months at $400, and 16 months at $600. The bars are light green, bluish green, and blue."} Because `months_to_ef_goal()` accepts arrays, the whole chart is one call: ```{python} #| label: ef-build contributions = [200, 400, 600] build = pl.DataFrame({ "monthly": contributions, "months": months_to_ef_goal( target=target, current_balance=0, monthly_contribution=contributions, ), }) build ``` Doubling the contribution from \$200 to \$400 cuts the timeline from `{python} build["months"][0]` months to `{python} build["months"][1]`, and \$600 gets there in `{python} build["months"][2]`. ### Longer deadlines mean smaller payments The same comparison works in reverse. The code below finds the monthly amount needed to close the \$8,400 gap in one, one and a half, or two years: ```{python} #| label: ef-deadlines deadline_months = [12, 18, 24] deadlines = pl.DataFrame({ "months": deadline_months, "monthly": monthly_contribution_needed( target=target, current_balance=saved, months=deadline_months, ), }) deadlines ``` Stretching the deadline from one year to two drops the monthly amount from \$`{python} deadlines["monthly"][0]` to \$`{python} deadlines["monthly"][2]`. ::: {.callout-warning title="Limits"} * `emergency_fund_target()` doesn't choose the number of months for you. The default of 3 is the low end of the range, so pass a larger `months` for variable income or dependents. * `months_to_ef_goal()` and `monthly_contribution_needed()` ignore interest, so they slightly overstate the time and money needed when the fund sits in a HYSA. Both round up and return 0 when the balance already meets the target. * `monthly_contribution` and `months` must be greater than 0. A zero raises a `ValueError` instead of returning `inf`. * `ef_growth()` assumes the APY stays fixed and nothing goes in or out during the period. Pass the APY as a decimal (`0.04`), not a percent (`4`). ::: ## Putting it together The book's order matters here. A \$1,000 starter fund comes first, then high interest debt (see [Managing Debt](04-managing-debt.qmd)), and then the full fund. The scenario below picks up at the last step: \$2,400 a month in essential expenses, a 4 month target, \$1,200 already saved, and an 18 month deadline. `percent_of_income()` from [Budgeting](03-budgeting.qmd) shows how much of a \$3,200 take home paycheck the plan uses. ```{python} #| label: ef-plan plan_target = emergency_fund_target(monthly_expenses=2400, months=4) plan_monthly = monthly_contribution_needed( target=plan_target, current_balance=1200, months=18, ) plan_months = months_to_ef_goal( target=plan_target, current_balance=1200, monthly_contribution=plan_monthly, ) plan_share = percent_of_income(expense=plan_monthly, income=3200) plan_interest = ef_growth(balance=plan_target, apy=0.04, months=12) - plan_target pl.DataFrame({ "step": [ "target", "monthly contribution", "months to goal", "percent of take home pay", "first year of interest", ], "value": [ round(float(v), 1) for v in [plan_target, plan_monthly, plan_months, plan_share, plan_interest] ], }) ``` Saving \$`{python} plan_monthly` a month takes `{python} f"{plan_share:.1f}"`% of the paycheck. Feeding that contribution back into `months_to_ef_goal()` returns `{python} plan_months` months, which confirms the plan meets the deadline. Once the fund is full, a year in a HYSA adds \$`{python} f"{plan_interest:,.0f}"` without any new deposits. [Automating Savings](08-automating-savings.qmd) covers setting up the monthly transfer, and [High-Yield Savings Accounts](07-high-yield-accounts.qmd) covers choosing the account. ## Recap An emergency fund comes down to four numbers. They are the target, the months to reach it, the monthly amount a deadline requires, and the interest earned along the way. `emergency_fund_target()`, `months_to_ef_goal()`, `monthly_contribution_needed()`, and `ef_growth()` compute each one. All four accept arrays, so comparing contributions or deadlines takes a single call. * [Emergency Fund](https://mjfrigaard.github.io/fm-finance/emergency_fund.html) in Personal Finance: a field manual * Reference: `emergency_fund_target()`, `months_to_ef_goal()`, `monthly_contribution_needed()`, `ef_growth()` * Next: [Savings Strategies](06-savings-strategies.qmd) ## Savings ### Savings Strategies ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` How much of your paycheck do you actually keep? The [Savings Strategies](https://mjfrigaard.github.io/fm-finance/savings_strategies.html) chapter of the book argues that your savings rate is the one number worth tracking above all others, because it sets how fast wealth builds. In this page I'll answer that question with `savings_rate()`, using the chapter's numbers so you can check every result against the book. Then we'll borrow a few functions from other chapters to follow one paycheck from savings rate to emergency fund to long term investing. ## The savings strategies function `savings_rate()` follows the conventions on the [Get started](00-get-started.qmd) page. Like the other ratio functions, it returns a percent, not a decimal. | Function | Returns | Units | |---|---|---| | `savings_rate()` | the share of income not spent | percent (`15` is 15%); negative when spending exceeds income | ## What is your savings rate? The chapter's first job takes home \$3,200 a month and spends \$2,720 of it. Every dollar of the paycheck goes to either spending or savings, so the question is how big the savings slice is. Think of the take home pay as one bar. Spending fills most of it, and savings is the slice left at the end: ![\$3,200 take home pay: spending and savings](assets/savings-strategies-savings-rate-bar-model.png){fig-alt="Bar model: one horizontal bar for $3,200 of monthly take home pay, split into a large bluish green slice labeled Spending $2,720 (85%) and a small blue slice at the right end labeled Savings $480 (15%)."} `savings_rate()` subtracts spending from income, divides by income, and multiplies by 100: ```{python} #| label: first-job-rate first_job_rate = savings_rate(income=3200, spending=2720) first_job_rate ``` The first job saves `{python} f"{first_job_rate:.0f}"`% of take home pay, which lands in the chapter's average tier (10% to 20%). The result is a percent, so `15.0` means 15%. Income and spending need to cover the same period; a monthly spending total against a yearly salary gives a rate that is badly wrong. ## What do the benchmark tiers look like in dollars? The chapter gives four benchmarks: under 10% is the danger zone, 10% to 20% is average, 20% to 30% is strong, and 30% or more is the path to financial independence. Percentages are easy to compare but hard to picture, so the chapter converts one example from each tier into dollars on a \$45,000 income: ![Annual dollars saved at four savings rate tiers on a \$45,000 income](assets/savings-strategies-savings-rate-bar-model-intro.png){fig-alt="Horizontal bar chart of annual savings on a $45,000 income at four tiers: 8% (danger zone) saves $3,600 in vermillion, 15% (average) saves $6,750 in bluish green, 25% (strong) saves $11,250 in blue, and 35% (FI path) saves $15,750 in pale green. Each bar is longer than the one above it."} Each bar is income minus spending. Because `savings_rate()` accepts arrays, one call can work backward from the dollars in each bar to the tier it belongs to: ```{python} #| label: tiers saved = [3600, 6750, 11250, 15750] pl.DataFrame({ "tier": ["danger zone", "average", "strong", "FI path"], "saved": saved, "rate": savings_rate(income=45000, spending=[45000 - s for s in saved]), }) ``` The rates come back as 8, 15, 25, and 35, one for each bar. Moving from the danger zone to the strong tier on the same salary means saving an extra \$7,650 a year. ## Variations The chapter's central claim is that savings rate matters more than income. It compares someone earning \$45,000 and spending \$36,000 with someone earning \$75,000 and spending \$67,500. Passing both people to `savings_rate()` at once gives their rates: ```{python} #| label: two-earners earners = pl.DataFrame({ "income": [45000, 75000], "spending": [36000, 67500], }) earners = earners.with_columns( saved=pl.col("income") - pl.col("spending"), rate=savings_rate(income=earners["income"], spending=earners["spending"]), ) earners ``` The lower earner saves 20% and the higher earner saves 10%. To see where each one ends up, we can borrow `future_value_series()` from [Investing Basics](09-investing-basics.qmd). It grows a yearly contribution at 7% (`rate` is a decimal per period, and here the period is a year): ```{python} #| label: two-earners-growth years = [23, 24, 25, 26] pl.DataFrame({ "years": years, "saves_20_pct": future_value_series(contribution=9000, rate=0.07, periods=years), "saves_10_pct": future_value_series(contribution=7500, rate=0.07, periods=years), }) ``` The \$45,000 earner crosses \$500,000 in year 24, and the \$75,000 earner crosses it in year 26. That matches the chapter's chart. The higher saver also lives on \$36,000 a year, so they need a smaller pile to stop working. ::: {.callout-warning title="Limits"} `savings_rate()` does one subtraction and one division, so it leaves a few things to you: * It doesn't know which income you mean. The chapter uses take home pay here, while [Automating Savings](08-automating-savings.qmd) measures the rate on gross pay because 401(k) contributions come out before taxes. The same paycheck gives a different rate on each base. * It doesn't check that `income` and `spending` cover the same period. * It returns a negative rate when spending exceeds income instead of raising an error. * It raises an error when `income` is zero or negative: ```{python} #| label: zero-income #| error: true savings_rate(income=0, spending=500) ``` ::: ## Putting it together Back to the first job saving \$480 a month. The chapter says savings should be protected before they grow, so the first stop is an emergency fund. The [Emergency Fund](05-emergency-fund.qmd) chapter uses \$2,400 a month in essential expenses and a four month target. `emergency_fund_target()` sets the goal, and `months_to_ef_goal()` counts the months to reach it at \$480 a month: ```{python} #| label: first-job-ef monthly_saved = 3200 - 2720 ef_target = emergency_fund_target(monthly_expenses=2400, months=4) ef_months = months_to_ef_goal( target=ef_target, current_balance=0, monthly_contribution=monthly_saved ) ef_target, ef_months ``` At a `{python} f"{first_job_rate:.0f}"`% savings rate, the \$`{python} f"{ef_target:,.0f}"` fund is full in `{python} f"{ef_months}"` months. After that, the same \$480 can go to investing instead. `future_value_series()` takes a monthly rate here, so the 7% yearly return is divided by 12: ```{python} #| label: first-job-invested invested = future_value_series(contribution=monthly_saved, rate=0.07 / 12, periods=30 * 12) invested ``` Thirty years of \$480 a month could grow to about \$`{python} f"{invested:,.0f}"`. Nothing about the salary changed; the savings rate did all the work. ## Recap Your savings rate is the lever you fully control, and `savings_rate()` measures it as a percent of income. One call can check a single paycheck, place several savings amounts on the chapter's benchmark tiers, or compare people with different salaries. Paired with the emergency fund and investing functions, it shows how a modest rate turns into a protected cushion and then long term wealth. * [Savings Strategies](https://mjfrigaard.github.io/fm-finance/savings_strategies.html) in Personal Finance: a field manual * Reference: `savings_rate()` * Next: [High-Yield Savings Accounts](07-high-yield-accounts.qmd) ### High-Yield Savings Accounts ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Where should your savings live, and what does that choice earn? The [High-Yield Savings Accounts](https://mjfrigaard.github.io/fm-finance/high_yield_accounts.html) chapter of the book makes the case for a high yield savings account (HYSA) at an online bank: it's insured, you can reach the money in a day or two, and it pays far more than a big bank's basic savings account. In this page I'll put numbers on that case with `hysa_balance()`, using the chapter's \$9,600 emergency fund so you can check every result against the book. ## The high yield accounts function `hysa_balance()` follows the conventions on the [Get started](00-get-started.qmd) page: the APY goes in as a decimal, and every argument accepts arrays. | Function | Returns | Units | |---|---|---| | `hysa_balance()` | the balance after growing at an APY for some years | dollars (`annual_apy` is a decimal; `years` defaults to 1) | ## How much does an emergency fund earn in a year? The chapter follows the \$9,600 emergency fund from [Emergency Fund](05-emergency-fund.qmd) into a HYSA paying 4% APY. The APY (annual percentage yield) already includes daily compounding, so a year of growth is one multiplication by 1.04: ```{python} #| label: one-year one_year = hysa_balance(principal=9600, annual_apy=0.04) one_year, one_year - 9600 ``` After one year the fund holds \$`{python} f"{one_year:,.0f}"`, and \$`{python} f"{one_year - 9600:,.0f}"` of that is interest. `years` defaults to 1, so the call above doesn't need it. ## How does the balance grow year by year? Leave the money alone and each year multiplies the previous balance by 1.04 again. The chapter draws each year as a bar split into the money you put in and the interest it has earned so far: ![\$9,600 at 4% APY: deposit and interest earned, year by year](assets/high-yield-accounts-hysa-bar-model.png){fig-alt="Stacked bar chart of a $9,600 deposit at 4% APY over years 0 through 5. Each bar has the same bluish green base for the $9,600 deposit, topped by a blue layer for interest earned that grows each year. Bar totals read $9,600, $9,984, $10,383, $10,799, $11,231, and $11,680."} The bluish green base never changes; only the blue interest layer grows. Passing several values to `years` reproduces every bar in one call: ```{python} #| label: five-years years = list(range(6)) balances = hysa_balance(principal=9600, annual_apy=0.04, years=years) pl.DataFrame({ "years": years, "deposit": [9600] * 6, "interest": balances - 9600, "balance": balances, }).with_columns(pl.col("interest", "balance").round(2)) ``` After five years the fund holds \$`{python} f"{balances[5]:,.2f}"`, which is the chapter's \$11,680. That's \$`{python} f"{balances[5] - 9600:,.0f}"` of growth without putting a dollar of the deposit at risk. ## Variations The chapter compares account types rather than banks. In late 2026 the national average savings rate was 0.39%, a big bank's basic account often paid 0.01%, and the best online accounts paid 3.8% to 4.2%. `annual_apy` accepts an array, so one call compares a \$10,000 balance across all of them: ```{python} #| label: compare-apy apys = [0.0001, 0.0039, 0.038, 0.04, 0.042] pl.DataFrame({ "account": ["big bank basic", "national average", "online low", "online typical", "online high"], "apy": apys, "interest_year_1": hysa_balance(principal=10000, annual_apy=apys) - 10000, }).with_columns(pl.col("interest_year_1").round(2)) ``` The gap between online banks is small: \$40 a year separates the low and high ends on \$10,000. The gap between an online bank and a big bank's basic account is large: \$400 against \$1. As the chapter puts it, pick an online HYSA and don't overthink which one. ::: {.callout-warning title="Limits"} `hysa_balance()` grows one lump sum at one rate, so it leaves out a few things: * It assumes the APY never changes. Real HYSA rates move with interest rates, sometimes several times a year. * It doesn't add deposits along the way. For a fixed monthly deposit, use `future_value_series()` from [Investing Basics](09-investing-basics.qmd). * It ignores taxes on interest and inflation. * It doesn't know about the \$250,000 FDIC limit per account holder per bank. Balances above that need a second bank. * It checks that inputs are numbers, not that they make sense. A negative `annual_apy` or `years` returns a result instead of an error. ::: ## Putting it together The chapter's two headline numbers are an APY and an emergency fund, and both come from other chapters' functions. Banks sometimes advertise an APR, the rate before compounding. `apr_to_apy()` from [Managing Debt](04-managing-debt.qmd) converts it with daily compounding, the way most HYSAs pay: ```{python} #| label: apr-to-apy apy = apr_to_apy(apr=0.0392) apy ``` A 3.92% APR compounded daily is an APY of `{python} f"{apy * 100:.2f}"`%. Next, `emergency_fund_target()` from [Emergency Fund](05-emergency-fund.qmd) sets the balance to park: four months of \$2,400 in essential expenses. We can then compare that fund after five years in the HYSA and in a big bank's basic account: ```{python} #| label: ef-in-hysa ef_target = emergency_fund_target(monthly_expenses=2400, months=4) in_hysa = hysa_balance(principal=ef_target, annual_apy=apy, years=5) in_basic = hysa_balance(principal=ef_target, annual_apy=0.0001, years=5) ef_target, round(in_hysa, 2), round(in_basic, 2) ``` The same \$`{python} f"{ef_target:,.0f}"` fund grows to \$`{python} f"{in_hysa:,.2f}"` in the HYSA and \$`{python} f"{in_basic:,.2f}"` at the big bank, a difference of \$`{python} f"{in_hysa - in_basic:,.0f}"`. Finally, `ef_growth()` from the Emergency Fund chapter does the same math in months, which helps when a goal doesn't land on a whole year: ```{python} #| label: ef-growth ef_growth(balance=ef_target, apy=0.04, months=[12, 18]) ``` Twelve months matches `hysa_balance()` with the default one year, and 18 months shows the balance halfway through year two. ## Recap A HYSA keeps your savings safe and reachable while paying hundreds of times what a basic account pays. `hysa_balance()` grows a balance at an APY, and passing several years or several APYs compares horizons and accounts in one call. With `apr_to_apy()`, `emergency_fund_target()`, and `ef_growth()`, it shows what an emergency fund earns while it waits. * [High-Yield Savings Accounts](https://mjfrigaard.github.io/fm-finance/high_yield_accounts.html) in Personal Finance: a field manual * Reference: `hysa_balance()` * Next: [Automating Savings](08-automating-savings.qmd) ### Automating Savings ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Once you know your savings rate and where the money will live, how much should leave each paycheck automatically? The [Automating Savings](https://mjfrigaard.github.io/fm-finance/automating_savings.html) chapter of the book argues for paying yourself first: savings move out before you see them, so saving no longer depends on willpower. In this page I'll answer the "how much" question with `monthly_savings()`, using the chapter's \$4,000 gross monthly pay so you can check every result against the book. Then we'll borrow functions from other chapters to follow the automated money into an emergency fund and an investment account. ## The automating savings function `monthly_savings()` follows the conventions on the [Get started](00-get-started.qmd) page. Note the units: its `savings_rate` argument is a decimal (`0.20`), while the `savings_rate()` function from [Savings Strategies](06-savings-strategies.qmd) returns a percent (`20.0`). | Function | Returns | Units | |---|---|---| | `monthly_savings()` | the monthly amount to pay yourself first | dollars per month (`savings_rate` is a decimal) | ## How much should you automate each month? The chapter's example earns \$48,000 a year, or \$4,000 a month before taxes, and aims for a 20% savings rate. The rate is measured on gross pay here because 401(k) contributions come out before taxes. Picture the gross paycheck as one bar cut into five equal fifths. One fifth goes to savings before you ever see it, and the rest is what you live on: ![\$4,000 of gross monthly pay with 20% automated to savings](assets/automating-savings-pyf-bar-model.png){fig-alt="Bar model: one horizontal bar for $4,000 of gross monthly pay, with dotted lines dividing it into five equal fifths. The first fifth is blue and labeled Automated savings ($800); the other four fifths are bluish green and labeled Everything else ($3,200)."} Taking one fifth of the bar is the same as multiplying it by 0.20, which is what `monthly_savings()` does: ```{python} #| label: pay-yourself-first automated = monthly_savings(gross_monthly_income=4000, savings_rate=0.20) automated ``` The paycheck sends \$`{python} f"{automated:,.0f}"` a month to savings, which leaves \$`{python} f"{4000 - automated:,.0f}"` for taxes and everything else. ## How do you split it across accounts? In practice the 20% goes to several places at once. The chapter splits it into an emergency fund, a 401(k) contribution large enough to get a typical employer match, and sinking funds (money set aside each month for a known future bill). `savings_rate` accepts an array, so one call prices every destination: ```{python} #| label: split split = pl.DataFrame({ "destination": ["emergency fund", "401(k) match", "sinking funds"], "rate": [0.10, 0.05, 0.05], }) split = split.with_columns( amount=monthly_savings(gross_monthly_income=4000, savings_rate=split["rate"]), ) split ``` The three amounts add up to \$`{python} f"{split['amount'].sum():,.0f}"`, the same 20% from the bar model. Payroll takes the 401(k) share before taxes, so the direct deposit split only needs to send the other \$`{python} f"{split['amount'].sum() - split['amount'][1]:,.0f}"` to the HYSA. ## Variations The chapter's long game is escalation: raise the savings rate with each raise instead of cutting spending. Its timeline pairs a growing salary with a rate that climbs five points every two years. Dividing each salary by 12 gives the monthly income, and arrays in both arguments price every year at once. `future_value_series()` from [Investing Basics](09-investing-basics.qmd) then shows what 30 years of each monthly amount could grow to at 7% (`rate` is per month here, so the yearly return is divided by 12): ```{python} #| label: escalation salary = [50000, 54000, 58000, 63000] rate = [0.15, 0.20, 0.25, 0.30] monthly = monthly_savings(gross_monthly_income=[s / 12 for s in salary], savings_rate=rate) pl.DataFrame({ "year": [1, 3, 5, 7], "salary": salary, "rate": rate, "monthly": monthly.round(2), "after_30_years": future_value_series(contribution=monthly, rate=0.07 / 12, periods=30 * 12).round().astype(int), }) ``` The monthly amounts match the chapter's \$625, \$900, \$1,208, and \$1,575, and the 30 year values match its \$762k to \$1.92M range. Most of that jump is paid for by raises, not by spending less. ::: {.callout-warning title="Limits"} `monthly_savings()` is a single multiplication, so it leaves a few things to you: * `savings_rate` is a decimal. Passing `20` instead of `0.20` returns \$80,000, not \$800, and no error is raised. * It doesn't check ranges. A negative income or a rate above 1 returns a result instead of an error. * It uses whatever income you give it. The chapter uses gross pay; a rate measured on take home pay gives a smaller amount. * It assumes a steady paycheck. For gig or commission income, the chapter suggests passing your average monthly income over the last six months. ::: ## Putting it together Back to the \$4,000 paycheck. The emergency fund line gets \$400 a month until the fund is full. The [Emergency Fund](05-emergency-fund.qmd) chapter's first job has \$2,400 a month in essential expenses, a four month target, and \$1,200 already saved. `emergency_fund_target()` and `months_to_ef_goal()` show how long the automation takes to finish the job: ```{python} #| label: ef-plan ef_monthly = monthly_savings(gross_monthly_income=4000, savings_rate=0.10) ef_target = emergency_fund_target(monthly_expenses=2400, months=4) ef_months = months_to_ef_goal( target=ef_target, current_balance=1200, monthly_contribution=ef_monthly ) ef_target, ef_months ``` The \$`{python} f"{ef_target:,.0f}"` fund is full in `{python} f"{ef_months}"` months without a single decision along the way. Once it's full, the chapter sends the \$400 to investing instead. `future_value_series()` shows what that redirected transfer could become over 30 years at 7%: ```{python} #| label: redirect redirected = future_value_series(contribution=ef_monthly, rate=0.07 / 12, periods=30 * 12) redirected ``` The same \$400 transfer could grow to about \$`{python} f"{redirected:,.0f}"`. As a last check, `percent_of_income()` from [Budgeting](03-budgeting.qmd) turns the automated dollars back into a rate. It returns a percent, the reverse of the decimal `monthly_savings()` takes: ```{python} #| label: round-trip percent_of_income(expense=automated, income=4000) ``` ## Recap Automation makes saving the default instead of a monthly decision. `monthly_savings()` turns a savings rate into the dollar amount to automate, and its array inputs price a split across accounts or a whole escalation plan in one call. Paired with the emergency fund and investing functions, it shows where those automated dollars end up. * [Automating Savings](https://mjfrigaard.github.io/fm-finance/automating_savings.html) in Personal Finance: a field manual * Reference: `monthly_savings()` * Next: [Investing Basics](09-investing-basics.qmd) ## Investing ### Investing Basics ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Investing math is mostly one idea (compounding) applied a few different ways. You want to know what money invested today grows into, how long it takes to double, and what a monthly habit adds up to. You also want to know how much of a return is left once inflation takes its share. In this page I'll answer those questions with `future_value()`, `rule_of_72()`, `future_value_series()`, and `real_return()`. The numbers come from the [Investing Basics](https://mjfrigaard.github.io/fm-finance/investing_basics.html) chapter of the book, so you can check every result against it. ## The investing basics functions All four functions accept arrays and follow the conventions in [Get started](00-get-started.qmd). Rates are decimals, with one exception: `rule_of_72()` takes a percent. | Function | Returns | Units | |---|---|---| | `future_value()` | what a single amount grows to | dollars (`rate` is a decimal) | | `rule_of_72()` | years for money to double | years (`annual_return_pct` is a percent) | | `future_value_series()` | what a regular contribution grows to | dollars (`rate` is per period) | | `real_return()` | the return left after inflation | decimal (`0.039` is 3.9%) | ## How much does a single amount grow? The chapter invests \$10,000 at 7% a year. Each year adds 7% to the balance, and the next year's 7% is applied to that larger balance. Interest earns interest. Each bar below is the one before it multiplied by the same growth factor. The bars curve upward instead of climbing in a straight line: ![\$10,000 growing at 7%: value at each checkpoint](assets/investing-basics-compound-bar-model.png){fig-alt="Bar chart of $10,000 invested at 7% a year, with bars at year 0 ($10,000), year 5 ($14,026), year 10 ($19,672), year 20 ($38,697), and year 30 ($76,123). Each bar is taller than the last, and the jumps between bars get bigger over time, so the growth curves upward."} `future_value()` multiplies the starting amount by (1 + rate) once for every year: ```{python} #| label: fv-10 fv_10 = future_value(present_value=10000, rate=0.07, years=10) fv_10 ``` After 10 years, \$10,000 grows to \$`{python} f"{fv_10:,.2f}"`. That's almost exactly double, which is what the rule of 72 predicts. ### How long until money doubles? The rule of 72 is a shortcut: divide 72 by the yearly return (as a percent) to estimate the years it takes to double. `rule_of_72()` is the one function in the package that takes a percent, so 7% goes in as `7`: ```{python} #| label: rule-72 double_years = rule_of_72(annual_return_pct=7) double_years ``` At 7%, money doubles about every `{python} f"{double_years:.1f}"` years. That matches the bar model: \$10,000 at year 0 is close to \$20,000 at year 10 and close to \$40,000 at year 20. ## What do regular contributions grow to? Most people don't invest one lump sum. They invest a fixed amount every month. The chapter's example is \$500 a month for 30 years at 7% a year. Monthly investing builds wealth in two layers: the money you put in, and the growth on everything you've already put in. The bar model separates the two: ![\$500 a month at 7%: contributed vs. gains](assets/investing-basics-fv-series-bar-model.png){fig-alt="Stacked bar chart of $500 a month invested at 7% at three checkpoints: year 10 ($86,542), year 20 ($260,463), and year 30 ($609,985). The dark green bottom layer is money contributed and grows in equal steps; the light green top layer is investment gains. By year 30 the gains layer is more than twice as tall as the contributions layer."} `future_value_series()` adds up every contribution and its growth in one step. The `rate` is the rate per period, so a monthly series uses the yearly rate divided by 12, and `periods` is the number of months: ```{python} #| label: fv-series-30 fv_series_30 = future_value_series(contribution=500, rate=0.07 / 12, periods=30 * 12) contributed_30 = 500 * 30 * 12 fv_series_30, contributed_30 ``` After 30 years the account holds about \$`{python} f"{fv_series_30:,.0f}"`, and only \$`{python} f"{contributed_30:,.0f}"` of it is money you put in. The other \$`{python} f"{fv_series_30 - contributed_30:,.0f}"` is growth. ## What is a return worth after inflation? A 7% return sounds good, but prices rise too. The chapter sets a 7% nominal return (the number before inflation) against 3% inflation. The real return is what's left: ![Nominal return, inflation, and real return](assets/investing-basics-real-return-bar-model.png){fig-alt="Bar chart of three rates: a nominal return of 7%, inflation of 3%, and a real return of about 3.9%. The real return bar is a little shorter than the 4% you would get by subtracting inflation from the nominal return."} The real return isn't a simple subtraction; it's a ratio, because both rates compound. `real_return()` divides one growth factor by the other: ```{python} #| label: real-7-3 real = real_return(nominal=0.07, inflation=0.03) real ``` The real return is `{python} f"{real * 100:.2f}"`%, a little less than the 4% you'd get by subtracting. The result is a decimal, so you can pass it straight into `future_value()` or `future_value_series()` to get an answer in today's dollars. ## Variations Array inputs answer several versions of a question in one call. Passing a few returns to `rule_of_72()`, then growing \$10,000 for that many years with `future_value()`, shows how close the shortcut gets to an exact double: ```{python} #| label: rule-72-check pcts = [4, 7, 10] doubling = rule_of_72(annual_return_pct=pcts) pl.DataFrame({ "return_pct": pcts, "years_to_double": doubling, "value": future_value( present_value=10000, rate=[p / 100 for p in pcts], years=doubling ), }) ``` Each value lands within a few hundred dollars of \$20,000, so the rule of 72 is a good shortcut for returns in this range. ### One call compares every checkpoint Passing several horizons to `periods` reproduces each bar in the contributions bar model, with the money contributed alongside: ```{python} #| label: fv-series-horizons years = [10, 20, 30] pl.DataFrame({ "years": years, "contributed": [500 * 12 * y for y in years], "value": future_value_series( contribution=500, rate=0.07 / 12, periods=[y * 12 for y in years] ), }) ``` ::: {.callout-warning title="Limits"} These functions are for planning, not prediction. A few things they don't do: * `future_value()` and `future_value_series()` assume the same return every year. Real returns bounce around, and they ignore taxes, fund fees, and inflation unless you pass a real return. * `future_value_series()` assumes each contribution is made at the end of the period. The `rate` is per period, so passing a yearly rate with monthly `periods` gives a much larger (wrong) answer. A 0% rate returns the sum of the contributions. * `rule_of_72()` is an estimate, and it takes a percent (`7`, not `0.07`). A return of 0 or less raises a `ValueError`, because money that doesn't grow never doubles. * `real_return()` returns a decimal, not a percent. ::: ## Putting it together Back to the \$500 a month for 30 years. The \$`{python} f"{fv_series_30:,.0f}"` from earlier is in future dollars. Passing the real return from the inflation section as the monthly rate gives the same account in today's dollars: ```{python} #| label: fv-series-real fv_series_today = future_value_series( contribution=500, rate=real_return(nominal=0.07, inflation=0.03) / 12, periods=360 ) fv_series_today ``` In today's dollars the account is worth about \$`{python} f"{fv_series_today:,.0f}"`. That's less than the headline number, but it's still nearly twice the \$`{python} f"{contributed_30:,.0f}"` you put in. Small amounts work the same way. The chapter's recap invests \$50 a month for 30 years at 7%: ```{python} #| label: fv-series-50 small_habit = future_value_series(contribution=50, rate=0.07 / 12, periods=360) small_habit ``` \$50 a month becomes about \$`{python} f"{small_habit:,.0f}"`. The [Budgeting](03-budgeting.qmd) page puts a price on spending decisions with the same compounding math in `opportunity_cost()`. ## Recap Compounding is the force multiplier behind every investing decision. `future_value()` grows a single amount, `rule_of_72()` estimates how long it takes to double, and `future_value_series()` grows a monthly habit. `real_return()` takes inflation out of the return, so any of the others can answer in today's dollars. * [Investing Basics](https://mjfrigaard.github.io/fm-finance/investing_basics.html) in Personal Finance: a field manual * Reference: `future_value()`, `rule_of_72()`, `future_value_series()`, `real_return()` * Next: [Retirement Accounts](10-retirement-accounts.qmd) ### Retirement Accounts ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` A retirement account is a container for your investments, and the container decides how they get taxed. Two questions decide most of the value. How much free money does the employer match add? And does paying tax now (Roth) or later (Traditional) leave you with more? In this page I'll answer both with `employer_match()` and `after_tax_value()`, using the numbers from the [Retirement Accounts](https://mjfrigaard.github.io/fm-finance/retirement_accounts.html) chapter of the book. ## The retirement account functions Both functions accept arrays and follow the conventions in [Get started](00-get-started.qmd): every rate and percentage goes in as a decimal. | Function | Returns | Units | |---|---|---| | `employer_match()` | what the employer adds each year | dollars per year (all percentages are decimals) | | `after_tax_value()` | what a contribution is worth after tax and growth | dollars (`tax_rate` and `rate` are decimals) | ## How much is the employer match worth? The chapter's example is a \$45,000 salary with a common deal: the employer matches 50% of your contributions on the first 6% of salary. If you put in 6%, the employer adds another 3%. Think of what goes into the 401(k) as one bar. Your contribution is the first slice, and the employer adds a second, smaller slice on top: ![6% of a \$45,000 salary, plus a 50% employer match](assets/retirement-accounts-match-bar-model.png){fig-alt="Horizontal stacked bar of yearly 401(k) deposits on a $45,000 salary, with a green slice labeled Your contribution $2,700 and a blue slice labeled Employer match $1,350. The match slice is half the length of the contribution slice, bringing the total to $4,050."} The match slice is your contribution (up to the match limit) times the match rate. `employer_match()` takes the salary, your contribution, the match limit, and the match rate, all as decimals: ```{python} #| label: match-6 match_6 = employer_match( salary=45000, contribution_pct=0.06, match_limit_pct=0.06, match_rate=0.50 ) match_6 ``` Contributing 6% earns \$`{python} f"{match_6:,.0f}"` a year in free money. That's an instant 50% return on the \$2,700 you put in. ### What if you contribute less? Many employers enroll new hires at 3%. At that rate the match slice shrinks with your contribution: ```{python} #| label: match-3 match_3 = employer_match( salary=45000, contribution_pct=0.03, match_limit_pct=0.06, match_rate=0.50 ) match_3 ``` At 3% the employer adds only \$`{python} f"{match_3:,.0f}"`, so the default rate leaves \$`{python} f"{match_6 - match_3:,.0f}"` a year on the table. ## Should you pay tax now or later? Every retirement account taxes your money at some point. A Roth account taxes the contribution now, and the rest grows tax free. A Traditional account lets the whole contribution grow, and the tax comes out in retirement. The chapter sets aside \$1,000, grows it at 7% for 40 years, and uses a 12% tax rate both now and later. ![\$1,000 after 40 years at 7%, with a 12% tax rate now and later](assets/retirement-accounts-roth-bar-model.png){fig-alt="Stacked bar chart comparing a Roth account (tax now) and a Traditional account (tax later) for $1,000 grown at 7% for 40 years. Each bar has a large green layer labeled yours to spend and a thin vermillion layer on top for taxes plus the growth they would have earned. Both bars are the same height and both keep $13,178."} The \$120 of Roth tax looks small today, but it would have grown along with everything else. Counted that way, the two bars are the same. Multiplying by (1 minus the tax rate) gives the same answer whether you do it first or last. `after_tax_value()` does that multiplication once and then grows the rest: ```{python} #| label: roth-12 roth = after_tax_value(contribution=1000, tax_rate=0.12, rate=0.07, years=40) roth ``` With a 12% rate now and later, either account leaves you about \$`{python} f"{roth:,.0f}"`. The only thing that changes the answer is a different tax rate in retirement. If that rate is 22%, the Traditional account leaves less: ```{python} #| label: trad-22 traditional = after_tax_value(contribution=1000, tax_rate=0.22, rate=0.07, years=40) traditional ``` The Traditional account keeps about \$`{python} f"{traditional:,.0f}"`, or \$`{python} f"{roth - traditional:,.0f}"` less than the Roth. A Roth wins when your tax rate today is lower than it will be in retirement. ## Variations Array inputs compare several choices in one call. Here is the same \$45,000 job at four contribution rates: ```{python} #| label: match-rates rates = [0.0, 0.03, 0.06, 0.10] pl.DataFrame({ "contribution_pct": rates, "you_put_in": [45000 * r for r in rates], "employer_adds": employer_match( salary=45000, contribution_pct=rates, match_limit_pct=0.06, match_rate=0.50 ), }) ``` The match stops growing at 6%. Contributing 10% still helps your retirement, but the extra 4% isn't matched. ### Which tax rate wins? `after_tax_value()` takes several tax rates at once. Use your rate today for the Roth and your expected rate in retirement for the Traditional account: ```{python} #| label: tax-rates tax_rates = [0.10, 0.12, 0.22, 0.24] pl.DataFrame({ "tax_rate": tax_rates, "after_tax": after_tax_value( contribution=1000, tax_rate=tax_rates, rate=0.07, years=40 ), }) ``` Find your rate now and your rate later in the table. Whichever account is taxed at the lower rate leaves you more. ::: {.callout-warning title="Limits"} These functions cover the math in the chapter, not every plan rule: * `employer_match()` handles a single tier match ("50% of the first 6%"). Tiered formulas such as "100% of the first 3%, then 50% of the next 2%" need one call per tier, added together. * `employer_match()` ignores vesting, the yearly contribution limit (\$24,500 in 2026), and any match paid only at year end. * `after_tax_value()` applies one tax rate to the whole amount. It ignores the 10% early withdrawal penalty, state taxes, and the fact that income in retirement spans several brackets. * `after_tax_value()` assumes the same return every year and the same investments in both accounts. ::: ## Putting it together Back to the \$45,000 job at 6%. You put in \$2,700 a year and the employer adds \$`{python} f"{match_6:,.0f}"`. Treating each year's deposits as one yearly contribution, `future_value_series()` from [Investing Basics](09-investing-basics.qmd) shows what 40 years of them grow to, and what the match alone adds: ```{python} #| label: match-40 deposits = 2700 + match_6 total_40 = future_value_series(contribution=deposits, rate=0.07, periods=40) match_40 = future_value_series(contribution=match_6, rate=0.07, periods=40) total_40, match_40 ``` The account grows to about \$`{python} f"{total_40:,.0f}"`, and \$`{python} f"{match_40:,.0f}"` of that comes from the match. That's the cost of skipping it. The chapter's last warning is about cashing out an old 401(k). A \$5,000 balance cashed out at 22 loses a 12% income tax and a 10% penalty. With `rate=0` and `years=0`, `after_tax_value()` just takes out the tax, so a combined 22% gives the check you'd receive. `future_value()` shows what the same \$5,000 becomes if you leave it invested until 67: ```{python} #| label: cash-out cash_now = after_tax_value(contribution=5000, tax_rate=0.12 + 0.10, rate=0, years=0) left_invested = future_value(present_value=5000, rate=0.07, years=67 - 22) cash_now, left_invested ``` Cashing out leaves \$`{python} f"{cash_now:,.0f}"`. Leaving it invested grows it to about \$`{python} f"{left_invested:,.0f}"`, and that's before any tax in retirement. ## Recap The employer match is part of your pay, and `employer_match()` shows how much of it you collect at each contribution rate. `after_tax_value()` shows that Roth versus Traditional comes down to one comparison: your tax rate now versus your tax rate later. Early in a career, when that rate is low, Roth is usually the better default. * [Retirement Accounts](https://mjfrigaard.github.io/fm-finance/retirement_accounts.html) in Personal Finance: a field manual * Reference: `employer_match()`, `after_tax_value()` * Next: [Index Funds](11-index-funds.qmd) ### Index Funds ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` You can't control what the market does, but you can control what you pay. Index fund math is about that one thing: what fees cost you. A fee looks tiny for a single year, and it comes out every year, so each dollar it takes stops growing. In this page I'll measure both with `yearly_fee()` and `future_value_after_fees()`, using the numbers from the [Index Funds](https://mjfrigaard.github.io/fm-finance/index_funds.html) chapter of the book. ## The index fund functions Both functions accept arrays and follow the conventions in [Get started](00-get-started.qmd). An expense ratio is a decimal, so a 0.04% fee goes in as `0.0004`. | Function | Returns | Units | |---|---|---| | `yearly_fee()` | the fee a fund takes in one year | dollars (`expense_ratio` is a decimal) | | `future_value_after_fees()` | what monthly contributions grow to after fees | dollars (`annual_return` and `expense_ratio` are decimals) | ## What does a fund charge this year? An expense ratio is the yearly fee a fund charges, as a share of the money you have in it. The chapter puts \$10,000 in two funds: a broad index fund that charges 0.04%, and an active fund that charges 1%. Each bar below is the slice each fund takes from the \$10,000 in one year: ![One year of fees on \$10,000](assets/index-funds-fee-bar-model.png){fig-alt="Horizontal bar chart of one year of fees on $10,000. The index fund (0.04%) bar is a tiny green sliver labeled $4; the active fund (1%) bar is a long vermillion bar labeled $100, 25 times as long."} `yearly_fee()` multiplies the balance by the expense ratio. Passing both ratios at once returns both fees: ```{python} #| label: fee-10k fees = yearly_fee(balance=10000, expense_ratio=[0.0004, 0.01]) fees ``` The index fund charges \$`{python} f"{fees[0]:,.0f}"` a year and the active fund charges \$`{python} f"{fees[1]:,.0f}"`, `{python} f"{fees[1] / fees[0]:.0f}"` times as much. Neither number feels large, which is why the fee is easy to miss. ## What do fees cost over a lifetime? The chapter follows someone who invests \$300 a month at a 7% return for 40 years. The two bars at each checkpoint get the same contributions and the same return; the only difference is the fee. ![\$300 a month at 7%, with a 0.04% fee vs. a 1% fee](assets/index-funds-fee-drag-bar-model.png){fig-alt="Grouped bar chart of $300 a month invested at 7% at four checkpoints, with a green bar for the index fund (0.04%) and a vermillion bar for the active fund (1%). The pairs are $52k and $49k at year 10, $156k and $139k at year 20, $363k and $301k at year 30, and $779k and $597k at year 40. The gap between the bars widens at every checkpoint."} The fee comes out of the return, so the math is the contribution formula from [Investing Basics](09-investing-basics.qmd) with a smaller rate. `future_value_after_fees()` subtracts the expense ratio from the return, then compounds the monthly contributions: ```{python} #| label: fee-drag-40 index_fund = future_value_after_fees( contribution=300, annual_return=0.07, expense_ratio=0.0004, years=40 ) active_fund = future_value_after_fees( contribution=300, annual_return=0.07, expense_ratio=0.01, years=40 ) index_fund, active_fund, index_fund - active_fund ``` After 40 years the index fund grows to about \$`{python} f"{index_fund:,.0f}"` and the active fund to about \$`{python} f"{active_fund:,.0f}"`. Both investors put in the same \$`{python} f"{300 * 12 * 40:,.0f}"`. The 1% fee cost \$`{python} f"{index_fund - active_fund:,.0f}"`, about `{python} f"{(index_fund - active_fund) / index_fund * 100:.0f}"`% of what the index fund investor ended up with. ## Variations Passing several horizons to `years` reproduces every pair of bars in the bar model in one call per fund: ```{python} #| label: fee-drag-horizons years = [10, 20, 30, 40] fee_drag = pl.DataFrame({ "years": years, "index_fund": future_value_after_fees(300, 0.07, 0.0004, years), "active_fund": future_value_after_fees(300, 0.07, 0.01, years), }).with_columns(cost_of_fees=pl.col("index_fund") - pl.col("active_fund")) fee_drag ``` The cost of the fee grows faster than the balances do, because the money it takes would have compounded too. ### Comparing expense ratios The chapter suggests looking for funds under 0.10%. Passing a range of expense ratios shows what each one leaves after 40 years: ```{python} #| label: fee-ratios ratios = [0.0003, 0.0004, 0.001, 0.005, 0.01] pl.DataFrame({ "expense_ratio": ratios, "fee_on_10k": yearly_fee(balance=10000, expense_ratio=ratios), "after_40_years": future_value_after_fees(300, 0.07, ratios, 40), }) ``` The difference between 0.03% and 0.10% is small. The difference between 0.10% and 1% is not. ::: {.callout-warning title="Limits"} A few things these functions leave out: * `yearly_fee()` uses one balance. A fund charges its fee on your balance through the year, so a growing account pays a little more than this. * `future_value_after_fees()` subtracts the expense ratio from the return and assumes both stay the same every year. Contributions are monthly, made at the end of each month. * Neither function counts sales charges (loads), trading costs, advisor fees, or taxes in a taxable account. ::: ## Putting it together The 0.04% fee looks harmless at \$4 a year, but it's charged on the balance, and the balance gets large. `yearly_fee()` shows what each fund charges in year 40, using each fund's own ending balance: ```{python} #| label: fee-year-40 fees_40 = yearly_fee(balance=[index_fund, active_fund], expense_ratio=[0.0004, 0.01]) fees_40 ``` In the last year alone, the active fund takes \$`{python} f"{fees_40[1]:,.0f}"` while the index fund takes \$`{python} f"{fees_40[0]:,.0f}"`. With an expense ratio of 0, `future_value_after_fees()` gives the same answer as `future_value_series()` from [Investing Basics](09-investing-basics.qmd). Comparing the fee free number with the index fund shows how little a low fee costs: ```{python} #| label: no-fee no_fee = future_value_series(contribution=300, rate=0.07 / 12, periods=40 * 12) no_fee, no_fee - index_fund ``` A 0.04% fee costs about \$`{python} f"{no_fee - index_fund:,.0f}"` over 40 years, compared with \$`{python} f"{index_fund - active_fund:,.0f}"` for a 1% fee. ## Recap Fees are the one part of investing you control. `yearly_fee()` turns an expense ratio into dollars for one year, and `future_value_after_fees()` shows what that fee costs over a working lifetime. A 1% fee can cost close to a quarter of your money, so look for broad index funds that charge under 0.10%. * [Index Funds](https://mjfrigaard.github.io/fm-finance/index_funds.html) in Personal Finance: a field manual * Reference: `yearly_fee()`, `future_value_after_fees()` * Next: [Asset Allocation](12-asset-allocation.qmd) ### Asset Allocation ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Your asset allocation is how you split your investments between stocks and bonds. It does more to decide how your money grows (and how bumpy the ride feels) than which funds you pick. Asset allocation math answers two questions. What does a split do in a good year and a bad year? And how much do you move when you rebalance? In this page I'll answer both with `portfolio_return()` and `rebalance_amount()`, using the numbers from the [Asset Allocation](https://mjfrigaard.github.io/fm-finance/asset_allocation.html) chapter of the book. ## The asset allocation functions Both functions accept arrays and follow the conventions in [Get started](00-get-started.qmd): shares and returns are decimals. `portfolio_return()` also accepts polars expressions, so it works inside `with_columns()`. | Function | Returns | Units | |---|---|---| | `portfolio_return()` | the return on a stock and bond split | decimal (`-0.32` is a 32% loss) | | `rebalance_amount()` | how much to buy or sell to reach a target | dollars (positive buys, negative sells) | ## What does a split do in good and bad years? The chapter splits \$10,000 three ways: 100/0, 80/20, and 60/40 (stocks/bonds). It assumes stocks earn 10% in an average year and lose 40% in a bad year. Bonds earn 4% in an average year and break even in a bad year. These are round numbers for illustration, not predictions. ![\$10,000 in an average year and a bad year, by stock/bond split](assets/asset-allocation-mix-bar-model.png){fig-alt="Bar chart of the change in $10,000 for three stock/bond splits, with a green bar for an average year and a vermillion bar for a bad year. The average year gains are $1,000 for 100/0, $880 for 80/20, and $760 for 60/40. The bad year losses are $4,000, $3,200, and $2,400. Adding bonds shrinks the gains a little and the losses a lot."} Each bar is a weighted average: the stock return times the share in stocks, plus the bond return times the share in bonds. `portfolio_return()` takes the share in stocks and the two returns. Here is the 80/20 split in a bad year and an average year: ```{python} #| label: mix-80-20 bad_80 = portfolio_return(stock_pct=0.80, stock_return=-0.40, bond_return=0.0) avg_80 = portfolio_return(stock_pct=0.80, stock_return=0.10, bond_return=0.04) bad_80, avg_80 ``` In a bad year the 80/20 split loses `{python} f"{-bad_80 * 100:.0f}"`%, or \$`{python} f"{-bad_80 * 10000:,.0f}"` on \$10,000. In an average year it gains `{python} f"{avg_80 * 100:.1f}"`%, or \$`{python} f"{avg_80 * 10000:,.0f}"`. The result is a decimal, so multiply by the balance to get dollars. ## How much do you move when you rebalance? Your split won't stay where you set it. The chapter starts with \$10,000 at 80/20 (\$8,000 in stocks and \$2,000 in bonds), then stocks drop 30%. The stock part of the bar shrinks to \$5,600, the total falls to \$7,600, and stocks are now only about 74% of it. ![An 80/20 portfolio before a 30% stock drop, after it, and after rebalancing](assets/asset-allocation-rebalance-bar-model.png){fig-alt="Horizontal stacked bar chart of a portfolio at three stages, with stocks in dark green and bonds in light green. Before the drop it holds $8,000 in stocks and $2,000 in bonds. After the drop it holds $5,600 and $2,000. After rebalancing the total is still $7,600, split $6,080 in stocks and $1,520 in bonds."} Rebalancing moves just enough from bonds to stocks to get back to 80/20. The target for stocks is 80% of the new total, and `rebalance_amount()` returns the difference between that target and what you hold: ```{python} #| label: rebalance-stocks move = rebalance_amount(target_pct=0.80, total=5600 + 2000, current_amount=5600) move ``` A positive answer means buy. You move \$`{python} f"{move:,.0f}"` from bonds into stocks, which means buying stocks while they're down. That's exactly what rebalancing is for. ## Variations The chapter's Python code builds all three splits at once with polars. Because `portfolio_return()` accepts `pl.col("stocks")`, it works inside `with_columns()` like any other expression. Multiplying by the \$10,000 balance gives the dollar labels from the bar model: ```{python} #| label: mix-polars pl.DataFrame({"stocks": [1.0, 0.8, 0.6]}).with_columns( average=portfolio_return(pl.col("stocks"), 0.10, 0.04), bad=portfolio_return(pl.col("stocks"), -0.40, 0.0), ).with_columns( average_dollars=pl.col("average") * 10000, bad_dollars=pl.col("bad") * 10000, ) ``` Moving from 100/0 to 60/40 gives up \$240 in an average year and saves \$1,600 in a bad one. ### Rebalancing every fund at once `rebalance_amount()` takes arrays, so one call rebalances every fund in a portfolio. Suppose the chapter's three fund portfolio (60% US stocks, 30% international stocks, 10% bonds) has drifted to \$6,600, \$2,500, and \$900: ```{python} #| label: rebalance-three-fund current = [6600, 2500, 900] pl.DataFrame({ "fund": ["US stocks", "international stocks", "bonds"], "target_pct": [0.60, 0.30, 0.10], "current": current, "move": rebalance_amount( target_pct=[0.60, 0.30, 0.10], total=sum(current), current_amount=current ), }) ``` Sell \$600 of US stocks and use it to buy the other two. The moves add up to zero, because rebalancing only shifts money between funds. ::: {.callout-warning title="Limits"} Both functions are simple on purpose: * `portfolio_return()` covers two assets (stocks and bonds) for one year. The returns you pass are assumptions, and it ignores fees, taxes, and inflation. * `rebalance_amount()` doesn't check that your targets add up to 100%, and `total` has to include `current_amount`. * `rebalance_amount()` ignores trading costs and the taxes that selling can trigger in a taxable account. Inside a 401(k) or IRA, selling doesn't trigger taxes. ::: ## Putting it together Here is the chapter's bad year from start to finish. \$10,000 at 80/20 meets a 30% stock drop, and bonds break even. `portfolio_return()` gives the loss on the whole portfolio, and `rebalance_amount()` gives the move: ```{python} #| label: drop-and-rebalance drop = portfolio_return(stock_pct=0.80, stock_return=-0.30, bond_return=0.0) after_drop = 10000 * (1 + drop) to_stocks = rebalance_amount( target_pct=0.80, total=after_drop, current_amount=8000 * (1 - 0.30) ) drop, after_drop, to_stocks ``` The portfolio falls `{python} f"{-drop * 100:.0f}"`% to \$`{python} f"{after_drop:,.0f}"`, and rebalancing moves \$`{python} f"{to_stocks:,.0f}"` into stocks. How long until it's back to \$10,000? If the next years are average ones, the 80/20 split grows at `{python} f"{avg_80 * 100:.1f}"`% a year, and `future_value()` from [Investing Basics](09-investing-basics.qmd) shows the path: ```{python} #| label: recovery recovery_years = [1, 2, 3, 4] pl.DataFrame({ "years": recovery_years, "value": future_value(present_value=after_drop, rate=avg_80, years=recovery_years), }) ``` The portfolio is back above \$10,000 in year 4. Staying invested (and rebalancing into the drop) is what makes the recovery possible. ## Recap Asset allocation is how you split your money between stocks and bonds, and it matters more than which funds you pick. `portfolio_return()` shows what a split does in a good year and a bad one, and it works on polars columns as well as numbers. `rebalance_amount()` shows how much to move to get back on target, which makes you buy low without predicting anything. * [Asset Allocation](https://mjfrigaard.github.io/fm-finance/asset_allocation.html) in Personal Finance: a field manual * Reference: `portfolio_return()`, `rebalance_amount()` * Next: [Taxes](13-taxes.qmd) ## Taxes and insurance ### Taxes ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Taxes are the biggest bill most people pay, and two questions come up again and again. How much federal income tax do you owe on your salary? And how much of a raise do you keep once a higher bracket takes its share? The [Taxes](https://mjfrigaard.github.io/fm-finance/taxes.html) chapter of the book answers both by slicing income into brackets. In this page I'll answer the same questions with `income_tax()` and `raise_kept()`, using the chapter's numbers so you can check every result against the book. ## The tax functions Both functions take single numbers only (see the conventions table in [Get started](00-get-started.qmd)). To compare several incomes, loop over them; the Variations section shows how. | Function | Returns | Units | |---|---|---| | `income_tax()` | 2026 federal income tax for a single filer | dollars per year | | `raise_kept()` | the part of a raise left after federal income tax | dollars per year | ## How much tax do you owe on a salary? The chapter's example is a \$45,000 salary for a single filer in 2026. The question is the federal income tax bill, and what share of the salary it takes. Think of the salary as one long bar. The first \$16,100 is covered by the standard deduction and isn't taxed. The next \$12,400 is taxed at 10%. The last \$16,500 is taxed at 12%: ![A \$45,000 salary, sliced by the standard deduction and 2026 tax brackets](assets/taxes-bracket-bar-model.png){fig-alt="Stacked horizontal bar of a $45,000 salary split into three slices. A pale green slice of $16,100 for the standard deduction owes $0 tax, a bluish green slice of $12,400 in the 10% bracket owes $1,240, and a blue slice of $16,500 in the 12% bracket owes $1,980. Only the last slice is taxed at the top rate."} `income_tax()` subtracts the deduction, multiplies each slice by its own rate, and adds up the slices: ```{python} #| label: salary-tax tax = income_tax(income=45000) effective = tax / 45000 tax, effective ``` The tax is \$`{python} f"{tax:,.0f}"`, an effective rate of `{python} f"{effective * 100:.1f}"`%. That is well below 12%, the marginal rate on this salary's last dollar. The effective rate is a decimal here because we divided it ourselves; `income_tax()` returns dollars, not a rate. ## How much of a raise do you keep? Now imagine you earn \$66,000 and get a \$2,000 raise. Taxable income goes from \$49,900 to \$51,900, which crosses the 22% line at \$50,400. The fear is that the higher bracket eats the raise. The bar below is just the raise. The first \$500 fills the rest of the 12% bracket, and only the last \$1,500 is taxed at 22%: ![A \$2,000 raise that crosses into the 22% bracket](assets/taxes-raise-bar-model.png){fig-alt="Stacked horizontal bar of a $2,000 raise split into three parts. A long bluish green slice labeled You keep $1,610 fills most of the bar, a thin pale green slice is $60 of tax at 12%, and a vermillion slice is $330 of tax at 22%. Most of the raise stays with you even after crossing into the higher bracket."} `raise_kept()` takes the tax on the new income, subtracts the tax on the old income, and takes that difference out of the raise: ```{python} #| label: raise kept = raise_kept(old_income=66000, raise_amount=2000) extra_tax = income_tax(income=68000) - income_tax(income=66000) kept, extra_tax ``` You keep \$`{python} f"{kept:,.0f}"` of the \$2,000 raise, and the extra tax is \$`{python} f"{extra_tax:,.0f}"`. Crossing into a higher bracket never makes a raise cost you money; only the dollars above the line pay the higher rate. ## The call stack `raise_kept()` doesn't have its own bracket table. It calls `income_tax()` twice, once on the new income and once on the old income, and subtracts the two results. The tree below shows that relationship: ```{python} #| label: call-stack #| eval: false from rich import print from rich.tree import Tree tree = Tree("raise_kept()") tree.add("income_tax(old_income + raise_amount)") tree.add("income_tax(old_income)") print(tree) ``` ``` raise_kept() ├── income_tax(old_income + raise_amount) └── income_tax(old_income) ``` Any change to the brackets in `income_tax()` flows straight into `raise_kept()`. ## Variations Because both functions take single numbers, a list comprehension compares several salaries. The table below puts the tax and the effective rate side by side: ```{python} #| label: incomes incomes = [30000, 45000, 66000, 100000, 150000] taxes = [income_tax(income=i) for i in incomes] pl.DataFrame({ "income": incomes, "tax": taxes, "effective_rate": [t / i for t, i in zip(taxes, incomes)], }) ``` The effective rate climbs with income, but it stays below each salary's top bracket. The same pattern works for raises. Here is a \$2,000 raise at each salary: ```{python} #| label: raises pl.DataFrame({ "income": incomes, "kept": [raise_kept(old_income=i, raise_amount=2000) for i in incomes], }) ``` ::: {.callout-warning title="Limits"} `income_tax()` hard codes the 2026 federal brackets for a single filer and a \$16,100 standard deduction. A few other limits apply: * Other years, married filers, and heads of household need different brackets, which the function doesn't take. * You can pass a different `deduction` (for example, itemized deductions), but not different brackets. * Neither function counts credits, FICA (7.65%), state or local taxes, or self employment tax. * Both functions take single numbers only. A list or array raises a `ValueError`; text raises a `TypeError`. ::: ## Putting it together Back to the \$45,000 salary. Federal income tax is only part of what comes out of the paycheck. FICA (Social Security and Medicare) takes 7.65% of every dollar, with no deduction. `percent_of_income()` from the [Budgeting](03-budgeting.qmd) page shows how much of the salary the two together claim: ```{python} #| label: paycheck salary = 45000 fica = salary * 0.0765 federal = income_tax(income=salary) total = fica + federal total_share = percent_of_income(expense=total, income=salary) fica, federal, total_share ``` FICA takes \$`{python} f"{fica:,.2f}"` and federal income tax takes \$`{python} f"{federal:,.0f}"`. Together they claim `{python} f"{total_share:.1f}"`% of the salary, before any state tax. Next, a \$2,000 raise on the same salary. All of it stays in the 12% bracket, so you keep a little more than in the \$66,000 example: ```{python} #| label: raise-45k raise_kept(old_income=salary, raise_amount=2000) ``` This number is before FICA, which takes another 7.65% of the raise. ## Recap Tax brackets apply to slices of income, not the whole salary. `income_tax()` adds up the tax on each slice, and dividing by income gives the effective rate. `raise_kept()` calls `income_tax()` twice to show that a raise always leaves you with more money. * [Taxes](https://mjfrigaard.github.io/fm-finance/taxes.html) in Personal Finance: a field manual * Reference: `income_tax()`, `raise_kept()` * Next: [Insurance](14-insurance.qmd) ### Insurance ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Insurance math helps with two everyday choices. Which deductible should you pick, and which health plan costs less over a year? The [Insurance](https://mjfrigaard.github.io/fm-finance/insurance.html) chapter of the book answers both with a little arithmetic. In this page I'll answer the same questions with `break_even_years()` and `plan_cost()`, using the chapter's numbers so you can check every result against the book. ## The insurance functions Both functions accept arrays, so one call can compare several deductibles or several kinds of years. | Function | Returns | Units | |---|---|---| | `break_even_years()` | years of premium savings needed to cover a higher deductible | years, not rounded | | `plan_cost()` | the yearly cost of a health plan | dollars per year | ## Which deductible should you pick? The chapter's car insurance costs \$1,500 a year with a \$500 deductible, or \$1,350 a year with a \$1,000 deductible. The higher deductible saves \$150 a year, but you pay \$500 more each time you file a claim. Each bar below is the savings piling up year after year. The dashed line is the extra \$500 you'd pay on a claim: ![Savings from a \$1,000 deductible vs. a \$500 deductible, year by year](assets/insurance-deductible-bar-model.png){fig-alt="Bar chart of cumulative premium savings over five years: $150, $300, $450, $600, and $750. A dashed vermillion line at $500 is labeled Extra $500 per claim. Years 1 to 3 are bluish green and sit below the line; years 4 and 5 are blue and rise above it, so the savings pass the extra deductible a little after year 3."} `break_even_years()` divides the gap between the deductibles by the yearly savings: ```{python} #| label: deductible years = break_even_years(high_deductible=1000, low_deductible=500, yearly_savings=150) years ``` The savings cover the extra deductible after about `{python} f"{years:.1f}"` years. If you go longer than that between claims, the higher deductible comes out ahead. Most drivers go much longer, but pick it only if your emergency fund can cover the \$1,000. ## Which health plan costs less? Your job offers two plans. Plan A has a \$100 monthly premium and a \$3,000 out of pocket maximum. Plan B is a high deductible plan with a \$40 monthly premium, a \$5,000 out of pocket maximum, and \$500 a year from your employer into your HSA. We'll compare a healthy year (about \$300 of care) with the worst year possible. ![Total yearly cost of two health plans in a healthy year and the worst year](assets/insurance-health-bar-model.png){fig-alt="Grouped bar chart of yearly health plan cost in two kinds of year. In a healthy year, Plan A (bluish green) costs $1,500 and Plan B (blue) costs $280. In the worst year, Plan A costs $4,200 and Plan B costs $4,980. Plan B is far cheaper in a healthy year and somewhat more expensive in the worst year."} Each bar is twelve premiums, plus your medical bills up to the out of pocket maximum, minus the employer's HSA money. `plan_cost()` takes `float("inf")` for `medical_cost` to get the worst year, because the bills are then capped at the maximum: ```{python} #| label: plans costs = [300, float("inf")] plan_a = plan_cost(monthly_premium=100, medical_cost=costs, oop_max=3000) plan_b = plan_cost(monthly_premium=40, medical_cost=costs, oop_max=5000, employer_hsa=500) pl.DataFrame({"year": ["healthy", "worst"], "plan_a": plan_a, "plan_b": plan_b}) ``` Plan B saves \$`{python} f"{plan_a[0] - plan_b[0]:,.0f}"` in a healthy year and costs \$`{python} f"{plan_b[1] - plan_a[1]:,.0f}"` more in the worst year. The worst year is the ceiling on what each plan can cost you. ## Variations The deductible decision depends on how much the higher deductible saves. Passing several values to `yearly_savings` shows how fast each one breaks even: ```{python} #| label: savings-options savings = [100, 150, 250] pl.DataFrame({ "yearly_savings": savings, "years": break_even_years(high_deductible=1000, low_deductible=500, yearly_savings=savings), }) ``` The bigger the yearly savings, the sooner the higher deductible pays off. ### Health plans across many kinds of year Most years fall somewhere between healthy and worst. One call per plan covers a range of medical bills: ```{python} #| label: bill-range bills = [0.0, 300.0, 1000.0, 2500.0, 5000.0, float("inf")] pl.DataFrame({ "medical_cost": bills, "plan_a": plan_cost(monthly_premium=100, medical_cost=bills, oop_max=3000), "plan_b": plan_cost(monthly_premium=40, medical_cost=bills, oop_max=5000, employer_hsa=500), }) ``` With no medical bills at all, Plan B's cost is negative: the employer's \$500 is more than the \$480 of premiums. Plan B stays cheaper until the bills pass about \$4,220. Past that point Plan A has hit its maximum, and it comes out ahead. ::: {.callout-warning title="Limits"} Both functions use the simple version of the math in the chapter. A few limits apply: * `plan_cost()` assumes you pay every medical bill up to the out of pocket maximum. For plans with coinsurance, it slightly overstates the cost. * `plan_cost()` ignores copays, tax savings from HSA contributions, and what HSA money could earn if invested. * `break_even_years()` assumes the premium savings are the same every year and ignores premium increases after a claim. * `break_even_years()` raises a `ValueError` when `yearly_savings` is zero or negative. Text raises a `TypeError`, and `nan` raises a `ValueError` in either function. ::: ## Putting it together The chapter suggests putting Plan B's healthy year savings into the HSA. How many healthy years does it take for those savings to cover Plan B's extra cost in a worst year? The structure is the same as the deductible question: a gap divided by savings per year. That means `break_even_years()` answers it too: ```{python} #| label: hsa-cushion cushion = break_even_years( high_deductible=plan_b[1], low_deductible=plan_a[1], yearly_savings=plan_a[0] - plan_b[0], ) cushion ``` The savings cover the worst year gap in `{python} f"{cushion:.2f}"` years, so a single healthy year is enough. After that, a bad year on Plan B still leaves you ahead of Plan A overall. The same rule as the deductible applies: have an emergency fund that covers the \$5,000 maximum first (see [Emergency Fund](05-emergency-fund.qmd)). ## Recap Insurance choices trade a known cost now for a possible cost later. `break_even_years()` shows how long the premium savings take to cover a higher deductible. `plan_cost()` puts two health plans on the same yearly scale, from a healthy year to the worst one. * [Insurance](https://mjfrigaard.github.io/fm-finance/insurance.html) in Personal Finance: a field manual * Reference: `break_even_years()`, `plan_cost()` * Next: [Financial Goals](15-financial-goals.qmd) ## Planning ### Financial Goals ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` A goal without a number and a date is a wish. Once you have both, two questions are left: how much do you set aside each month, and which goal do you fund first when you can't fund them all? In this page I'll answer both with `monthly_for_goal()` and `months_to_fund()`, using the numbers from the [Financial Goals](https://mjfrigaard.github.io/fm-finance/financial_goals.html) chapter of the book so you can check every result. ## The goal functions Both functions accept arrays and follow the conventions on the [Get started](00-get-started.qmd) page. | Function | Returns | Units | |---|---|---| | `monthly_for_goal()` | the monthly deposit that grows into a goal | dollars per month (`annual_rate` is a decimal) | | `months_to_fund()` | months to save a goal with no interest | whole months, rounded up (an `int`) | ## How much should you save each month? The chapter's example is a \$15,000 down payment in five years. The money sits in a high yield savings account earning 4% a year. Without interest you would divide \$15,000 by 60 months and save \$250 a month. Interest does part of the work, so you can save a little less. The bar below is the \$15,000 goal. Most of it comes from your deposits, and interest fills in the rest: ![A \$15,000 goal in 5 years at 4%: your deposits plus interest](assets/financial-goals-goal-bar-model.png){fig-alt="Bar model: one horizontal bar for a $15,000 goal, split into a long bluish green section labeled Your deposits $13,575 and a short blue section labeled Interest $1,425. Deposits cover about nine tenths of the bar; interest covers the last tenth."} `monthly_for_goal()` works backward from the future value of a series of deposits. It asks which monthly deposit grows into the goal, compounding at `annual_rate / 12`: ```{python} #| label: goal-monthly monthly = monthly_for_goal(goal=15000, annual_rate=0.04, months=60) monthly ``` You need about \$`{python} f"{monthly:,.2f}"` a month, which is \$`{python} f"{250 - monthly:,.2f}"` less than saving without interest. Over five years your deposits total \$`{python} f"{monthly * 60:,.0f}"`, and interest adds the other \$`{python} f"{15000 - monthly * 60:,.0f}"`. ## Which goal comes first? Say you can save \$600 a month toward two goals: a \$3,000 trip and a \$9,000 car. You can fund them one at a time (trip first, then car), or split the \$600 evenly until the trip is paid for and then send everything to the car. Each bar below is a goal on a timeline. It starts at month 0 and ends the month the goal is fully funded: ![Two goals funded with \$600 a month: one at a time vs. split evenly](assets/financial-goals-sequence-bar-model.png){fig-alt="Grouped horizontal bar chart of months to fund two goals under two plans. One at a time: the light green trip bar ends at month 5 and the bluish green car bar ends at month 20. Split evenly: the trip bar ends at month 10 and the car bar ends at month 20. The car finishes at month 20 under both plans."} `months_to_fund()` divides the goal by the monthly amount going to it and rounds up to a whole month. The last goal is done when all of the money is saved, so its goal is the total of both: ```{python} #| label: goal-sequence one_at_a_time = ( months_to_fund(goal=3000, monthly=600), months_to_fund(goal=3000 + 9000, monthly=600), ) split_evenly = ( months_to_fund(goal=3000, monthly=300), months_to_fund(goal=3000 + 9000, monthly=600), ) one_at_a_time, split_evenly ``` The trip finishes at month `{python} one_at_a_time[0]` one at a time, or month `{python} split_evenly[0]` split evenly. The car finishes at month `{python} one_at_a_time[1]` either way. The order only decides which goal you get first. ## Variations Passing several rates to `annual_rate` shows how much interest helps the down payment goal. The 0% row is the plain \$15,000 ÷ 60: ```{python} #| label: goal-rates rates = [0.0, 0.02, 0.04, 0.05] pl.DataFrame({ "annual_rate": rates, "monthly": monthly_for_goal(goal=15000, annual_rate=rates, months=60), }) ``` Each point of interest trims the deposit by a few dollars a month. Time matters more. The same goal over three, five, and seven years: ```{python} #| label: goal-horizons months = [36, 60, 84] pl.DataFrame({ "months": months, "monthly": monthly_for_goal(goal=15000, annual_rate=0.04, months=months), "months_no_interest": months_to_fund(goal=15000, monthly=[400, 250, 180]), }) ``` The last column runs the other direction: it asks how long \$400, \$250, or \$180 a month takes with no interest at all. ::: {.callout-warning title="Limits"} `monthly_for_goal()` assumes the same rate every month and a deposit at the end of each month. It ignores taxes on interest and inflation, so a goal priced in today's dollars will cost more later. `months_to_fund()` ignores interest entirely and rounds up, so it gives the first month the goal is fully funded. Both functions stop with a `ValueError` when the divisor isn't positive: ```{python} #| label: goal-error #| error: true months_to_fund(goal=3000, monthly=0) ``` `monthly_for_goal()` does the same when `months` is 0 or negative. ::: ## Putting it together Back to the \$600 a month. Suppose the down payment comes first, and whatever is left goes to the trip and the car. The down payment takes the amount we found above, and `months_to_fund()` shows how long the remainder needs for both smaller goals: ```{python} #| label: goal-together down_payment = monthly_for_goal(goal=15000, annual_rate=0.04, months=60) left_over = 600 - down_payment both_goals = months_to_fund(goal=3000 + 9000, monthly=left_over) round(left_over, 2), both_goals ``` With \$`{python} f"{left_over:,.2f}"` a month left over, the trip and the car take `{python} both_goals` months instead of 20. That trade is the real decision: the down payment stays on schedule, and the smaller goals wait longer. The [Major Purchases](16-major-purchases.qmd) page picks up the down payment and asks what the mortgage would cost. ## Recap A goal needs a number, a date, and a monthly amount. `monthly_for_goal()` turns the number and the date into the monthly amount, with interest doing part of the work. `months_to_fund()` shows that the order of your goals changes which one you reach first, but not when the last one is done. * [Financial Goals](https://mjfrigaard.github.io/fm-finance/financial_goals.html) in Personal Finance: a field manual * Reference: `monthly_for_goal()`, `months_to_fund()` * Next: [Major Purchases](16-major-purchases.qmd) ### Major Purchases ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` A home is the biggest purchase most people ever make, and small percentages turn into tens of thousands of dollars. The [Major Purchases](https://mjfrigaard.github.io/fm-finance/major_purchases.html) chapter of the book asks three questions: when does renting beat buying, what will the mortgage cost each month, and where does the first payment go? In this page I'll answer them with `rent_buy_threshold()`, `mortgage_payment()`, and `first_payment_split()`, using the chapter's numbers so you can check each result against the book. ## The major purchase functions `rent_buy_threshold()` and `mortgage_payment()` accept arrays. `first_payment_split()` takes single numbers and returns a `dict`. | Function | Returns | Units | |---|---|---| | `rent_buy_threshold()` | the monthly rent that matches the unrecoverable cost of owning | dollars per month (`unrecoverable_rate` is a decimal, default `0.05`) | | `mortgage_payment()` | the monthly payment on a fixed rate loan | dollars per month, principal and interest only | | `first_payment_split()` | the interest and principal in the first payment | a `dict` of dollars, plus `pct_interest` as a percent | ## Should you rent or buy? Owning a home costs money you never get back, whether or not you have a mortgage. The 5% rule from the chapter adds up three of those costs for a \$500,000 home: about 1% a year for property tax, 1% for maintenance, and 3% for the cost of capital (the return your money could have earned somewhere else). ![The three parts of the 5% rule on a \$500,000 home](assets/major-purchases-rent-buy-bar-model.png){fig-alt="Bar model: one horizontal bar of annual unrecoverable cost on a $500,000 home, split into a vermillion section for property tax (about 1%, $5,000 a year), a bluish green section for maintenance (about 1%, $5,000 a year), and a dark brown section for cost of capital (about 3%, $15,000 a year). The whole bar is $25,000 a year, or $2,083 a month, and cost of capital fills more than half of it."} `rent_buy_threshold()` takes 5% of the home's value and divides by 12: ```{python} #| label: rent-buy threshold = rent_buy_threshold(home_value=500000) threshold ``` Owning this home costs about \$`{python} f"{threshold:,.0f}"` a month that you never get back. If you can rent a similar place for less than that, renting and investing the difference tends to win. ## What will the mortgage cost each month? The chapter's loan is \$480,000: a \$600,000 home with 20% down, at 6%. The same loan gives very different payments depending on how many months you spread it over: ![Monthly payment on a \$480,000 loan at 6% across three terms](assets/major-purchases-mortgage-payment-bar-model.png){fig-alt="Bar chart of the monthly payment on a $480,000 loan at 6% for three loan terms: a vermillion bar at $4,051 for 15 years, a bluish green bar at $3,439 for 20 years, and a blue bar at $2,878 for 30 years. Shorter terms have taller bars."} `mortgage_payment()` spreads the principal plus all future interest into equal monthly payments, with the rate as a decimal: ```{python} #| label: mortgage payment = mortgage_payment(principal=480000, annual_rate=0.06, years=30) payment ``` The 30 year loan costs about \$`{python} f"{payment:,.2f}"` a month. That covers principal and interest only; property tax and insurance come on top. ## Where does the first payment go? Early mortgage payments are mostly interest. In month one the interest is the full balance times the monthly rate, and only what's left of the payment reduces the principal: ![Interest vs. principal at three points on a \$480,000, 6%, 30 year mortgage](assets/major-purchases-first-payment-bar-model.png){fig-alt="Stacked bar chart of how the same $2,878 monthly payment splits between interest (vermillion) and principal (blue) at three points in a 30 year loan. Month 1: $2,400 interest (83%) and $478 principal (17%). Month 180: $1,711 interest (59%) and $1,167 principal (41%). Month 348: $181 interest (6%) and $2,697 principal (94%). The interest share shrinks as the loan ages."} `first_payment_split()` returns the payment, its interest and principal parts, and the interest share as a percent: ```{python} #| label: first-payment split = first_payment_split(principal=480000, annual_rate=0.06, years=30) split ``` Of the first \$`{python} f"{split['payment']:,.0f}"` payment, \$`{python} f"{split['interest']:,.0f}"` is interest (`{python} f"{split['pct_interest']:.0f}"`%) and only \$`{python} f"{split['principal']:,.0f}"` reduces the loan. That's why moving after a few years leaves you with very little principal paid down. ### Call stack `first_payment_split()` doesn't repeat the payment formula. It calls `mortgage_payment()`, which uses the internal `_annuity_factor()` helper (the same one behind `monthly_for_goal()`): ```{python} #| label: call-stack #| eval: false from rich import print from rich.tree import Tree tree = Tree("first_payment_split()") tree.add("mortgage_payment()").add("_annuity_factor()") print(tree) ``` ``` first_payment_split() └── mortgage_payment() └── _annuity_factor() ``` ## Variations Passing several terms to `years` reproduces the three bars in the mortgage bar model. Multiplying each payment by the number of payments shows the total interest over the life of the loan: ```{python} #| label: mortgage-terms years = [15, 20, 30] payments = mortgage_payment(principal=480000, annual_rate=0.06, years=years) pl.DataFrame({ "years": years, "payment": payments, "total_interest": payments * [y * 12 for y in years] - 480000, }) ``` The 30 year loan has the lowest payment and more than twice the interest of the 15 year loan. The same approach compares rent thresholds across home prices: ```{python} #| label: rent-buy-prices home_values = [300000, 500000, 700000] pl.DataFrame({ "home_value": home_values, "threshold": rent_buy_threshold(home_value=home_values), }) ``` ::: {.callout-warning title="Limits"} `rent_buy_threshold()` is a rule of thumb. The 5% default is an average; set `unrecoverable_rate` if your property tax or maintenance is higher or lower. It ignores home price growth, the costs of buying and selling, and how long you stay. `mortgage_payment()` assumes a fixed rate and returns principal and interest only, with no property tax, insurance, or PMI. A 0% rate returns `principal / (years * 12)`, and `years` must be greater than 0. `first_payment_split()` takes single numbers only. An array raises an error: ```{python} #| label: split-error #| error: true first_payment_split(principal=480000, annual_rate=0.06, years=[15, 30]) ``` ::: ## Putting it together The chapter's loan comes from a \$600,000 home with 20% down. That's a \$120,000 down payment, the kind of goal the [Financial Goals](15-financial-goals.qmd) page plans for. Here is the whole decision in one cell: the monthly saving for the down payment over 10 years at 4%, the rent threshold for the home, and the mortgage payment once you buy: ```{python} #| label: purchase-together home = 600000 save_monthly = monthly_for_goal(goal=home * 0.20, annual_rate=0.04, months=120) rent_line = rent_buy_threshold(home_value=home) mortgage = mortgage_payment(principal=home * 0.80, annual_rate=0.06, years=30) round(save_monthly, 2), round(rent_line, 2), round(mortgage, 2) ``` Saving the down payment takes about \$`{python} f"{save_monthly:,.0f}"` a month for 10 years. Once you buy, the mortgage is \$`{python} f"{mortgage:,.0f}"` a month, and the 5% rule says owning costs about \$`{python} f"{rent_line:,.0f}"` a month that you never get back. If a comparable rental costs less than \$`{python} f"{rent_line:,.0f}"`, renting and investing the down payment is worth a serious look. ## Recap The 5% rule gives a quick rent or buy test, and `rent_buy_threshold()` turns it into a monthly number. `mortgage_payment()` shows how the term changes the payment, and `first_payment_split()` shows how little of an early payment goes to principal. Run these numbers before you fall in love with a floor plan. * [Major Purchases](https://mjfrigaard.github.io/fm-finance/major_purchases.html) in Personal Finance: a field manual * Reference: `rent_buy_threshold()`, `mortgage_payment()`, `first_payment_split()` * Next: [Estate Planning](17-estate-planning.qmd) ### Estate Planning ```{python} #| label: setup #| include: false import polars as pl from perfinpy import * ``` Your estate is everything you own and everything you owe. Estate planning math asks two things about it: what is it worth, and how much of it do your beneficiary forms control? In this page I'll answer both with `net_worth()` and `beneficiary_share()`, using the 25 year old from the [Estate Planning](https://mjfrigaard.github.io/fm-finance/estate_planning.html) chapter of the book so you can check each result. ## The estate functions Both functions take a `dict` of name to amount, as the book does. A plain list of amounts works too. | Function | Returns | Units | |---|---|---| | `net_worth()` | total assets minus total debts | dollars (a `float`) | | `beneficiary_share()` | the share of assets with a named beneficiary | a decimal (`0.8875` is 88.75%) | ## What is your estate worth? The chapter's example is a 25 year old with a 401(k), a Roth IRA, some savings, and a car. On the other side are a car loan and a small credit card balance. The bar model puts what you own on one bar and what you owe on the other: ![Assets, debts, and net worth for a 25 year old](assets/estate-planning-networth-bar-model.png){fig-alt="Bar model with two horizontal bars. What you own: 401(k) $12,000 in bluish green, Roth IRA $6,000 in blue, Savings $8,000 in light green, and Car $9,000 in sky blue, for $35,000 in all. What you owe: Car loan $6,000 in vermillion and Credit card $1,000 in orange, for $7,000. The owe bar is about one fifth the length of the own bar."} Net worth is the length of the top bar minus the length of the bottom bar. `net_worth()` adds up each `dict` and subtracts: ```{python} #| label: net-worth assets = {"401k": 12000, "roth_ira": 6000, "savings": 8000, "car": 9000} debts = {"car_loan": 6000, "credit_card": 1000} worth = net_worth(assets, debts) worth ``` The estate is worth \$`{python} f"{worth:,.0f}"`: \$`{python} f"{sum(assets.values()):,}"` in assets minus \$`{python} f"{sum(debts.values()):,}"` in debts. ## How much do your beneficiary forms control? Now add life insurance through work. Many employers give free coverage equal to one year of salary, say \$45,000. It isn't part of net worth while you're alive, but it pays out when you die. The bar below shows everything that would pass to someone else, split by what decides who gets it: ![What decides who gets each part of the estate](assets/estate-planning-beneficiary-bar-model.png){fig-alt="Bar model: one horizontal bar for an $80,000 estate, split into a bluish green section for beneficiary forms ($63,000), a light green section for savings with a payable on death designation ($8,000), and a vermillion section for your will or state law ($9,000). The two green sections together fill almost nine tenths of the bar."} The green sections are decided by forms you fill out online; only the vermillion section depends on a will. `beneficiary_share()` divides the green sections by the whole bar: ```{python} #| label: beneficiary with_beneficiary = { "401k": 12000, "roth_ira": 6000, "life_insurance": 45000, "savings_pod": 8000, } without_beneficiary = {"car": 9000} share = beneficiary_share(with_beneficiary, without_beneficiary) share ``` About `{python} f"{share * 100:.0f}"`% of the estate is decided by forms that take minutes to fill out. That's why the book puts beneficiary designations ahead of a will for most young people. Note that the result is a decimal, not a percent. ## Variations `beneficiary_share()` takes one estate at a time, so a list comprehension compares several. Here is the same estate with fewer forms filed: ```{python} #| label: beneficiary-scenarios scenarios = { "all forms filed": (with_beneficiary, without_beneficiary), "no POD on savings": ( {"401k": 12000, "roth_ira": 6000, "life_insurance": 45000}, {"savings": 8000, "car": 9000}, ), "retirement forms only": ( {"401k": 12000, "roth_ira": 6000}, {"life_insurance": 45000, "savings": 8000, "car": 9000}, ), } pl.DataFrame({ "scenario": list(scenarios), "share": [beneficiary_share(w, wo) for w, wo in scenarios.values()], }) ``` Skipping the life insurance form costs the most, because it is the largest item. (Most employer life insurance asks for a beneficiary at enrollment; the last row shows what happens if you leave it blank.) ::: {.callout-warning title="Limits"} `net_worth()` adds the values you give it. It doesn't know what a car is worth next year, so use today's market value, and enter debts as positive balances. It ignores taxes owed on retirement accounts and the costs of probate. `beneficiary_share()` returns a decimal, unlike the ratio functions that return percents. It ignores joint ownership, which also passes outside a will, and it stops with a `ValueError` when total assets aren't greater than 0: ```{python} #| label: beneficiary-error #| error: true beneficiary_share({}, {"car": 0}) ``` Both functions raise a `TypeError` for text and a `ValueError` for missing values. ::: ## Putting it together Estates change as you save. Five years from now, suppose the retirement accounts grow at 7% a year (with `future_value()` from [Investing Basics](09-investing-basics.qmd)), savings reach \$15,000, the car is paid off and worth \$6,000, and the credit card is cleared: ```{python} #| label: estate-later retirement = future_value(present_value=[12000, 6000], rate=0.07, years=5) assets_later = { "401k": retirement[0], "roth_ira": retirement[1], "savings": 15000, "car": 6000, } worth_later = net_worth(assets_later, debts={"car_loan": 0, "credit_card": 0}) share_later = beneficiary_share( { "401k": retirement[0], "roth_ira": retirement[1], "life_insurance": 45000, "savings_pod": 15000, }, {"car": 6000}, ) round(worth_later, 2), round(share_later, 4) ``` Net worth grows to \$`{python} f"{worth_later:,.0f}"`, and the forms now decide `{python} f"{share_later * 100:.0f}"`% of the estate. The bigger the accounts get, the more those ten minute forms matter. ## Recap `net_worth()` gives the starting number for any estate plan: what you own minus what you owe. `beneficiary_share()` shows how much of that estate passes by beneficiary forms instead of a will. For most young people the answer is most of it, so fill in those forms first. This is the last chapter of the book and the last page of the guide. * [Estate Planning](https://mjfrigaard.github.io/fm-finance/estate_planning.html) in Personal Finance: a field manual * Reference: `net_worth()`, `beneficiary_share()` * Back to: [Get started](00-get-started.qmd)