#!/usr/bin/env python3 """Generate and solve Chapter 13 practice with Python 3.10 or later. For web-chat practice, you do not need Python installed on your computer. Attach this file to a chat with file uploads and Python execution available. Ask it to read TUTOR_GUIDE, execute self_test(), and show the actual output. Reading this file is not the same as executing it. If execution is unavailable, use another capable chat or choose the optional local method below. ChatGPT data analysis documentation: https://help.openai.com/en/articles/8437071-data-analysis-with-chatgpt Claude code execution documentation: https://support.claude.com/en/articles/12111783-create-and-edit-files-with-claude In Claude, check Settings > Capabilities > Code execution and file creation. Account settings and upload limits may affect access. Optional local use requires Python 3.10 or later, with no extra packages. The script makes no network requests or AI API calls. Local commands: python chapter-13-practice.py --topic present --seed 42 python chapter-13-practice.py --topic present --seed 42 --show-solution python chapter-13-practice.py --topic note --seed 42 --save problem.json python chapter-13-practice.py --solve problem.json python chapter-13-practice.py --guide python chapter-13-practice.py --self-test Import with runpy.run_path(path). Call generate_problem(topic, seed), then solve_problem(problem). The first function returns only facts and questions. The second returns named results, formulas, worked steps, and any schedule. Rates are decimals: 0.06 means 6%. All amounts are hypothetical US dollars. """ from __future__ import annotations import argparse import json import random from decimal import ROUND_HALF_UP, Decimal, localcontext from pathlib import Path TUTOR_GUIDE = """Help me practice the Chapter 13 time-value calculations. 1. Ask which topic I want and whether I want a hint before trying it. 2. Execute this file's self_test() and show its actual output. If it fails, stop and report the error. Then use generate_problem(topic, seed). Give me the complete problem facts and one task at a time. Keep solutions private until I attempt the task or ask to see them. Change the seed for another problem; preserve it so the same problem can be reproduced. 3. Before calculating, ask me to identify payment timing, the valuation date, and the matching rate and period units. For note accounting, distinguish stated cash interest from effective interest revenue or expense. 4. Execute solve_problem(problem) to verify every numerical explanation. Use its cent-rounding policy. Do not substitute mental arithmetic, rewrite the solver, or claim that code ran if your chat cannot execute Python. 5. After my attempt, show the general formula, substituted inputs, relevant intermediate values, and what the result means. Render division as a fraction and make exponents clear. Explain why a step applies. Do not just tell me to discount the payments or apply a factor. 6. If my answer is wrong, identify the earliest wrong step and offer a hint before revealing the full solution. Judge reasoning as well as the amount. For a schedule, check one row at a time. Do not expose later answers. 7. Give me another problem of the same type before increasing difficulty. Vary timing, amounts, and rates. Use only the supported topics. No fees, credit losses, taxes, early repayment, continuous compounding, or solving for an unknown yield. These are practice calculations, not a GAAP checker. 8. If you cannot execute Python, stop and say so. Explain that I can use a chat with Python execution without installing Python on my computer. Offer local commands only as an optional alternative requiring Python. If I choose that option, ask for the command output. Never claim that your own unexecuted arithmetic is Python-verified. """ TOPICS = ( "simple", "future", "present", "annuity-pv", "annuity-fv", "due-pv", "due-fv", "rates", "equivalent-periodic", "mixed", "note", "installment", "accrual", ) D = Decimal CENT = D("0.01") def number(value): """Reject nonfinite values and booleans before doing arithmetic.""" if isinstance(value, bool): raise ValueError("Use a number, not true or false.") result = D(str(value)) if not result.is_finite(): raise ValueError("Every input must be finite.") return result def amount(value): result = number(value) if result < 0: raise ValueError("Use a nonnegative amount for this calculation.") return result def rate(value): result = number(value) if not 0 <= result <= 1: raise ValueError("Use a decimal rate from 0 to 1; enter 0.08 for 8%.") return result def integer(value, minimum=1): result = number(value) if result != result.to_integral_value() or not minimum <= result <= 1000: raise ValueError(f"Use a whole-number period count from {minimum} to 1000.") return int(result) def cents(value): return value.quantize(CENT, rounding=ROUND_HALF_UP) def money(value): return f"${cents(value):,.2f}" def annuity_factor(i, n, due=False, future=False): """Sum dated factors; this also works when the rate is zero.""" times = range(0, n) if due else range(1, n + 1) return sum(((1 + i) ** ((n - t) if future else -t) for t in times), D(0)) def generate_problem(topic="mixed", seed=None): """Return a reproducible problem without its answers. 'random' picks a topic.""" if seed is None: seed = random.SystemRandom().randrange(1_000_000_000) rng = random.Random(seed) if topic == "random": topic = rng.choice(TOPICS) rng = random.Random(seed) if topic not in TOPICS: raise ValueError(f"Choose one of: {', '.join(TOPICS)}.") principal = rng.randrange(5, 31) * 1000 i = str(D(rng.choice([4, 5, 6, 8, 10])) / 100) n = rng.randint(2, 5) inputs = {"periodic_rate": i, "periods": n} context = "All amounts are US dollars. Time 0 is the valuation date." questions = [] if topic in {"simple", "accrual"}: months = rng.choice([2, 3, 6, 9]) inputs = {"principal": principal, "annual_rate": i, "months": months} if topic == "simple": context += ( f" A borrower receives ${principal:,} for {months} months at " f"{D(i):.0%} annual simple interest. No interim payments " f"occur." ) questions = ["Calculate total interest.", "Calculate the total payment at maturity."] else: context += ( f" A lender advances ${principal:,} at face amount at " f"{D(i):.0%} annual simple interest. At the reporting date, " f"{months} whole months have elapsed. Principal and all " f"interest are due after that date. No interest has been " f"recorded or collected." ) questions = [ "Calculate interest earned by the reporting date.", "Identify the lender's adjusting entry.", ] elif topic in {"future", "present"}: inputs["amount"] = principal inputs["period_unit"] = "year" if topic == "future": context += ( f" Deposit ${principal:,} at time 0 for {n} years at " f"{D(i):.0%} compounded annually, with no other deposits or " f"withdrawals." ) questions = ["Calculate the balance at the end of the term."] else: context += ( f" A single ${principal:,} payment is due {n} years after " f"time 0. Use a {D(i):.0%} effective annual rate." ) questions = ["Calculate the payment's present value at time 0."] elif topic in {"annuity-pv", "annuity-fv", "due-pv", "due-fv"}: inputs["payment"] = rng.randrange(2, 9) * 500 inputs["period_unit"] = "year" due = topic.startswith("due") times = list(range(0, n) if due else range(1, n + 1)) context += ( f" Receive {n} equal payments of ${inputs['payment']:,} at " f"times {times}, measured in years. Use a {D(i):.0%} " f"effective annual rate." ) target = f"future value at time {n}" if topic.endswith("fv") else "present value at time 0" questions = [ "Identify whether this is an ordinary annuity or an annuity due.", f"Calculate its {target}.", ] elif topic in {"rates", "equivalent-periodic"}: frequency = rng.choice([2, 4, 12]) if topic == "rates": inputs = {"nominal_annual_rate": i, "periods_per_year": frequency} context += ( f" A contract quotes a {D(i):.0%} nominal annual rate " f"compounded {frequency} times per year." ) questions = [ "Calculate the rate per compounding period.", "Calculate the effective annual rate.", ] else: inputs = {"effective_annual_rate": i, "periods_per_year": frequency} context += ( f" A contract has a {D(i):.0%} effective annual rate. Divide " f"the year into {frequency} equal compounding periods." ) questions = [ ( "Calculate the equivalent periodic rate. Explain why " "dividing the annual rate is inappropriate here." ) ] elif topic == "mixed": flows = [{"period": t, "amount": rng.randrange(1, 9) * 1000} for t in (1, 2, 4)] inputs = {"periodic_rate": i, "period_unit": "year", "cash_flows": flows} context += ( f" Use a {D(i):.0%} effective annual rate. Receipts occur as follows: " + "; ".join(f"${f['amount']:,} at year {f['period']}" for f in flows) + "." ) questions = [ "Calculate each receipt's present value at time 0.", "Calculate their combined present value.", ] elif topic == "note": stated = rng.choice(["0", "0.04", "0.06", "0.10"]) inputs = { "face": principal, "stated_periodic_rate": stated, "periodic_rate": i, "periods": n, "period_unit": "year", } context += ( f" A lender advances cash for a ${principal:,} face-value " f"note. Principal is due after {n} years. The stated annual " f"rate is {D(stated):.0%}, with interest paid at each " f"year-end. The effective annual rate is {D(i):.0%}. There " f"are no fees, other exchanged benefits, credit losses, or " f"early payments." ) questions = [ "Calculate the annual contractual cash interest.", "Calculate the initial advance and identify any discount or premium.", ( "Prepare each annual row: opening carrying amount, interest " "revenue, cash collected, amortization, and closing carrying " "amount." ), ] elif topic == "installment": inputs["principal"] = principal inputs["period_unit"] = "year" context += ( f" A borrower receives ${principal:,} at time 0. There is no " f"discount, premium, or fee. The annual rate is {D(i):.0%}. " f"The loan is repaid in {n} year-end installments, with no " f"separate maturity payment." ) questions = [ "Calculate the equal installment before rounding.", ( "Prepare each annual row: interest, principal repaid, and " "remaining balance. Adjust the final cash payment for cent " "rounding." ), ] return { "topic": topic, "seed": seed, "context": context, "inputs": inputs, "questions": questions, "rounding": ( "Value cash flows at full precision and round final dollar " "answers to cents. For schedules, round the initial balance " "and each period's interest to cents. The solution " "identifies any final rounding adjustment. For rates, use at " "least four decimal places in percent form." ), } def solve_problem(problem): """Calculate from named inputs, without reading numbers out of the story. An AI may edit inputs for a custom problem but must update the story too. Result rates are decimals. Unrounded values remain available as strings. """ with localcontext() as ctx: ctx.prec = 50 return _solve(problem) def _solve(problem): topic, x = problem["topic"], problem["inputs"] steps, rows, results = [], [], {} if topic in {"simple", "accrual"}: p, annual, months = amount(x["principal"]), rate(x["annual_rate"]), integer(x["months"]) interest = p * annual * D(months) / 12 steps = [ "Interest = Principal × Annual rate × (Months / 12).", f"{money(p)} × {annual} × ({months} / 12) = {money(interest)}.", ] results["interest"] = str(cents(interest)) if topic == "simple": results["total_due"] = str(cents(p + interest)) steps += [ "Total due = Principal + Interest.", f"{money(p)} + {money(interest)} = {money(p + interest)}.", ] else: steps += [ ( f"Debit Interest Receivable {money(interest)}; credit " f"Interest Revenue {money(interest)}." ), "The lender earned the interest before collecting it. Principal remains unchanged.", ] elif topic in {"rates", "equivalent-periodic"}: frequency = integer(x["periods_per_year"]) if topic == "rates": annual = rate(x["nominal_annual_rate"]) periodic = annual / frequency effective = (1 + periodic) ** frequency - 1 steps = [ "Periodic rate = Nominal annual rate / Periods per year.", f"{annual} / {frequency} = {periodic}.", "Effective annual rate = (1 + Periodic rate)^(Periods per year) − 1.", f"(1 + {periodic})^{frequency} − 1 = {effective}.", "The later periods earn interest on interest from earlier periods.", ] else: effective = rate(x["effective_annual_rate"]) periodic = (1 + effective) ** (D(1) / frequency) - 1 steps = [ "Periodic rate = (1 + Effective annual rate)^(1 / Periods per year) − 1.", f"(1 + {effective})^(1 / {frequency}) − 1 = {periodic}.", ( "Reverse compounding. Dividing an effective annual rate " "would produce a different annual return." ), ] results = {"periodic_rate": str(periodic), "effective_annual_rate": str(effective)} else: i = rate(x["periodic_rate"]) unit = x.get("period_unit", "period") steps.append(f"Use i = {i} per {unit}. Count n in the same units.") if topic == "mixed": values = [] if not x["cash_flows"]: raise ValueError("Supply at least one dated cash flow.") steps.append("Present value of each cash flow = Cash flow / (1 + i)^t.") for flow in x["cash_flows"]: t, cash = integer(flow["period"], 0), number(flow["amount"]) value = cash / (1 + i) ** t values.append(value) rows.append( {"period": t, "cash_flow": str(cash), "present_value_unrounded": str(value)} ) steps.append(f"Period {t}: {cash} / (1 + {i})^{t} = {value}.") total = sum(values, D(0)) results["present_value"] = str(cents(total)) steps += [ "Total present value = Sum of the individual present values.", " + ".join(str(v) for v in values) + f" = {money(total)} (rounded).", ] else: n = integer(x["periods"], 0 if topic in {"future", "present"} else 1) if topic in {"future", "present"}: p = amount(x["amount"]) exponent = n if topic == "future" else -n value = p * (1 + i) ** exponent formula = ( "Future value = Present amount × (1 + i)^n." if topic == "future" else "Present value = Future amount / (1 + i)^n." ) op = "×" if topic == "future" else "/" steps += [ formula, f"{money(p)} {op} (1 + {i})^{n} = {money(value)}.", ( "Compounding moves a value later; discounting reverses that " "growth to find an earlier equivalent value." ), ] results["value"] = str(cents(value)) elif topic in {"annuity-pv", "annuity-fv", "due-pv", "due-fv"}: payment = amount(x["payment"]) due, future = topic.startswith("due"), topic.endswith("fv") ordinary = annuity_factor(i, n, future=future) factor = annuity_factor(i, n, due=due, future=future) formula = "[((1 + i)^n − 1) / i]" if future else "[(1 − (1 + i)^(-n)) / i]" steps += [ ( f"Ordinary-annuity {'future' if future else 'present'} value " f"= Payment × {formula}." ) ] if i == 0: steps.append(f"At a zero rate, use Payment × n: {money(payment)} × {n}.") else: steps.append( f"Ordinary factor = " f"{formula.replace('i', str(i)).replace('n', str(n))} = " f"{ordinary}; ordinary value = {money(payment)} × {ordinary}." ) if due: steps += [ "Annuity-due value = Ordinary-annuity value × (1 + i).", f"{payment * ordinary} × (1 + {i}) = {money(payment * factor)}.", ] else: steps.append(f"{money(payment)} × {factor} = {money(payment * factor)}.") for t in range(n) if due else range(1, n + 1): exponent = n - t if future else -t value = payment * (1 + i) ** exponent rows.append( { "payment_period": t, "periods_of_growth" if future else "periods_discounted": n - t if future else t, "equivalent_value_unrounded": str(value), } ) steps.append( f"Payment at time {t}: {money(payment)} × (1 + {i})^({exponent}) = {value}." ) steps.append( "Sum those individual values before rounding. Each payment " "has its own time to grow or be discounted." ) results = {"value": str(cents(payment * factor)), "factor_unrounded": str(factor)} elif topic in {"note", "installment"}: results, rows, more = loan_solution(topic, x, i, n) steps += more else: raise ValueError(f"Unsupported topic: {topic}") return {"results": results, "steps": steps, "schedule": rows} def loan_solution(topic, x, i, n): """Post cent amounts and disclose the final rounding adjustment.""" factor = annuity_factor(i, n) rows = [] steps = ["Ordinary-annuity PV factor = [1 − (1 + i)^(-n)] / i."] if i == 0: steps.append(f"At a zero rate, the factor is the payment count, {n}.") else: steps.append(f"[1 − (1 + {i})^(-{n})] / {i} = {factor}.") if topic == "note": face = amount(x["face"]) if face != cents(face): raise ValueError("Enter face amount in whole cents.") stated = rate(x["stated_periodic_rate"]) contractual = face * stated if contractual != cents(contractual): raise ValueError( "Choose note terms whose contractual periodic interest is a whole number of cents." ) pv_interest, pv_face = contractual * factor, face / (1 + i) ** n initial = cents(pv_interest + pv_face) difference = face - initial results = { "cash_interest": str(contractual), "initial_advance": str(initial), "discount": str(max(difference, D(0))), "premium": str(max(-difference, D(0))), } steps += [ "Cash interest = Face amount × Stated periodic rate.", f"{money(face)} × {stated} = {money(contractual)}.", ( "Initial advance = Cash interest × Ordinary-annuity PV " "factor + Face amount / (1 + i)^n." ), f"PV of interest = {contractual} × {factor} = {pv_interest}.", f"PV of principal = {face} / (1 + {i})^{n} = {pv_face}.", f"Initial advance = {pv_interest} + {pv_face} = {money(initial)} (rounded).", ( "Discount = Face − Advance when the advance is below face. " "Premium = Advance − Face when it is above face." ), f"Face − Advance = {money(face)} − {money(initial)} = {money(difference)}.", ] else: initial = amount(x["principal"]) if initial != cents(initial): raise ValueError("Enter principal in whole cents.") if initial <= 0: raise ValueError("An installment loan needs positive principal.") exact_payment = initial / factor contractual = cents(exact_payment) if contractual <= 0: raise ValueError("The rounded installment must exceed zero.") results = {"payment_unrounded": str(exact_payment), "regular_payment": str(contractual)} steps += [ "Equal payment = Initial principal / Ordinary-annuity PV factor.", ( f"{money(initial)} / {factor} = {exact_payment}; regular " f"payment = {money(contractual)}." ), ( "Principal repaid = Cash payment − Interest. The final " "payment is adjusted for rounding." ), ] steps += [ "Interest = Opening carrying amount × Effective periodic rate.", ( "Closing carrying amount = Opening carrying amount + " "Interest − Total cash received or paid." ), ] balance = initial total_interest = D(0) for t in range(1, n + 1): opening = balance calculated_interest = cents(opening * i) interest, adjustment = calculated_interest, D(0) cash = contractual if topic == "note": if t == n: cash += face adjustment = cash - opening - interest if abs(adjustment) > CENT * (n + 1): raise ValueError("Final rounding difference is too large; check the terms.") interest += adjustment elif t == n: cash = opening + interest adjustment = cash - contractual if topic == "installment" and (cash <= interest or cash > opening + interest): raise ValueError( "The rounded installment cannot repay this loan over the stated periods." ) balance = opening + interest - cash row = { "period": t, "opening": str(opening), "interest_before_adjustment": str(calculated_interest), "interest": str(interest), "cash": str(cash), "closing": str(balance), "rounding_adjustment": str(adjustment), } if topic == "note": amortization = interest - contractual row["discount_amortization"] = str(max(amortization, D(0))) row["premium_amortization"] = str(max(-amortization, D(0))) else: row["principal_repaid"] = str(cash - interest) rows.append(row) total_interest += interest steps.append( f"Period {t}: interest = {money(opening)} × {i} = " f"{money(calculated_interest)}; closing = {money(opening)} + " f"{money(interest)} − {money(cash)} = {money(balance)}." ) if topic == "note": if amortization >= 0: steps.append( f"Discount amortization = Interest − Cash interest = " f"{money(interest)} − {money(contractual)} = " f"{money(amortization)}." ) else: steps.append( f"Premium amortization = Cash interest − Interest = " f"{money(contractual)} − {money(interest)} = " f"{money(-amortization)}." ) else: steps.append( f"Principal repaid = Cash payment − Interest = {money(cash)} " f"− {money(interest)} = {money(cash - interest)}." ) if adjustment: target = "interest" if topic == "note" else "final cash payment" steps.append( f"Period {t}: rounding adjustment to {target} = " f"{money(adjustment)}. It is shown separately in the " f"schedule." ) results["total_interest"] = str(total_interest) results["final_balance"] = str(balance) steps.append( "Each period's cash flow and change in carrying amount " "reconcile to interest. The borrower reports interest " "expense; the lender reports interest revenue." ) return results, rows, steps def self_test(): """Check known chapter amounts, zero rates, timing, and loan reconciliation.""" def solve(topic, **inputs): return solve_problem({"topic": topic, "inputs": inputs}) assert ( solve("future", amount=10000, periodic_rate=".06", periods=3)["results"]["value"] == "11910.16" ) assert ( solve("present", amount=10000, periodic_rate=".06", periods=3)["results"]["value"] == "8396.19" ) assert ( solve("annuity-pv", payment=3000, periodic_rate=".06", periods=3)["results"]["value"] == "8019.04" ) assert ( solve("due-pv", payment=3000, periodic_rate=".06", periods=3)["results"]["value"] == "8500.18" ) assert ( solve("due-fv", payment=3000, periodic_rate=0, periods=3)["results"]["value"] == "9000.00" ) for stated in ("0", ".06", ".08", ".10"): out = solve( "note", face=100000, stated_periodic_rate=stated, periodic_rate=".08", periods=3 ) assert D(out["results"]["final_balance"]) == 0 assert sum(D(r["cash"]) - D(r["interest"]) for r in out["schedule"]) == D( out["results"]["initial_advance"] ) for topic in TOPICS: for seed in range(12): problem = generate_problem(topic, seed) assert problem == generate_problem(topic, seed) solution = solve_problem(problem) for row in solution["schedule"]: if "opening" in row: assert D(row["opening"]) + D(row["interest"]) - D(row["cash"]) == D( row["closing"] ) return "Self-test passed. These checks verify calculations, not an AI tutor's explanation." def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("--topic", choices=(*TOPICS, "random"), default="random") parser.add_argument("--seed", type=int, help="Reuse a seed and topic to reproduce a problem.") parser.add_argument("--show-solution", action="store_true") parser.add_argument( "--save", type=Path, help="Save the problem as JSON; refuses to overwrite a file." ) parser.add_argument("--solve", type=Path, help="Solve a previously saved problem JSON file.") parser.add_argument("--guide", action="store_true", help="Print instructions for an AI tutor.") parser.add_argument("--self-test", action="store_true") args = parser.parse_args() try: if args.guide: print(TUTOR_GUIDE) elif args.self_test: print(self_test()) elif args.solve: problem = json.loads(args.solve.read_text(encoding="utf-8")) print(json.dumps(solve_problem(problem), indent=2, ensure_ascii=False)) else: problem = generate_problem(args.topic, args.seed) if args.save: with args.save.open("x", encoding="utf-8") as file: json.dump(problem, file, indent=2, ensure_ascii=False) print(json.dumps(problem, indent=2, ensure_ascii=False)) if args.show_solution: print(json.dumps(solve_problem(problem), indent=2, ensure_ascii=False)) except (ValueError, KeyError, TypeError, ArithmeticError, OSError) as exc: parser.exit(2, f"Cannot calculate: {exc}\n") if __name__ == "__main__": main()