Skip to content

The Data Scientist

Tornado interval plot of the most influential flagged assumption per fund and resulting investor score swing in the 30% institutional run

How to Simulate Tokenised RWA Funds & Redemption Gates in Python Without Breaking Stock-Flow Conservation (TokenLab Tutorial)

TOKENLAB_PYTHON_TUTORIAL // STOCK_FLOW_RWA_SIMULATION_ENGINE MODULE: TokenLab.simulationcomponents.productclasses // CONSERVATION_TOL: < 1e-6

How to Simulate Tokenised RWA Funds & Redemption Gates in Python Without Breaking Stock-Flow Conservation (TokenLab Tutorial)

A developer and quant guide to building stock-flow consistent simulations of tokenised real-world-asset funds in Python—covering FIFO redemption gates, multi-month asset settlement pipelines, looped DeFi cohorts, and Monte Carlo stress testing.

AUTHORS: Dr Stylianos Kampakis & Linas Stankevičius (TokenLab Quantitative Research · The Tesseract Academy) // CODEBASE: github.com/stelios12312312/TokenLab
CORE_ENGINE_CLASS
TokenisedProductEconomy
CONSERVATION_IDENTITY
|ΔNAV – Flows| < 10^-6
QUEUE_SETTLEMENT
FIFO + Lag λ Pipeline
MONTE_CARLO_HARNESS
9 Scenarios × 100 Paths

01 // Why Tokenised RWA Models Need Accrual-Basis Stock-Flow Conservation

When quantitative researchers model a tokenised fund in a standard Python script or spreadsheet, two accounting bugs almost always creep in:

  1. The Pipeline Disappearance Bug: When an investor redeems shares from a credit fund whose loans take \(\lambda = 3\) months to liquidate (such as ONyc or ACRED), the assets ordered for liquidation are neither invested in the active portfolio \(A_t\) nor available as spendable cash \(C_t\). If you don’t track receivables in transit \(R_t\) and escrowed queue shares \(E_t\), your NAV per share \(p_t\) jumps or drops artificially whenever a redemption is queued.
  2. The Distribution Comparability Bug: Some funds pay monthly yield in cash (reducing ending NAV), while others auto-compound or mint payment-in-kind (PIK) shares. Comparing ending AUM across funds mistakes a payout choice for asset performance.

In TokenLab (src/TokenLab/simulationcomponents/productclasses.py), TokenisedProductEconomy resolves both issues by enforcing a strict nine-step monthly accounting cycle and verifying the stock-flow conservation identity at every single step.

02 // Step-by-Step Python Implementation: Simulating a Gated or Looped RWA Fund

Below is a complete, runnable Python script using TokenLab that configures an on-chain RWA credit fund with three holder cohorts (Treasury, Institutional, and Kamino_Looped), a 1-to-3 month liquidation pipeline, a monthly redemption gate, and a Month-12 institutional or looping stress shock:

examples/simulate_rwa_fund_tokenlab.py PYTHON 3.11+ // TOKENLAB
from TokenLab.simulationcomponents.productclasses import (
    AssetPortfolioController,
    InvestorCohort,
    ProductScenarioProfile,
    RedemptionQueueManager,
    TokenisedProductEconomy,
)

# 1. Configure the Underlying Real-World Asset Portfolio & Liquidation Pipeline
portfolio = AssetPortfolioController(
    initial_aum=301_000_000.0,         # e.g., $301.0M AUM (ONyc reinsurance calibration)
    target_cash_buffer_ratio=0.10,     # 10% ready cash / T-bill liquidity buffer
    gross_annual_yield=0.1140,         # 11.40% gross annual portfolio yield
    annual_management_fee=0.0000,      # 0 bps fixed management fee (uses 15% gross income fee)
    annual_operating_cost=210_000.0,   # $210k fixed annual sponsor operating cost
    liquidation_delay_steps=3,         # lambda = 3 monthly steps to liquidate reinsurance assets
    liquidation_haircut=0.005,         # 50 bps forced-liquidation haircut on stressed sales
    distribution_ratio=1.0,            # 100% of net investment income distributed
    reinvest_ratio=1.0,                # Accumulating / auto-compounding share class
)

# 2. Configure the FIFO Primary Redemption Queue & Gate Policy
redemption_queue = RedemptionQueueManager(
    max_redemption_rate=1.00,          # 1.00 = un-gated (set 0.017 for ACRED 1.7%/mo gate, 0.05 for HLSCOPE)
    settlement_delay_steps=0,          # Additional administrative notice lag
    redemption_fee=0.000,              # Primary exit fee
    pricing_policy="payment_date_nav", # Shares remain in escrow E_t until cash payment
    liquidity_risk_spread=0.06,        # s_liq = 6.00%/yr for no-arbitrage immediate-exit discount d_t
    sla_max_wait_steps=3,              # 3-month SLA objective for reverse stress testing
)

# 3. Configure Holder Cohorts (Including On-Chain Kamino Looped Share s_loop = 56%)
cohorts = [
    InvestorCohort(
        name="Kamino_Looped_Traders",
        initial_share=0.56,            # 56% of ONyc AUM posted as Kamino collateral on 2026-10-28
        base_subscription_rate=0.010,
        base_redemption_rate=0.015,
        yield_sensitivity=0.50,
    ),
    InvestorCohort(
        name="Institutional_Allocators",
        initial_share=0.34,
        base_subscription_rate=0.010,
        base_redemption_rate=0.010,
        yield_sensitivity=0.30,
    ),
    InvestorCohort(
        name="DAO_Treasuries",
        initial_share=0.10,
        base_subscription_rate=0.005,
        base_redemption_rate=0.005,
        yield_sensitivity=0.15,
    ),
]

# 4. Define the Stress Scenario (e.g., Scenario 9: Kamino Looping Unwind in Months 12 & 13)
loop_unwind_scenario = ProductScenarioProfile(
    name="Scenario_09_Kamino_Looping_Unwind",
    steps_per_year=12,
    risk_free_rate_annual=0.0396,      # 3.96% US 3-month T-bill benchmark
    redemption_multiplier_schedule={
        12: 25.0,                      # Triggers 60% looped cohort unwind in Month 12
        13: 10.0,                      # Triggers 20% looped cohort unwind in Month 13
    },
)

# 5. Instantiate and Run the 36-Month Stock-Flow Simulation
economy = TokenisedProductEconomy(
    portfolio=portfolio,
    redemption_queue=redemption_queue,
    cohorts=cohorts,
    scenario=loop_unwind_scenario,
    initial_nav_per_share=1.00,
    name="ONyc_Loop_Unwind_Sim",
    seed=42,
)

summary = economy.run_simulation(steps=36)
assert summary["max_conservation_gap"] < 1e-6, "Stock-flow conservation violated!"
print(f"Investor Score: {summary['product_stability_score']:.1f} / 100")
print(f"Max Queue Wait: {summary['max_wait_time_steps']} months | Peak Exit Discount: {summary['max_secondary_discount']*100:.2f}%")
print(f"Max Stock-Flow Conservation Gap: ${summary['max_conservation_gap']:.2e}")

03 // Inspecting the Stock-Flow Reconciliation Ledger in Python

Every call to economy.step() appends a full telemetry row to economy.get_history_df() and verifies that the change in Net Asset Value equals the sum of all accrual and cash-flow components:

conservation_gap_t = |(NAV_t - NAV_{t-1}) - (I_t + Δ_t^val - Φ_t - L_t - D_t + S_t - X_t + W_t)| < 10^-6

Here is how our 17-fund benchmark uses TokenisedProductEconomy to generate the Monte Carlo score bands, one-at-a-time assumption sensitivity tornadoes, and reverse-stress breaking points published in our flagship technical study:

Monte Carlo P10-P90 investor score intervals and rank-1 probabilities across 17 funds
[FIG_01] Output of 100 Monte Carlo paths per scenario × 9 scenarios + 20,000 Dirichlet weight and scale perturbation draws generated by TokenLab.
One-at-a-time assumption sensitivity tornado plot in the 30% institutional run
[FIG_02] Automated one-at-a-time parameter sweep across every flagged assumption in calibration_provenance.csv during the 30% institutional run.
Reverse stress test smallest Month-12 institutional shock that breaches 3-month payment SLA
[FIG_03] Reverse-stress solver output: sweeping Month-12 institutional withdrawal shocks from 0% to 80% in 5% increments to locate the exact 3-month SLA breaking point (10% for ACRED, 35% for HLSCOPE).

04 // Key Takeaways for Python Quants & Tokenomics Engineers

  • Never Mix Investor Utility with Sponsor Revenue: In TokenisedProductEconomy, investor_score (weights 0.30, 0.30, 0.20, 0.20) is strictly decreasing in management and redemption fees, while sponsor_viability_score is reported separately.
  • Always Sweep Undisclosed Operational Lags: As Figure 2 demonstrates, varying liquidation_delay_steps from 0 to 2 months swings credit-fund scores by up to 28 points in a 30% run.
  • Use Reverse Stress Testing for Governance SLAs: Instead of arguing over whether a 30% run is “realistic,” solve for the smallest withdrawal shock \(s^*\) where max_wait_time_steps > 3.

05 // Technical FAQ: Simulating RWA Funds in Python with TokenLab

1. Why do spreadsheet APY models fail when simulating tokenised RWA funds?

Spreadsheets typically track headline yield and AUM as independent columns without enforcing accrual-basis double-entry accounting across asset liquidation pipelines, uninvested cash, accrued fees, payable distributions, and FIFO redemption queues. When a redemption gate binds or underlying assets take 1–3 months to liquidate, naive models silently leak value between queued redeemers and remaining shareholders.

2. How does TokenLab enforce stock-flow conservation at every simulation step?

In TokenLab’s TokenisedProductEconomy (src/TokenLab/simulationcomponents/productclasses.py), every monthly iteration reconciles NAV_t = NAV_{t-1} + I_t + Δ_t^val - Φ_t - L_t - D_t + S_t - X_t + W_t against the balance-sheet identity NAV_t = (A_t + C_t + R_t) - F_t - P_t - Q_t^fix. Across all 17 funds, 9 scenarios, and 100 Monte Carlo repetitions, the maximum absolute stock-flow discrepancy is verified to be strictly below 10^-6.

3. What is the difference between payment_date_nav and request_date_nav in RedemptionQueueManager?

Under payment_date_nav (used by all 17 funds in our empirical calibration), queued redemption requests remain denominated in escrowed shares E_t until cash is paid out, so queued holders share proportionally in asset revaluation or credit write-downs while waiting. Under request_date_nav, tendered shares are cancelled immediately on the request date and converted into a fixed dollar liability Q_t^fix, shifting subsequent asset losses onto remaining shareholders.

4. How are time-weighted return (TWR) and forced-exit return calculated in TokenLab?

Because cash distributions D_t leave the fund’s balance sheet when paid in cash (whereas reinvesting funds retain or mint shares), comparing ending NAV_H / NAV_0 understates cash-distributing funds. TokenLab chains per-share total return r_t = (p_t + d_t^cash + d_t^pik * p_t) / p_{t-1} - 1 over H steps to compute annualised TWR, and multiplies the wealth index at the peak queue step t* by (1 - d_{t*}) to compute the forced-exit return.

5. How can I run the full 17-fund RWA benchmark suite locally in Python?

Clone the open-source TokenLab repository, install the package in editable mode (pip install -e .), and execute the RWA universe runner or instantiate TokenisedProductEconomy directly with AssetPortfolioController, RedemptionQueueManager, and InvestorCohort objects as shown in the code walkthrough below.

Mathematical Advisory • The Tesseract Academy

Bespoke Mathematical Tokenomics Design & Simulation

cadCAD differential equations and token velocity modeling to design antifragile, sustainable cryptoeconomies.