After-Tax Investment Math Brainstorming
Section titled “After-Tax Investment Math Brainstorming”Date: 2026-03-18
Background
Section titled “Background”- The following uses terminology for investing in Canada, but the US investment industry is also a core target.
- Taxation of investments is complex, different in various regions (countries and even provinces/states), and changes over time.
- As a result, too often investment strategies are assessed based on a before-tax analysis both in the academic world and investment industry. This is inappropriate, and can lead to the wrong conclusions, hurting investors and the financial industry.
- For similar reasons, investment strategies are often assessed on a before-tax lump sum basis when the real objective is income, as in the foundational savings goal of retirement. Specifically, the real retirement savings goal is to provide sufficient net retirement income, accounting for all factors including taxes, and the “hidden tax” of clawbacks of government benefits.
- For one simplistic example of how this creates problems, consider the classic apples and oranges comparison of tax-deferred investing (like in RRSPs) versus unregistered investing (taxable account). Is 100 oranges (taxable RRSP) better than 80 apples (not all taxable)? Everyone would rather have 100 instead of 80 when it is apples to apples. But in this case, it is entirely unclear whether $100k in an RRSP would be better than $80K unregistered — in terms of producing after-tax retirement income over 20 years.
- These issues might be named the Before-Tax Trap or Before-Tax Thinking (to be less dramatic) versus the After-Tax Reality (or perhaps After-Tax Truth), described next.
- The real objective for all investment strategies is to maximize net after-tax income over a desired time period. For retirement, that generally means decades. For education savings, that might mean 4 years. For purchase goals like buying a house, that means in a single year. Same for maximizing estate values, where the real objective is a net after-tax lump sum — in other words a net after-tax income where the withdrawal period is one year.
- Extensive research reveals that there is no free and open source analysis software library that thoroughly handles all forms of investment taxation. And while some commercial financial planning software does address various issues accounting for taxation, there also appears to be none that comprehensively address all investment taxation scenarios to provide financial advisors or investors with the objective truth about which investment strategies are truly better for well-defined investment goals.
- Thus the need for After-Tax Investment Analysis (ATIA) software tools, built on top of a comprehensive After-Tax Investment Math (ATIM) library.
- Critical for accurate analysis of leveraged investment strategies, directly relevant to my SMART DEBT Coach mission.
- Critical for accurate analysis of the foundational savings goal of funding retirement — After-Tax Retirement Income.
Opportunity
Section titled “Opportunity”- This is an opportunity to add significant value to investors and the investment industries in many developed countries. It would make a “positive dent in the financial planning universe”.
End Goal
Section titled “End Goal”The end goal is to produce a comprehensive After-Tax Investment Math (ATIM) software library that handles all possible tax scenarios that exist in Canada, US, and generally — to reveal the After-Tax Reality that impacts investment strategies. This is a massively complex task.
Functionality
Section titled “Functionality”- Calculate After-Tax Income (ATI) for all investment scenarios
- different types of special accounts: tax deferred (RRSPs), tax exempt (TFSAs), tax assisted (RESPs, FHSAs)
- taxable accounts, handling all types of investment “distributions”: interest, dividends (eligible, ineligible), capital gains (taxable), deferred capital gains, return of capital (RoC), …
- Account types to model: International classification of taxation on savings
Name Contributions Income/growth Withdrawals Examples
EET Exempt Exempt Taxed RRSP, RPP, CPP
TEE Taxed Exempt Exempt TFSA, principle residence
TTE Taxed Taxed Exempt open/unsheltered investments
withdrawal of contribution is tax-exempt, but gains are taxable
EEE (new) Exempt Exempt Exempt FHSA (First Home Savings Account)
- Exempt Contributions produce tax refunds (if source deductions already made), which can be spent/reinvested/grossed up
- International Classification of Taxation on Savings
| Regime | Contributions | Income/Growth | Withdrawals | Examples | Notes |
|---|---|---|---|---|---|
| EET | Exempt | Exempt | Taxed | RRSP, RPP, CPP | |
| TEE | Taxed | Exempt | Exempt | TFSA, principal residence | |
| TTE | Taxed | Taxed | Exempt | Open/unsheltered investments | Withdrawal of contribution is tax-exempt, but gains are taxable |
| EEE | Exempt | Exempt | Exempt | FHSA (First Home Savings Account) | (new) |
- **taxation methods**: combined (federal + provincial), separate federal and provincial , limited (with or without unused amounts carried forward/back), different treatments of capital gains (rates, exemption thresholds and timelines, ...), ...- **hidden taxes**: like clawbacks of government benefits (GIS/OAS, cancelled Senior's Benefit), Ontario Health Premiums), ...- **other factors**: to be discovered later- Handle flexible tax profiles, for efficiency in communication and calculations
- During investment stages of accumulation (saving), withdrawal (retirement), and termination (estate)
- Allows easy analysis of After-Tax Reality of strategies like RRSPs: contrast single tax forever vs decreasing in retirement vs increasing, with GIS clawback or cancelled Senior’s Benefit
- Debt repayment: is a form of “investment”, with after-tax impacts, for both consumer (non-deductible) and investment debt (possibly deductible)
- Behavioural factors: critical and often overlooked (refund strategy with exempt/deduction-producing investments like RRSPs), what portion of freed-up cash flow is invested when debt is gone (debt vs invest analysis), what portion of new cash flow is invested (from bonus or inheritance), …
- Common investments: historical analysis of common investments (equity market indices, novel investments like Leveraged ETFs, …)
- Advanced investments or strategies: leveraging strategies (many), core popular option strategies, LEAPs, “Buy, Borrow, Die”, …
- Optimization last: Functionality, semantic code quality (for maintainability) are most important. Optimize for execution speed last.
- Probabilistic analysis (Monte Carlo) will be used.
- Python is probably preferred for semantic clarity. Only explore “or better” languages if execution speed optimization is worthwhile.
Artifacts
Section titled “Artifacts”- ATIM (After-Tax Investment Math) software library.
- Documentation: world-class, clear, concise, visual architectural diagrams, progressive.
- Testing system: establishes and maintains accuracy
- Auditability: proof of quality for partnerships with large firms
Phased Approach
Section titled “Phased Approach”- Brainstorm: To define a structure and approach that meets all desired functionality, iterating with multiple AI tools as needed.
- I have already thought deeply about such a math library, especially for investment debt analysis. But I do not want to introduce it yet to avoid steering in a suboptimal direction.
Task 1
Section titled “Task 1”- Thoroughly review all aspects of this development project.
- Identify any additional issues that might be overlooked and important to the long-term value and maintenance of such a library.
- Propose an initial structure to accommodate the core functionality. Advanced functionality and optimization of performance can be layered in later if this is a better sequencing. Use visual architectural diagrams if helpful for human understanding.
AI Response — 2026-03-18
Section titled “AI Response — 2026-03-18”ATIM Library — Comprehensive Brainstorming Analysis
Section titled “ATIM Library — Comprehensive Brainstorming Analysis”1. Complexity Analysis: Why This Project Is Genuinely Hard
Section titled “1. Complexity Analysis: Why This Project Is Genuinely Hard”This is not a “tax calculator with more features.” ATIM sits at the intersection of four complexity drivers that multiply each other — making naive approaches collapse quickly.
1.1 Tax Rules Are Jurisdiction-Specific, Year-Specific, and Interdependent
Section titled “1.1 Tax Rules Are Jurisdiction-Specific, Year-Specific, and Interdependent”Tax is not a single formula. It is a multi-layered pipeline where outputs of one stage become inputs to the next. Consider a Canadian taxpayer in Quebec:
Gross Income → Federal tax (progressive brackets, indexed annually) → Federal surtax (abolished 2001, but historical analysis needs it) → Provincial tax (Quebec has its OWN brackets, not piggyback) → Quebec abatement (16.5% reduction of federal tax) → CPP/QPP contributions (different rates CA vs QC) → EI premiums (different in QC due to QPIP) → Dividend gross-up + tax credit (eligible vs ineligible, different rates) → Capital gains inclusion rate (changed from 50% → 66.7% above $250K in 2024) → OAS clawback (15% recovery tax above threshold) → GIS clawback (50-75% implicit MTR depending on income type) → Ontario Health Premium (own bracket schedule, no credits apply)Each parameter in this pipeline can change year to year. The 2024 capital gains inclusion rate change alone demonstrates: a single parameter shift restructures optimal strategy across RRSP vs taxable vs TFSA for every affected taxpayer.
In the US, the pipeline is equally complex but structured differently:
Gross Income → AGI adjustments (above-the-line deductions) → Standard vs Itemized deduction (SALT cap, mortgage interest limits) → Ordinary income tax (7 brackets) → LTCG/Qualified dividends (0%/15%/20% based on taxable income) → NIIT (3.8% on investment income above threshold) → AMT (parallel tax system with own exemptions) → State income tax (0-13.3%, some piggyback, some independent) → IRMAA (Medicare surcharge, 2-year lookback) → Social Security taxation (up to 85% taxable, own formula)Key insight: You cannot compute any single tax in isolation. The dividend tax credit affects the base on which the OAS clawback is calculated. The RRSP deduction changes your net income which changes your GIS entitlement. Everything is coupled.
1.2 Multi-Year Stateful Simulation
Section titled “1.2 Multi-Year Stateful Simulation”Investment analysis is not a point-in-time calculation. It requires simulating decades of compounding, contributions, withdrawals, and tax events. State that carries forward between years includes:
- Adjusted Cost Base (ACB) for every holding in taxable accounts
- RRSP/TFSA contribution room (accumulated, used, carried forward)
- Capital loss carry-forwards (net capital losses, 3 years back / indefinite forward in CA; 3 back / indefinite forward in US)
- RRIF minimum withdrawal schedules (age-dependent, mandatory)
- GIS/OAS entitlement (based on prior-year income)
- US AMT credit carry-forwards
- Section 163(d) investment interest expense carry-forwards
- Net Operating Loss carry-forwards (US)
A single missed carry-forward can invalidate 30 years of simulation results.
1.3 Strategies Interact Non-Linearly (Optimization, Not Calculation)
Section titled “1.3 Strategies Interact Non-Linearly (Optimization, Not Calculation)”The question “Should I contribute to RRSP or TFSA?” is not answerable with a formula. It depends on:
- Current marginal tax rate vs expected future marginal rate
- Whether the RRSP refund is reinvested (behavioural factor)
- Whether GIS clawback applies in retirement (RRSP income triggers it; TFSA does not)
- Whether the contribution creates room for other strategies (Smith Manoeuvre requires RRSP refund reinvestment)
- Province of residence (Quebec’s unique tax structure changes the math)
These interactions mean the optimal strategy is not decomposable — you cannot optimize RRSP contributions independently of withdrawal strategy independently of account allocation. This is a coupled optimization problem.
1.4 Clawbacks Create Discontinuous Effective Marginal Rates
Section titled “1.4 Clawbacks Create Discontinuous Effective Marginal Rates”Clawbacks are the “hidden taxes” that make the effective tax landscape non-smooth:
Effective Marginal Tax Rate (Ontario, 2024, Senior with GIS)
Income Range Federal Provincial OAS GIS TOTAL$0 - $21,624 15% 5.05% - 50-75% 70-95% ← BRUTAL$21,624 - $30,000 15% 5.05% - - 20.05%$30,000 - $55,867 20.5% 9.15% - - 29.65%$55,867 - $90,599 26% 11.16% - - 37.16%$90,599 - $93,208 26% 11.16% 15% - 52.16% ← OAS CLAWBACK...$150,000 - $155,625 29% 12.16% 15% - 56.16%$155,625 - $220,000 29% 12.16% - - 41.16% ← OAS fully clawed back$220,000 - $235,675 33% 13.16% - - 46.16%The GIS clawback zone creates an effective MTR of 70-95% for low-income seniors — higher than any billionaire pays. This is the single most important “After-Tax Reality” insight for retirement planning, and most tools ignore it entirely.
These discontinuities mean:
- Gradient-based optimization fails (the landscape isn’t differentiable)
- Small income changes can cause large tax changes (cliff effects)
- The library must model clawbacks as explicit tax stages, not approximations
2. Architecture Proposal
Section titled “2. Architecture Proposal”2.1 Package Structure
Section titled “2.1 Package Structure”atim/├── core/ # Foundation types and utilities│ ├── money.py # Decimal-based Money type, Currency│ ├── types.py # Enums: Jurisdiction, AccountType, DistributionType│ ├── temporal.py # TaxYear, DateRange, Period│ └── registry.py # Plugin registry for jurisdictions│├── tax/ # Tax computation engine│ ├── engine.py # TaxEngine: orchestrates the pipeline│ ├── pipeline.py # TaxPipeline: ordered stages│ ├── brackets.py # Progressive bracket computation│ ├── credits.py # Tax credits (dividend, personal amounts, etc.)│ ├── clawbacks.py # Benefit clawbacks (OAS, GIS, IRMAA)│ ├── rules/ # Data-driven tax rules (YAML)│ │ ├── ca/│ │ │ ├── federal/│ │ │ │ ├── 2024.yaml│ │ │ │ └── 2025.yaml│ │ │ ├── on/│ │ │ ├── qc/│ │ │ └── bc/│ │ └── us/│ │ ├── federal/│ │ │ ├── 2024.yaml # Current law│ │ │ └── 2026_tcja_sunset.yaml # Scheduled law variant│ │ ├── ca_state/ # California│ │ └── ny/│ └── jurisdictions/ # Jurisdiction implementations│ ├── base.py # Abstract jurisdiction interface│ ├── composite.py # CompositeJurisdiction (Federal + Sub)│ ├── ca_federal.py│ ├── ca_ontario.py│ ├── ca_quebec.py # Dual-track: own brackets, abatement│ ├── us_federal.py│ └── us_california.py│├── accounts/ # Account type modeling│ ├── base.py # Account ABC│ ├── taxable.py # Open/unsheltered (TTE regime)│ ├── tax_deferred.py # RRSP, 401(k), IRA (EET regime)│ ├── tax_exempt.py # TFSA, Roth IRA (TEE regime)│ ├── hybrid.py # RESP, FHSA, 529 (special rules)│ └── acb.py # Adjusted Cost Base tracker│├── investments/ # Investment modeling│ ├── holding.py # Holding: units, ACB, distributions│ ├── distributions.py # DistributionType as first-class citizen│ ├── assets.py # Asset classes, historical returns│ └── debt.py # Investment debt, interest deductibility│├── strategy/ # Strategy definitions│ ├── contribution.py # Contribution strategies (RRSP, TFSA, taxable)│ ├── withdrawal.py # Withdrawal ordering, RRIF minimums, RMDs│ ├── rebalancing.py # Tax-aware rebalancing│ ├── leverage.py # Smith Manoeuvre, margin, HELOC strategies│ └── tax_loss.py # Tax-loss harvesting (with wash sale awareness)│├── sim/ # Simulation engine│ ├── scenario.py # Scenario: full definition of a simulation│ ├── yearstep.py # YearStep: immutable record of one year│ ├── simulator.py # Deterministic multi-year simulation│ ├── montecarlo.py # Monte Carlo wrapper│ └── timeline.py # Timeline: ordered sequence of YearSteps│└── analysis/ # Output and comparison ├── metrics.py # After-tax income, effective rates, IRR ├── comparison.py # Strategy A vs B comparison ├── audit.py # Audit trail with legal citations └── visualization.py # Chart generation (matplotlib optional)2.2 Tax Engine as Pipeline
Section titled “2.2 Tax Engine as Pipeline”The tax engine is the heart of ATIM. It must be modeled as an ordered pipeline of stages, not a single function.
CANADIAN TAX PIPELINE (Single Year) ===================================
┌─────────────────────────────────────────────────────────────────┐│ INPUTS ││ ┌──────────┐ ┌──────────┐ ┌───────────┐ ┌──────────────────┐ ││ │Employment│ │Investment│ │ RRSP/RRIF │ │ Carry-forwards │ ││ │ Income │ │Distrib- │ │Withdrawals│ │ (losses, room) │ ││ │ │ │utions │ │ │ │ │ ││ └────┬─────┘ └────┬─────┘ └─────┬─────┘ └────────┬─────────┘ ││ └─────────┬───┴─────────────┴────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 1: Income Classification │ ││ │ - Classify each dollar by type │ ││ │ - Apply gross-up (dividends) │ ││ │ - Apply inclusion rate (cap gains) │ ││ │ - Compute Total Income (Line 15000) │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 2: Net Income │ ││ │ - RRSP deduction │ ││ │ - Union dues, child care, moving │ ││ │ - Net Income (Line 23600) │◄── OAS/GIS threshold ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 3: Taxable Income │ ││ │ - Capital loss carry-forwards │ ││ │ - Other deductions │ ││ │ - Taxable Income (Line 26000) │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 4: Federal Tax │ ││ │ - Progressive brackets │ ││ │ - Basic personal amount credit │ ││ │ - Dividend tax credit │ ││ │ - Other non-refundable credits │ ││ │ - Quebec abatement (if QC resident) │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 5: Provincial/Territorial Tax │ ││ │ - Provincial brackets (own schedule) │ ││ │ - Provincial dividend tax credit │ ││ │ - Provincial surtaxes (ON, PEI) │ ││ │ - Ontario Health Premium │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 6: Clawbacks & Hidden Taxes │ ││ │ - OAS recovery tax (15% > threshold) │ ││ │ - GIS reduction (50-75% of income) │ ││ │ - Age credit reduction │ ││ │ - EI/CCB clawbacks (if applicable) │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 7: Payroll/Contribution Taxes │ ││ │ - CPP/CPP2 (or QPP/QPP2) │ ││ │ - EI premiums (or QC EI + QPIP) │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────────────────────────┐ ││ │ OUTPUT: TaxResult │ ││ │ - total_tax, effective_rate, marginal_rate_schedule │ ││ │ - by_stage breakdown (federal, provincial, clawbacks) │ ││ │ - net_income, carry_forwards_updated │ ││ │ - audit_trail (citation per stage) │ ││ └──────────────────────────────────────────────────────────┘ │└─────────────────────────────────────────────────────────────────┘ US TAX PIPELINE (Single Year) =============================
┌─────────────────────────────────────────────────────────────────┐│ INPUTS ││ (W-2, 1099-DIV, 1099-B, 1099-R, K-1, carry-forwards) ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 1: Gross Income & AGI │ ││ │ - Wages, interest, ordinary divs │ ││ │ - Short-term capital gains │ ││ │ - Above-the-line deductions │ ││ │ (IRA, HSA, student loan interest) │ ││ │ - AGI (Form 1040, Line 11) │◄── IRMAA, NIIT, ACA ││ └──────────────────┬───────────────────┘ thresholds ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 2: Taxable Income │ ││ │ - Standard deduction OR Itemized: │ ││ │ - SALT (capped at $10K) │ ││ │ - Mortgage interest │ ││ │ - Charitable contributions │ ││ │ - QBI deduction (Sec 199A) │ ││ │ - Taxable Income │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 3: Regular Tax │ ││ │ - Ordinary income → 7 brackets │ ││ │ - LTCG/Qual Divs → 0/15/20% │ ││ │ (stacked on top of ordinary) │ ││ │ - Credits (child, education, etc.) │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 4: Alternative Minimum Tax │ ││ │ - AMT income adjustments │ ││ │ - AMT exemption (phases out) │ ││ │ - AMT rate (26%/28%) │ ││ │ - Tentative minimum tax vs regular │ ││ │ - AMT credit carry-forward │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 5: Additional Taxes │ ││ │ - NIIT (3.8% on NII > $200K/$250K) │ ││ │ - Additional Medicare (0.9%) │ ││ │ - Sec 163(d) limitation │ ││ │ (investment interest ≤ NII) │ ││ │ - Early withdrawal penalties │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 6: State Income Tax │ ││ │ - State brackets (varies wildly) │ ││ │ - State-specific deductions/credits │ ││ │ - Some states piggyback federal AGI │ ││ │ - Some have own calculation │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────┐ ││ │ STAGE 7: Benefit Clawbacks │ ││ │ - Social Security taxation │ ││ │ (up to 85%, own formula) │ ││ │ - IRMAA surcharges (2-yr lookback) │ ││ │ - ACA subsidy clawback │ ││ └──────────────────┬───────────────────┘ ││ ▼ ││ ┌──────────────────────────────────────────────────────────┐ ││ │ OUTPUT: TaxResult (same structure as Canadian pipeline) │ ││ └──────────────────────────────────────────────────────────┘ │└─────────────────────────────────────────────────────────────────┘2.3 Jurisdiction Plugin System
Section titled “2.3 Jurisdiction Plugin System”Jurisdictions compose. A Canadian in Ontario is subject to CA_Federal + CA_Ontario. A New Yorker: US_Federal + US_NewYork + US_NYC (city tax). The architecture must support this:
JURISDICTION COMPOSITION ========================
┌─────────────────────────────────────────────┐ │ JurisdictionRegistry │ │ │ │ register("CA", ca_federal) │ │ register("CA-ON", ca_ontario) │ │ register("CA-QC", ca_quebec) │ │ register("US", us_federal) │ │ register("US-CA", us_california) │ │ register("US-NY", us_new_york) │ │ register("US-NY-NYC", us_nyc) │ │ │ │ resolve("CA-ON") → CompositeJurisdiction │ │ [ca_federal, ca_ontario] │ │ │ │ resolve("US-NY-NYC") → CompositeJurisdiction│ │ [us_federal, us_new_york, us_nyc] │ └─────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────┐ │ CompositeJurisdiction │ │ │ │ layers: List[Jurisdiction] │ │ │ │ compute_tax(income_profile, year) │ │ → runs each layer's pipeline │ │ → handles inter-layer dependencies │ │ (Quebec abatement, SALT deduction) │ │ → returns combined TaxResult │ └─────────────────────────────────────────────┘Each Jurisdiction provides:
- A
TaxPipeline(ordered stages) - A
TaxRulesloader (reads YAML for the given year) - Stage-specific computations
2.4 Data-Driven Tax Rules (YAML)
Section titled “2.4 Data-Driven Tax Rules (YAML)”Tax parameters change annually. Hardcoding them is unmaintainable. Instead, every number comes from a YAML file keyed by (jurisdiction, year):
jurisdiction: CAlevel: federalyear: 2024indexed: trueindexation_factor: 1.047 # CPI adjustment for 2024
brackets: - { floor: 0, ceiling: 55867, rate: 0.15 } - { floor: 55867, ceiling: 111733, rate: 0.205 } - { floor: 111733, ceiling: 154906, rate: 0.26 } - { floor: 154906, ceiling: 220000, rate: 0.29 } - { floor: 220000, ceiling: null, rate: 0.33 }
personal_amounts: basic: 15705 age_amount: 8790 # reduced when income > 42335 age_amount_threshold: 42335
capital_gains: inclusion_rate: 0.50 inclusion_rate_above_250k: 0.6667 # New for 2024 threshold: 250000
dividend_tax_credit: eligible: gross_up: 0.38 federal_credit_rate: 0.150198 # 6/38 of grossed-up amount ineligible: gross_up: 0.15 federal_credit_rate: 0.090301
oas: recovery_threshold: 90997 recovery_rate: 0.15 full_clawback_income: 148065 # approx
contribution_room: rrsp_limit: 31560 rrsp_rate: 0.18 # of prior year earned income tfsa_annual: 7000
citations: brackets: "ITA s. 117(2), indexed per s. 117.1" capital_gains: "ITA s. 38(a), amended 2024 Budget Bill C-69" oas_recovery: "OAS Act s. 12, Recovery Tax Regulations"This approach enables:
- Historical analysis (load 2015 rules for back-testing)
- What-if analysis (create
2026_proposed.yamlwith different rates) - Auditability (every number has a citation to legislation)
- Community contribution (adding a province = adding YAML + thin adapter)
2.5 YearStep as Auditable Unit
Section titled “2.5 YearStep as Auditable Unit”Every simulated year produces an immutable YearStep — a complete record of what happened and why:
YEARSTEP STRUCTURE ==================
┌─────────────────────────────────────────────────────┐│ YearStep(year=2035) ││ ││ ┌─────────────────────────────────────────┐ ││ │ inputs: │ ││ │ employment_income: $0 │ ││ │ rrif_withdrawal: $28,400 │ ││ │ tfsa_withdrawal: $15,000 │ ││ │ taxable_dividends: $8,200 (eligible) │ ││ │ capital_gains_realized: $12,000 │ ││ └─────────────────────────────────────────┘ ││ ││ ┌─────────────────────────────────────────┐ ││ │ tax_result: │ ││ │ federal_tax: $3,842 │ ││ │ provincial_tax: $2,156 │ ││ │ oas_clawback: $0 │ ││ │ gis_reduction: $14,200 ← HIDDEN TAX │ ││ │ total_tax: $20,198 │ ││ │ effective_rate: 31.7% │ ││ │ marginal_rates: {...per income type} │ ││ └─────────────────────────────────────────┘ ││ ││ ┌─────────────────────────────────────────┐ ││ │ account_states: │ ││ │ rrif_balance: $412,000 │ ││ │ tfsa_balance: $185,000 │ ││ │ taxable_acb: $45,200 │ ││ │ taxable_market_value: $62,300 │ ││ └─────────────────────────────────────────┘ ││ ││ ┌─────────────────────────────────────────┐ ││ │ carry_forwards: │ ││ │ capital_loss_cf: $3,200 │ ││ │ rrsp_room: $0 (retired) │ ││ │ tfsa_room: $7,000 (new annual) │ ││ └─────────────────────────────────────────┘ ││ ││ ┌─────────────────────────────────────────┐ ││ │ net_result: │ ││ │ gross_income: $63,600 │ ││ │ total_tax_and_clawbacks: $20,198 │ ││ │ net_after_tax_income: $43,402 │ ││ │ government_benefits_received: $7,800 │ ││ │ net_spendable: $51,202 │ ││ └─────────────────────────────────────────┘ ││ ││ audit_trail: [ ││ "RRIF minimum: 5.28% at age 72 (ITA 146.3(1))", ││ "Eligible div gross-up: 38% (ITA 82(1)(b))", ││ "GIS single rate: Table 1, max $1,065.47/mo", ││ ... ││ ] │└─────────────────────────────────────────────────────┘2.6 DistributionType as First-Class Citizen
Section titled “2.6 DistributionType as First-Class Citizen”Every dollar flowing through ATIM must carry its tax character. This is the most important type in the system:
class DistributionType(Enum): """Every dollar has a tax character that determines how it is taxed."""
# Employment & pension EMPLOYMENT = "employment" PENSION = "pension" # RPP, CPP/QPP, OAS RRSP_RRIF = "rrsp_rrif" # EET withdrawal
# Investment income (taxable accounts) INTEREST = "interest" # Fully taxable ELIGIBLE_DIVIDEND = "eligible_div" # Gross-up + credit (public corps) INELIGIBLE_DIVIDEND = "ineligible_div" # Gross-up + credit (private corps) CAPITAL_GAIN = "capital_gain" # Inclusion rate applies RETURN_OF_CAPITAL = "return_of_capital"# Tax-free, reduces ACB FOREIGN_INCOME = "foreign_income" # May have withholding tax + FTC
# US-specific QUALIFIED_DIVIDEND = "qualified_div" # Taxed at LTCG rates ORDINARY_DIVIDEND = "ordinary_div" # Taxed as ordinary income SHORT_TERM_GAIN = "short_term_gain" # Taxed as ordinary income LONG_TERM_GAIN = "long_term_gain" # 0/15/20% preferential MUNICIPAL_INTEREST = "muni_interest" # Federal tax-exempt
# Tax-sheltered (no immediate tax) TFSA_WITHDRAWAL = "tfsa" # TEE: tax-free ROTH_WITHDRAWAL = "roth" # TEE: tax-free FHSA_WITHDRAWAL = "fhsa" # EEE: tax-free (qualifying)Every Distribution is a (amount: Decimal, distribution_type: DistributionType) pair. The tax engine routes each type through the appropriate pipeline stage. This design ensures:
- No accidental mixing of tax treatments
- Correct handling of blended funds (e.g., a mutual fund distributing interest + capital gains + ROC)
- Clear audit trail (“$8,200 taxed as eligible dividend per ITA 82(1)(b)“)
3. Overlooked Issues
Section titled “3. Overlooked Issues”Beyond what the task file describes, the following 13 issues are critical to long-term library value:
3.1 Currency & Cross-Border Taxation
Section titled “3.1 Currency & Cross-Border Taxation”Problem: Canadian investors holding US-listed ETFs face three layers most tools ignore:
- Foreign withholding tax (15% on US dividends, reducible by treaty)
- Foreign tax credit (FTC) to offset Canadian tax
- FX gains/losses on disposition — the ACB must be tracked in CAD even for USD-denominated holdings, and the FX gain itself is a taxable capital gain
Impact on ATIM: The ACB tracker must support dual-currency tracking. Every foreign investment transaction needs a spot rate lookup. The FTC computation is a separate pipeline stage.
3.2 Inflation Indexation of Tax Parameters
Section titled “3.2 Inflation Indexation of Tax Parameters”Problem: Canada indexes most tax brackets and personal amounts to CPI annually. The US indexes under TCJA (using chained CPI-U). But not everything is indexed:
- Ontario Health Premium thresholds: frozen since 2004
- US AMT exemption: indexed post-TCJA, but was not indexed historically
- GIS thresholds: indexed quarterly
- Some provincial surtax thresholds: frozen
Impact on ATIM: The YAML rules must distinguish indexed: true/false per parameter. Multi-year simulations with inflation must apply indexation selectively. Getting this wrong compounds over 30 years.
3.3 Tax Law Versioning & Sunset Provisions
Section titled “3.3 Tax Law Versioning & Sunset Provisions”Problem: US TCJA provisions expire after 2025 (brackets revert, SALT cap removed, personal exemptions return). Should the library simulate “current law” or “scheduled law”?
Impact on ATIM: The rules system needs scenario variants: 2026_current_law.yaml vs 2026_tcja_sunset.yaml. Users must be able to specify which assumption to use. The default should be scheduled law (what’s actually on the books), with current-law-extended as an option.
3.4 Interaction Between Accounts in the Same Year
Section titled “3.4 Interaction Between Accounts in the Same Year”Problem: An RRSP contribution in the same year as a large capital gain changes net income, which changes OAS clawback, which changes effective tax, which changes whether the RRSP contribution was optimal. These are circular dependencies within a single year.
Impact on ATIM: The within-year computation must either:
- Use a fixed-point iteration (compute tax → adjust strategy → recompute until stable)
- Define a strict ordering of decisions within the year (contribute first, compute tax second)
Option 2 is simpler and matches how real tax returns work (you make decisions, then file). But optimization requires Option 1.
3.5 ACB Tracking Complexity
Section titled “3.5 ACB Tracking Complexity”Problem: ACB is not just “purchase price + commissions.” It includes:
- Superficial loss rule (Canada): sell at a loss, rebuy within 30 days → loss denied, added to ACB of repurchased shares
- Wash sale rule (US): similar but 61-day window, and applies across accounts (including IRA!)
- Return of Capital reduces ACB (can go below zero → deemed capital gain)
- Stock splits, mergers, corporate actions alter ACB
- Identical property rule (Canada): all shares of the same security across all taxable accounts share one ACB per unit
Impact on ATIM: The ACB tracker is a significant subsystem. It must track per-security, across accounts (for identical property), handle corporate actions, and enforce superficial loss / wash sale rules. This alone could be a 2,000+ line module.
3.6 Corporate Ownership (CCPC Investing)
Section titled “3.6 Corporate Ownership (CCPC Investing)”Problem: Many Canadian advisors use corporate-owned investment portfolios. This introduces an entirely separate tax universe:
- Corporate tax rates on passive investment income (50.17% + refundable portion)
- RDTOH (Refundable Dividend Tax on Hand) — refunded when dividends paid
- CDA (Capital Dividend Account) — tax-free extraction of capital gains
- Passive income rules — reduce small business deduction when passive income > $50K
- Integration principle — the system is designed so corporate + personal tax ≈ personal tax, but imperfect integration creates real differences
Impact on ATIM: Corporate ownership is a Phase 5+ feature, but the architecture must not preclude it. The Account abstraction must support a corporate wrapper that adds its own tax layer before personal tax.
3.7 Spousal/Household Optimization
Section titled “3.7 Spousal/Household Optimization”Problem: Tax is assessed on individuals, but families optimize jointly:
- Spousal RRSP contributions (contributor gets deduction, spouse’s income on withdrawal)
- Pension income splitting (up to 50% of qualifying pension)
- Attribution rules — income on gifted/loaned assets attributed back to higher-income spouse
- US joint filing — entirely different bracket schedule
- Income splitting via prescribed-rate loans (Canada, using CRA prescribed rate)
Impact on ATIM: The Scenario must support 1 or 2 taxpayers with linked optimization. This doubles the state space. Single-person simulation should come first, with household as a Phase 4+ extension.
3.8 Decimal Precision
Section titled “3.8 Decimal Precision”Problem: Floating-point arithmetic introduces compounding errors over 30+ year simulations. A $0.01 rounding error per year on a $1M portfolio, compounded, produces material discrepancies. Tax authorities compute to the cent.
Impact on ATIM: All monetary values must use decimal.Decimal with explicit rounding rules (typically ROUND_HALF_UP to match CRA/IRS convention). This is a foundational decision that must be made at project start — retrofitting Decimal into a float-based codebase is painful. The Money type in atim.core should enforce this from day one.
3.9 Regulatory Compliance & Audit Trail
Section titled “3.9 Regulatory Compliance & Audit Trail”Problem: If ATIM is used to advise clients, regulators may require proof that calculations are correct. A financial advisor using ATIM-derived recommendations needs to show why the math says what it says.
Impact on ATIM: Every TaxResult must carry an audit_trail — a list of (computation_step, legal_citation, input_values, output_value) tuples. Example: "Federal tax on first $55,867 at 15% = $8,380.05 (ITA s. 117(2)(a), 2024 indexed)". This is not cosmetic — it’s a professional requirement.
3.10 Sequence-of-Returns Risk
Section titled “3.10 Sequence-of-Returns Risk”Problem: In the withdrawal phase, the order of returns matters enormously. Two portfolios with identical average returns but different sequences can produce vastly different after-tax outcomes:
- Bad early returns → forced to withdraw more units → less to compound → lower lifetime income
- This interacts with taxation: forced larger withdrawals push income into higher brackets
Impact on ATIM: The Monte Carlo module (Phase 6) must model sequence risk explicitly. The deterministic simulator should support user-specified return sequences (not just average returns). This is essential for honest retirement income projections.
3.11 Tax Loss Harvesting Interactions
Section titled “3.11 Tax Loss Harvesting Interactions”Problem: Tax loss harvesting (TLH) is not “sell losers, deduct losses.” It has complex interactions:
- Wash sale / superficial loss rules limit when you can rebuy
- US Section 163(d): investment interest deduction is limited to Net Investment Income (NII). Capital losses reduce NII, which can reduce the 163(d) deduction, creating a negative feedback loop for leveraged investors doing TLH
- Capital loss carry-forward rules differ by jurisdiction (CA: indefinite forward, 3 years back; US: $3,000/year against ordinary income, unlimited against gains)
Impact on ATIM: TLH must be modeled as a strategy that interacts with the full tax pipeline, not as an isolated optimization. The 163(d) interaction is particularly important for the leveraged investing use case central to SMART DEBT.
3.12 Mandatory Withdrawals
Section titled “3.12 Mandatory Withdrawals”Problem: Tax-deferred accounts have forced withdrawal schedules:
- Canada RRIF: must convert RRSP by age 71, minimums start immediately (5.28% at 72, rising)
- US RMD: Required Minimum Distributions from traditional IRA/401(k), starting at 73 (SECURE 2.0)
- These are not optional — failure triggers severe penalties (50% in CA, 25% in US)
Impact on ATIM: The withdrawal strategy module must enforce minimums before any optimization. RRIF/RMD withdrawals are inputs to the tax pipeline that cannot be deferred. The simulator must check these constraints every year and override any strategy that violates them.
3.13 Estate Tax vs Deemed Disposition
Section titled “3.13 Estate Tax vs Deemed Disposition”Problem: Canada and the US handle death completely differently:
- Canada: no estate tax, but deemed disposition at death (all assets sold at FMV → capital gains tax on everything). RRSP/RRIF fully included in income of the deceased (unless rolled to spouse).
- US: step-up in basis at death (heirs get FMV as new cost basis → no capital gains on appreciation). But estate tax applies above exemption ($13.61M in 2024, sunset to ~$7M in 2026).
- This creates the “Buy, Borrow, Die” strategy in the US (which doesn’t work in Canada)
Impact on ATIM: The terminal year of any simulation must model the correct death event. Canada: deemed disposition + final tax return. US: estate tax calculation + basis step-up. This fundamentally affects which strategies are optimal for estate planning.
4. Phased Development Roadmap
Section titled “4. Phased Development Roadmap”Phase 1: Core Foundation (Minimum Viable Tax Engine)
Section titled “Phase 1: Core Foundation (Minimum Viable Tax Engine)”Goal: Single-year tax computation for one Canadian individual with RRSP + taxable account.
Deliverables:
-
atim.core:Money(Decimal-based),DistributionType,TaxYear,Jurisdictionenum -
atim.tax.brackets: Progressive bracket computation (generic) -
atim.tax.credits: Basic personal amount, dividend tax credit -
atim.tax.rules: YAML loader, CA federal 2024, CA Ontario 2024 -
atim.tax.jurisdictions:CA_Federal,CA_Ontario,CompositeJurisdiction -
atim.tax.engine:TaxEngine.compute(income_profile, jurisdiction, year) → TaxResult -
atim.accounts:TaxableAccount(with ACB),RRSP(contribution room tracking) -
atim.investments.distributions:Distribution(amount, type)pairs - Test suite: 10+ known-answer tests against manually computed tax returns
- Audit trail: every TaxResult carries legal citations
What “done” looks like: You can compute the total tax (federal + Ontario) for a person with $80K salary, $5K eligible dividends, $10K capital gain, and $15K RRSP contribution, and get the exact same number as a manual tax return.
Phase 2: Multi-Year Simulation + Quebec
Section titled “Phase 2: Multi-Year Simulation + Quebec”Goal: Run 30-year accumulation + 25-year withdrawal simulations. Add Quebec’s dual-track tax.
Deliverables:
-
atim.sim.yearstep: ImmutableYearSteprecord -
atim.sim.simulator: Deterministic multi-year loop -
atim.sim.scenario:Scenariodefinition (person, strategy, horizon) -
atim.accounts.tax_exempt: TFSA with contribution room tracking -
atim.strategy.contribution: Basic RRSP-first, TFSA-first, split strategies -
atim.strategy.withdrawal: Basic withdrawal ordering (taxable → RRIF → TFSA) - Quebec jurisdiction: own brackets, abatement, QPP, QPIP
- Inflation indexation: apply indexed vs frozen parameter growth
- Carry-forward tracking: capital losses, unused contribution room
- Test suite: 5+ multi-year scenarios validated against commercial software or CRA examples
What “done” looks like: Compare 30-year RRSP-vs-TFSA-vs-taxable for an Ontario resident and a Quebec resident, showing after-tax retirement income for each strategy.
Phase 3: US Jurisdiction
Section titled “Phase 3: US Jurisdiction”Goal: Full US federal tax pipeline + 2-3 state implementations.
Deliverables:
- US federal pipeline: 7 brackets, LTCG stacking, standard/itemized deductions
- NIIT (3.8% Net Investment Income Tax)
- Section 163(d) investment interest limitation
- AMT (Alternative Minimum Tax) with credit carry-forward
- US account types: Traditional IRA, 401(k), Roth IRA, taxable brokerage
- RMD enforcement (SECURE 2.0 rules)
- State implementations: California, New York (+ NYC), one no-income-tax state (Texas/Florida)
- TCJA sunset scenario variants (2026+)
- Test suite: 10+ US scenarios, validated against IRS examples / TurboTax outputs
What “done” looks like: Compare Traditional-vs-Roth-vs-taxable for a California resident with LTCG, qualified dividends, and NIIT exposure over 30 years.
Phase 4: Clawbacks + Hidden Taxes
Section titled “Phase 4: Clawbacks + Hidden Taxes”Goal: Model the brutal effective marginal rates that most tools ignore.
Deliverables:
- Canadian: OAS recovery tax, GIS clawback (with income-type sensitivity), Age Amount reduction
- Canadian: Ontario Health Premium, provincial surtaxes
- US: Social Security taxation (up to 85%), IRMAA surcharges (with 2-year lookback)
- US: ACA premium subsidy clawback
- Effective marginal rate schedule output (showing all clawback-inclusive rates)
-
atim.analysis.metrics: After-tax income, effective rate, marginal rate by income type -
atim.analysis.comparison: Side-by-side strategy comparison with clawback visibility
What “done” looks like: Show that $1,000 of RRIF income for a GIS-eligible senior costs $700+ in combined tax and clawback, while $1,000 of TFSA income costs $0 — the core “After-Tax Reality” insight.
Phase 5: Advanced Strategies
Section titled “Phase 5: Advanced Strategies”Goal: Model the sophisticated strategies that make ATIM uniquely valuable.
Deliverables:
- Smith Manoeuvre (Canadian mortgage-to-investment-loan conversion)
- Leveraged investing: margin, HELOC, investment loans (with interest deductibility rules)
- Buy, Borrow, Die (US: leverage + step-up in basis)
- Tax loss harvesting (with wash sale / superficial loss enforcement)
- Prescribed-rate spousal loan (Canada)
- Corporate investing (CCPC): passive income, RDTOH, CDA (high-level)
- RESP and FHSA modeling
- Debt as investment: consumer debt repayment vs investing analysis
What “done” looks like: Model the Smith Manoeuvre over 25 years showing the after-tax cost of the mortgage converted to investment loan, after-tax investment returns, and net benefit vs paying down the mortgage — the core SMART DEBT use case.
Phase 6: Monte Carlo + Optimization
Section titled “Phase 6: Monte Carlo + Optimization”Goal: Probabilistic analysis and strategy optimization.
Deliverables:
-
atim.sim.montecarlo: Monte Carlo wrapper (numpy for random returns) - Sequence-of-returns modeling (withdrawal phase)
- Percentile-based outcome reporting (5th, 25th, 50th, 75th, 95th)
- Strategy optimizer: given a person profile, find optimal contribution/withdrawal strategy
- Sensitivity analysis: which parameters most affect outcome
- Household/spousal optimization (pension splitting, spousal RRSP, joint filing)
What “done” looks like: Monte Carlo simulation of Smith Manoeuvre showing probability distribution of outcomes, with 5th percentile “worst case” and median “expected case” after-tax retirement income.
Phase 7: Documentation + Auditability Formalization
Section titled “Phase 7: Documentation + Auditability Formalization”Goal: Production-ready documentation and proof of correctness.
Deliverables:
- Architecture documentation with diagrams
- API reference (auto-generated from docstrings)
- Tutorial: “Computing your first after-tax return”
- Cookbook: common scenarios with worked examples
- Audit formalization: every computation traceable to legislation
- Known-answer test suite: 20-30 scenarios validated against professional tax software
- Performance benchmarks (Monte Carlo with 10K+ iterations)
5. Testing & Implementation Notes
Section titled “5. Testing & Implementation Notes”5.1 Known-Answer Testing Strategy
Section titled “5.1 Known-Answer Testing Strategy”The most important tests are known-answer tests — scenarios where the correct tax result has been independently computed (manually, or via commercial tax software):
- Simple employment income — just salary, basic personal amount, federal + provincial
- Eligible dividends — gross-up, DTC, verify integration works
- Capital gains — inclusion rate, verify ACB tracking
- RRSP contribution — verify deduction reduces net income correctly
- RRSP withdrawal in retirement — verify full inclusion as income
- TFSA withdrawal — verify zero tax impact, zero clawback impact
- GIS-eligible senior — verify clawback calculation, show the 70%+ effective rate
- OAS clawback — verify 15% recovery tax triggers at correct threshold
- Ontario Health Premium — verify own bracket schedule applies
- Quebec dual-track — verify abatement + own brackets produce correct combined tax
- US LTCG stacking — verify 0% bracket, 15% bracket, 20% bracket transitions
- US NIIT — verify 3.8% applies only above threshold, only on NII
- US Section 163(d) — verify investment interest limited to NII
- US AMT — verify AMT triggers, credit carry-forward works
- Multi-year RRSP vs TFSA — verify 30-year comparison produces expected outcome
- Smith Manoeuvre — verify interest deductibility, gradual conversion
- Capital loss carry-forward — verify correct application across years
- RRIF minimum — verify forced withdrawal at correct percentage
- US RMD — verify correct age trigger and minimum amount
- Deemed disposition at death (Canada) — verify final return computation
5.2 Dependencies (Minimal)
Section titled “5.2 Dependencies (Minimal)”# Core (no external dependencies)python >= 3.11 # for modern typing, StrEnumdecimal # stdlib — mandatory for monetary precision
# Datapyyaml # tax rules files
# Testingpytest # test runnerpytest-cov # coverage reporting
# Optional (Phase 6+)numpy # Monte Carlo random number generationmatplotlib # visualization (optional)No pandas, no complex frameworks, no ORMs. The library should be pure computation with minimal external surface area.
5.3 Naming Conventions
Section titled “5.3 Naming Conventions”Domain-specific naming — readable by a tax professional, not just a programmer:
# YES — domain languageclass ScheduleNCarryForward: ...class NetInvestmentIncome: ...class EligibleDividendGrossUp: ...class OASRecoveryTax: ...class RRIFMinimumWithdrawal: ...def compute_capital_gains_inclusion(gains, year): ...
# NO — generic programmer namesclass CarryFwd: ...class NII: ...class DivGrossUp: ...class Clawback: ... # which clawback?class MinWithdrawal: ...def calc_cg(g, y): ...5.4 Key Design Decisions (For Task 2+)
Section titled “5.4 Key Design Decisions (For Task 2+)”These decisions should be made explicitly during implementation planning:
- Immutability: Should
YearStep,TaxResult,AccountStatebe frozen dataclasses or mutable? (Recommendation: frozen — enables caching, debugging, parallel Monte Carlo) - Error handling: What happens when tax rules are missing for a year? (Recommendation: explicit error, never extrapolate)
- Plugin boundary: How much can a jurisdiction override? (Recommendation: stages are fixed structure, but computations within stages are pluggable)
- Configuration vs code: Where is the line between YAML data and Python logic? (Recommendation: numbers and rates in YAML, algorithms in Python. The dividend tax credit formula is code; the rate is data)
- Python version: 3.11+ for
StrEnum,tomllib, modern type hints (Recommendation: 3.12+ to use latest typing features)
Summary
Section titled “Summary”ATIM is a genuinely ambitious project — comparable in complexity to an accounting engine or financial planning platform. The four complexity drivers (jurisdiction specificity, multi-year state, non-linear interactions, discontinuous clawbacks) mean that naive approaches will fail at scale.
However, the architecture proposed here — pipeline-based tax engine, jurisdiction composition, data-driven rules, immutable year steps, distribution types as first-class citizens — provides a foundation that can grow from a single Canadian province to multi-country, multi-decade, Monte Carlo-enabled analysis.
The phased roadmap ensures each phase delivers standalone value:
- Phase 1 alone is a useful Canadian tax calculator
- Phase 2 enables the core RRSP-vs-TFSA after-tax comparison
- Phase 4 reveals the “After-Tax Reality” of clawbacks
- Phase 5 delivers the SMART DEBT leverage analysis
The 13 overlooked issues identified ensure the architecture doesn’t paint itself into a corner — particularly around corporate ownership, household optimization, and cross-border taxation, which are difficult to retrofit.
Next Steps for Human
Section titled “Next Steps for Human”- Review this analysis — does it match your mental model?
- Flag any issues or strategies I’ve missed
- Decide if corporate ownership (3.6) and spousal optimization (3.7) should be elevated in priority
- Confirm Phase 1 scope as the right starting point
- When ready, create Task 2 for Phase 1 implementation planning
Human Response
Section titled “Human Response”- Questions
- Explain 95% effective tax for low-income seniors (GIS).
- Goal is “80/20 practical understanding” of fundamentals, based on first principals
- CRITICAL to turn “genuinely hard” project into “practical, doable”
- avoid the big wrong conclusions (some are opposite of conventional wisdom)
- get the foundation right, and don’t worry about the small details (like engineers)
- Important to know that a low-income 60-year old should NOT invest an inheritance in RRSPs (following the industry rule-of-thumb) because the contribution in a 20% tax rate soon (unknowingly) faces a 70% tax rate during withdrawals (20% tax + 50% clawback = 70% tax rate). It is not important whether the low-tax bracket is 20% or 23%. The 50% effective change in taxes is (almost all) of the issue to factor into strategy choice.
- 80% of “Tax Pipeline” is not needed
- don’t need a mini-tax return annually
- approximations and ratios are close enough for “much closer” to After-Tax Reality, relative to before-tax (lump sum) reference
- Do need to track ACB to get real ATI of taxable capital gain investments.
- Decimal precision
- Not relevant based on what is unknowable.
- Focus on Ikigai for financial strategies
- Goldilocks sweet spot of win-win-win
- Profitable for financial industry
- Sadly most important too often, as almost no one profits advising to pay down 20-30% credit card debt
- Simple enough to understand quickly, for clients AND advisors (unless profit is high)
- Complex (and controversial) strategies increase training, compliance, ongoing costs
- Most advisors receive little foundational strategies education. (CFP designation is almost totally about product and regulation, not the details about optimal investing or retirement planning).
- Benefits client
- Low business risk
- Lawsuits and bad PR are expensive, and very bad for dealer and industry
- Profitable for financial industry
- Goldilocks sweet spot of win-win-win
- Simplifying profiles
- We can meaningfully better understand the After-Tax Reality for the most common life profiles (or those profitable enough for the industry to focus on). That generally means for the investment industry, the HNW and upper- and middle-income savers.
- A few basic approximate tax profiles carries most of the load: middle/high-income + tax rate same vs up vs down. Use today’s approximate rates for history and future, and understand impact of changes to this reference point.
- Don’t need to model changing tax every year. Only at retirement (savings boundary turning to withdrawals).
- Ignore less common and complex scenarios for now (until market demands it).
- Corporations, cross-border investing, …
- Behavioural reality: Focus on what is knowable, and can influence
- It is impossible to know what minor or even major government changes happen in future. But we CAN better understand the impact. (The Senior’s Benefit proposed legislation in 1996 effectively pushed middle-income savers in a 40% tax bracket into a 60% tax bracket during retirement, reversing the benefit of RRSPs.)
- We CAN know that costs (real taxes) don’t go up, paying later is better than sooner. Thus, RRSPs make sense if tax rates don’t go up (or even not too much), ignoring behavioural factors (spending refunds).
AI Response — 2026-03-18 (Round 2)
Section titled “AI Response — 2026-03-18 (Round 2)”Good first-round feedback. This fundamentally recalibrates the approach — from “tax engine” to “strategy truth-teller.” Let me address everything.
Question: How Does GIS Create 70-95% Effective Tax?
Section titled “Question: How Does GIS Create 70-95% Effective Tax?”The Guaranteed Income Supplement (GIS) is a monthly benefit for low-income seniors (65+). It’s clawed back as income rises. Here’s the mechanism:
GIS Clawback Mechanics (2024, single senior):
- Maximum GIS: ~$1,065/month ($12,781/year)
- Clawback rate: 50% of most income types (employment, pension, RRSP/RRIF, interest)
- For every $1 of RRIF income, GIS is reduced by $0.50
The compound effect — a $1,000 RRIF withdrawal for a low-income Ontario senior:
| Layer | Rate | Tax on $1,000 |
|---|---|---|
| Federal income tax | 15% | $150 |
| Ontario income tax | 5.05% | $50 |
| GIS clawback | 50% | $500 |
| Total | 70.05% | $700 |
The senior keeps $300 of the $1,000 RRIF withdrawal.
How it gets to 95%: For a senior also receiving the Allowance (age 60-64 spouse of GIS recipient) or when provincial benefit clawbacks stack on top:
- GIS clawback: 50% (some income ranges 75%)
- OAS clawback: can overlap in certain income zones
- Provincial benefits (Ontario Trillium, GST/HST credit) also claw back
- Stacked: 15% federal + 5% provincial + 75% GIS = 95%
The 75% GIS rate applies to income above ~$5,000 for certain benefit tiers under Table 2 (married, spouse also receiving OAS).
The RRSP trap this reveals:
- Person at age 55, earning $45K, contributes to RRSP → saves ~20% in tax
- At age 68, withdraws from RRIF with low other income → pays ~70% effective tax (20% income tax + 50% GIS clawback)
- Net result: LOST 50 cents on every dollar “saved”
- The conventional wisdom (“contribute to RRSP, you’ll be in a lower bracket in retirement”) is catastrophically wrong for this person
- TFSA would have been tax-free in AND out — the correct answer by a massive margin
This is the poster child for why After-Tax Reality matters. Before-tax thinking says “RRSP beats taxable.” After-Tax Reality says “RRSP destroys wealth for GIS-eligible retirees.”
Recalibration: From Tax Engine to Strategy Truth-Teller
Section titled “Recalibration: From Tax Engine to Strategy Truth-Teller”Your feedback reshapes the core philosophy. Here’s what I heard and how it changes the approach:
What You Said → What It Means for ATIM
Section titled “What You Said → What It Means for ATIM”| Feedback | Implication |
|---|---|
| ”80/20 practical understanding” | ATIM is not a tax return calculator. It’s a strategy comparison engine using approximate rates. |
| ”Don’t need a mini-tax return” | Kill the 7-stage pipeline. Replace with tax profiles — a few representative rates that capture 80% of the truth. |
| ”Approximations close enough” | Use effective marginal rate bands, not bracket-by-bracket computation. The insight is “RRSP costs 70% not 20%” — whether it’s 68% or 72% doesn’t change the conclusion. |
| ”Do need ACB tracking” | ACB is the one place precision matters — because deferred capital gains are a real dollar advantage that compounds. Keep this. |
| ”Decimal precision not relevant” | Float is fine. The unknowable future (returns, tax law changes, inflation) dwarfs rounding errors. Drop the Decimal mandate. |
| ”Ikigai for strategies” | ATIM should evaluate strategies on a multi-axis scorecard (profitable, simple, beneficial, low-risk), not just raw after-tax return. |
| ”Few basic tax profiles” | Three profiles carry the load: same rate, rate goes down, rate goes up (including clawback). Today’s rates as baseline. |
| ”Ignore corporations, cross-border” | Defer entirely. Focus on the individual investor in one country. |
| ”Focus on knowable, influenceable” | Model the sensitivity to changes, not the changes themselves. “If your rate goes up 10%, here’s what happens to the RRSP advantage.” |
The Revised Mental Model
Section titled “The Revised Mental Model”BEFORE (Round 1): AFTER (Round 2):Tax Return Simulator Strategy Truth-Teller━━━━━━━━━━━━━━━━━━━━ ━━━━━━━━━━━━━━━━━━━━━
7-stage tax pipeline Tax Profile (3-5 rates)Every bracket computed Approximate effective ratesYear-by-year rules Accumulation rate + Withdrawal rateYAML per jurisdiction/year Simple config: "Ontario middle-income"Decimal precision Float (good enough)Regulatory audit trail Strategy insight narrativeFull tax return output "Strategy A beats B by $X over N years"
KEPT FROM ROUND 1:- ACB tracking (real dollars, compounds)- DistributionType (interest vs dividend vs cap gain matters)- Clawback awareness (the whole point)- Multi-year simulation (compounding is the engine)- Account type modeling (EET/TEE/TTE/EEE)Revised Architecture: The 80/20 ATIM
Section titled “Revised Architecture: The 80/20 ATIM”Tax Profiles Replace Tax Pipelines
Section titled “Tax Profiles Replace Tax Pipelines”Instead of computing tax from first principles, ATIM uses Tax Profiles — pre-defined effective rate sets that capture the After-Tax Reality for common investor archetypes:
TAX PROFILE SYSTEM ==================
┌──────────────────────────────────────────────────────┐│ TaxProfile ││ ││ name: "Ontario Middle-Income" ││ jurisdiction: CA-ON ││ ││ ┌────────────────────────────────────────────┐ ││ │ Accumulation Phase Rates │ ││ │ │ ││ │ marginal_rate: 33% (combined) │ ││ │ interest_rate: 33% (= marginal) │ ││ │ eligible_div_rate: 18% (after DTC) │ ││ │ capital_gain_rate: 16.5% (50% × 33%) │ ││ │ rrsp_deduction_value: 33% (= marginal) │ ││ └────────────────────────────────────────────┘ ││ ││ ┌────────────────────────────────────────────┐ ││ │ Withdrawal Phase Rates — Scenario A │ ││ │ "Rate stays same" │ ││ │ │ ││ │ marginal_rate: 33% │ ││ │ rrsp_withdrawal_rate: 33% │ ││ │ clawback_rate: 0% │ ││ │ effective_rrsp_cost: 33% │ ││ └────────────────────────────────────────────┘ ││ ││ ┌────────────────────────────────────────────┐ ││ │ Withdrawal Phase Rates — Scenario B │ ││ │ "Rate drops" (classic RRSP pitch) │ ││ │ │ ││ │ marginal_rate: 20% │ ││ │ rrsp_withdrawal_rate: 20% │ ││ │ clawback_rate: 0% │ ││ │ effective_rrsp_cost: 20% │ ││ │ RRSP advantage: 13pp (saved 33, │ ││ │ pay 20) │ ││ └────────────────────────────────────────────┘ ││ ││ ┌────────────────────────────────────────────┐ ││ │ Withdrawal Phase Rates — Scenario C │ ││ │ "GIS clawback trap" │ ││ │ │ ││ │ marginal_rate: 20% │ ││ │ rrsp_withdrawal_rate: 20% │ ││ │ clawback_rate: 50% ← GIS │ ││ │ effective_rrsp_cost: 70% ← THE TRAP │ ││ │ RRSP LOSS: -37pp (saved 33, │ ││ │ pay 70) │ ││ └────────────────────────────────────────────┘ ││ ││ (Scenario D, E... for OAS clawback, rate goes up) │└──────────────────────────────────────────────────────┘A handful of profiles covers the landscape:
| Profile | Accumulation Rate | Withdrawal Scenarios | Who |
|---|---|---|---|
| Low-income CA | ~20% | Same / GIS trap (70%) | Modest savers |
| Middle-income CA | ~33% | Same / Down (20%) / GIS (70%) | Core market |
| High-income CA | ~48% | Same / Down (33%) / OAS clawback (53%) | HNW |
| Middle-income US | ~28% | Same / Down (15%) / SS taxation | Core US market |
| High-income US | ~40% | Same / Down / IRMAA / NIIT | HNW US |
For each profile, the strategies (RRSP, TFSA, taxable, leverage) can be compared using just these rates — no tax return needed.
What Still Needs Precision: ACB and Distribution Types
Section titled “What Still Needs Precision: ACB and Distribution Types”Even in the 80/20 model, two things need real tracking:
ACB (Adjusted Cost Base):
- Taxable accounts defer capital gains until sale
- The deferred gain compounds tax-free — this is a real, quantifiable advantage
- Must track: purchases (add to ACB), return of capital (reduce ACB), sales (trigger gain/loss)
- Superficial loss / wash sale rules can wait for later phases
Distribution Types:
- A mutual fund distributing 40% interest + 30% eligible dividends + 20% capital gains + 10% ROC has a VERY different after-tax return than one distributing 100% capital gains
- The tax profile rates differ by distribution type (interest at 33%, cap gains at 16.5%, eligible divs at 18%)
- This is the difference between a meaningless and a meaningful comparison
Revised Package Structure
Section titled “Revised Package Structure”atim/├── core/│ ├── types.py # AccountType, DistributionType, Phase (accum/withdrawal)│ └── config.py # Scenario configuration│├── tax/│ ├── profile.py # TaxProfile: effective rates by income type│ ├── profiles/ # Pre-built profiles (YAML or Python dicts)│ │ ├── ca_low.py│ │ ├── ca_mid.py│ │ ├── ca_high.py│ │ └── us_mid.py│ └── clawbacks.py # GIS, OAS, SS clawback rate modeling│├── accounts/│ ├── base.py # Account ABC: balance, contribute, withdraw│ ├── registered.py # RRSP/RRIF, TFSA, Roth, 401k│ ├── taxable.py # Open account with ACB tracking│ └── acb.py # ACB tracker (the one precision component)│├── investments/│ ├── holding.py # Holding: distribution mix, return assumption│ └── distributions.py # Distribution(amount, type) — tax character│├── strategy/│ ├── contribution.py # Where to put savings (RRSP/TFSA/taxable/debt)│ ├── withdrawal.py # Where to draw income (ordering, RRIF minimums)│ └── leverage.py # Smith Manoeuvre, investment loans│├── sim/│ ├── scenario.py # Full scenario definition│ ├── yearstep.py # One year's record (simplified)│ └── simulator.py # Multi-year loop│└── analysis/ ├── comparison.py # Strategy A vs B ├── scorecard.py # Ikigai multi-axis evaluation └── sensitivity.py # "What if rate changes by X?"Half the files, a fraction of the complexity. The tax pipeline is gone, replaced by a lookup.
The Ikigai Scorecard for Strategies
Section titled “The Ikigai Scorecard for Strategies”This is a distinctive feature — evaluating strategies not just on math, but on the four axes you identified:
STRATEGY IKIGAI SCORECARD =========================
Strategy: Smith Manoeuvre (Convert mortgage to investment loan)
┌─────────────────────────────────────────────────────┐│ ││ BENEFITS CLIENT ████████████░░ 8/10 ││ After-tax advantage: Significant if rates ││ are same or higher. ││ Interest deductible. ││ ││ PROFITABLE (Industry) ████████████░░ 8/10 ││ AUM growth, ongoing relationship, product ││ sales (funds, insurance). ││ ││ SIMPLE ENOUGH ██████░░░░░░░░ 5/10 ││ Requires understanding of interest ││ deductibility, readvanceable mortgage. ││ Many advisors unfamiliar. ││ ││ LOW BUSINESS RISK ██████████░░░░ 7/10 ││ Well-established in CA. CRA has not challenged ││ when properly executed. Market risk remains. ││ ││ ┌───────────────────────────────────┐ ││ │ IKIGAI SCORE: 7.0 / 10 │ ││ │ Sweet spot: Yes, with education │ ││ └───────────────────────────────────┘ │└─────────────────────────────────────────────────────┘
Strategy: RRSP for low-income saver (GIS-eligible in retirement)
┌─────────────────────────────────────────────────────┐│ ││ BENEFITS CLIENT ██░░░░░░░░░░░░ 2/10 ││ DESTROYS WEALTH. Saves 20%, pays 70%. ││ TFSA is strictly better. ││ ││ PROFITABLE (Industry) ████████░░░░░░ 6/10 ││ RRSP still generates AUM. ││ But smaller balances. ││ ││ SIMPLE ENOUGH ████████████░░ 9/10 ││ "Put money in RRSP" is the simplest advice. ││ Industry default. ││ ││ LOW BUSINESS RISK ██░░░░░░░░░░░░ 2/10 ││ HIGH RISK. Advisor recommending RRSPs to someone ││ facing 70% effective rate = potential negligence ││ claim if client discovers the truth. ││ ││ ┌───────────────────────────────────┐ ││ │ IKIGAI SCORE: 4.75 / 10 │ ││ │ Sweet spot: NO — harmful advice │ ││ └───────────────────────────────────┘ │└─────────────────────────────────────────────────────┘This scorecard is unique to ATIM — no other tool evaluates strategies on these four axes. It makes the output immediately actionable for advisors and dealers.
Sensitivity Analysis: Focus on What’s Knowable
Section titled “Sensitivity Analysis: Focus on What’s Knowable”Instead of predicting future tax rates, ATIM shows what happens when rates change:
RRSP vs TFSA Sensitivity — $10K/year, 30 years, 6% return
Withdrawal Rate RRSP After-Tax TFSA After-Tax Winner Marginrelative to 33% Terminal Value Terminal Valueaccumulation rate─────────────────────────────────────────────────────────────────────────-20pp (13%) $711K $560K RRSP +$151K-10pp (23%) $646K $560K RRSP +$86K Same (33%) $560K $560K TIE $0+10pp (43%) $477K $560K TFSA +$83K+20pp (53% w/OAS) $394K $560K TFSA +$166K+37pp (70% w/GIS) $252K $560K TFSA +$308K ←!!The insight is directional and massive: the GIS trap doesn’t move the needle by 5% — it destroys half the value. That’s what matters, not whether the bracket is 14.8% or 15.0%.
This is the “knowable, influenceable” analysis you described. We can’t know future rates. But we CAN show: “If you end up GIS-eligible, your RRSP cost you $308K. Is that a risk worth taking?”
Revised Phased Roadmap (80/20 Version)
Section titled “Revised Phased Roadmap (80/20 Version)”Phase 1: Core Proof of Concept
- Tax profiles: CA low/mid/high with accumulation + 3 withdrawal scenarios each
- Account types: RRSP, TFSA, Taxable (with ACB)
- Distribution types: interest, eligible dividend, capital gain, ROC
- Single-year after-tax return computation using profile rates
- Strategy comparison: RRSP vs TFSA vs Taxable for one profile
- Done when: Can show the GIS trap destroying RRSP value vs TFSA — the core After-Tax Reality insight
Phase 2: Multi-Year Simulation
- Multi-year accumulation + withdrawal simulation
- RRIF minimum withdrawals enforced
- Contribution room tracking (RRSP, TFSA)
- Sensitivity analysis: rate change impact on strategy outcomes
- Done when: Can produce the sensitivity table above for any profile over 30+ years
Phase 3: Leverage & Advanced Strategies
- Interest deductibility modeling
- Smith Manoeuvre simulation (mortgage → investment loan conversion)
- Debt repayment as alternative “investment”
- Ikigai scorecard for each strategy
- Done when: Can show after-tax reality of Smith Manoeuvre vs mortgage paydown over 25 years
Phase 4: US Market
- US tax profiles: low/mid/high with LTCG, NIIT awareness
- US accounts: Traditional IRA, 401(k), Roth IRA, taxable
- RMD enforcement
- Social Security taxation awareness in profiles
- Done when: Can compare Traditional-vs-Roth-vs-Taxable for US investor
Phase 5: Monte Carlo & Optimization
- Random return sequences (numpy)
- Sequence-of-returns risk in withdrawal phase
- Percentile outcomes (5th/25th/50th/75th/95th)
- Done when: Can show probability distribution of Smith Manoeuvre outcomes
Phase 6: Expand as Market Demands
- Household/spousal optimization
- Corporate ownership
- Cross-border
- More jurisdictions
- Only build what users/partners need
Summary
Section titled “Summary”- Answered GIS 70-95% effective tax question with worked example
- Recalibrated architecture: tax engine → strategy truth-teller using approximate profiles
- Revised package structure (half the files, fraction of the complexity)
- Introduced Ikigai scorecard concept with worked examples
- Showed sensitivity analysis approach (directional, not precise)
- Revised 6-phase roadmap aligned with 80/20 philosophy
Next Steps for Human
Section titled “Next Steps for Human”- Does the Tax Profile approach capture the right level of approximation?
- Ikigai scorecard axes — are these four the right ones? Weights equal or different?
- Which tax profiles to build first? (I’d suggest CA middle-income as the core use case)
- Ready to create a Phase 1 implementation task, or more brainstorming needed?
- Any strategies I’m missing that are core to SMART DEBT Coach mission?