[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77SHJPDBZX99JAE6VJ5B57A":3,"skill-same:01M77SHJPDBZX99JAE6VJ5B57A":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":36,"commitSha":37,"skillDirectory":38,"forksCount":39,"repositoryHtmlUrl":40,"repositoryHomepageUrl":41,"ownerHtmlUrl":42,"ownerBlogUrl":6,"ownerDescription":43,"updatedAt":44,"install":45,"resources":58},"01M77SHJPDBZX99JAE6VJ5B57A","Quant Simulation Toolkit",null,"7 runnable Monte Carlo simulation tools extracted from a viral quant article. Importance sampling, particle filters, copulas, agent-based markets, variance reduction.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fq\u002Fquant-sim-toolkit\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: \"Quant Simulation Toolkit\"\nslug: \"quant-sim-toolkit\"\nversion: \"1.0.0\"\ndescription: \"7 runnable Monte Carlo simulation tools extracted from a viral quant article. Importance sampling, particle filters, copulas, agent-based markets, variance reduction.\"\ntags: [\"quant\", \"monte-carlo\", \"simulation\", \"finance\", \"prediction-markets\", \"copula\", \"particle-filter\", \"importance-sampling\"]\nauthor: \"marcindudek\"\n---\n\n# Quant Simulation Toolkit\n\nSeven self-contained Python tools for quantitative simulation. Every technique here is drawn from the viral X thread by @gemchange_ltd, **\"How to Simulate Like a Quant Desk\"** (2.7M views). Each file runs standalone with `python3 \u003Cfile>.py` and prints a formatted demo.\n\nDependencies: `numpy`, `scipy`. No other packages needed.\n\n```\nbinary_pricer.py      MC binary option pricing vs Black-Scholes\ntail_risk.py          Importance sampling for rare crash events\nparticle_filter.py    Sequential Monte Carlo for real-time updating\nvariance_reduction.py Antithetic + control variate + stratified sampling\ncopula_sim.py         Gaussian, Student-t, Clayton correlated outcomes\nmarket_abm.py         Agent-based prediction market microstructure\npipeline.py           Full end-to-end pipeline connecting all six tools\n```\n\n---\n\n## Tool 1: binary_pricer.py\n\n**Question it answers:** What is the probability that an asset finishes above a strike price at expiry?\n\nPrices a binary (digital) contract using Monte Carlo simulation of Geometric Brownian Motion under the risk-neutral measure. Compares the result to the Black-Scholes closed-form N(d2) and reports a 95% confidence interval. Also computes the Brier score to evaluate calibration.\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `mc_binary_price(S0, K, sigma, T, r, n_paths, rng)` | MC estimate of P(S_T > K) with 95% CI |\n| `analytical_binary_price(S0, K, sigma, T, r)` | Black-Scholes N(d2) benchmark |\n| `brier_score(predicted_prob, actual_outcome)` | Calibration score, lower is better |\n\n**Run it**\n\n```bash\npython3 binary_pricer.py\n```\n\n**Example output**\n\n```\nContract parameters:\n  S0=100, K=105, sigma=0.25, T=0.5yr, r=0.05\n\nBlack-Scholes analytical price [N(d2)]: 0.400562\n\n    n_paths     MC Prob    CI Width       Error     Time(s)\n------------------------------------------------------------\n      1,000    0.402000    0.030367    0.001438      0.0001\n     10,000    0.401500    0.009590    0.000938      0.0003\n    100,000    0.400630    0.003039    0.000068      0.0018\n\nBrier score (MC[100k] vs analytical): 0.00000000\n  CI width shrinks as O(1\u002Fsqrt(n_paths))\n```\n\n**Use for:** Calibrating prediction market prices, comparing model probability to market-implied probability, Brier score tracking across forecasters.\n\n---\n\n## Tool 2: tail_risk.py\n\n**Question it answers:** How likely is a rare crash event, and can we estimate it without running billions of paths?\n\nCrude Monte Carlo is fundamentally broken for rare events. When P(crash) ~ 0.001, a run of 100,000 paths produces only ~100 hits -- high variance, unstable across runs. **Importance Sampling with exponential tilting** fixes this by shifting the sampling distribution toward the crash region, then correcting for the bias with likelihood ratios.\n\n```\nE_P[f(X)] = E_Q[ f(X) * (dP\u002FdQ)(X) ]\n```\n\nThe optimal tilting parameter `theta` is calculated analytically to center the tilted distribution exactly on the crash threshold, giving ~50% hit rate under the new measure.\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `crude_mc_crash(S0, K_crash, sigma, T, r, n_paths, rng)` | Naive MC estimate of P(S_T \u003C K_crash) |\n| `importance_sampling_crash(..., theta, ...)` | IS estimate with exponential tilting |\n| `optimal_theta(S0, K_crash, sigma, T, r)` | Compute the best tilting parameter |\n\n**Run it**\n\n```bash\npython3 tail_risk.py\n```\n\n**Example output**\n\n```\nScenario: Estimating P(50% crash in 1 year)\n  Asset: S0=$100, Crash at: K=$50 (50% drawdown), sigma=30%, T=1yr\n\nOptimal theta: 2.3702\n\nMethod                         P(crash)       Variance       Std Error\n------------------------------------------------------------------------\nCrude Monte Carlo              0.000840       8.4000e-09     9.1652e-05\nImportance Sampling            0.000837       1.1300e-13     3.3615e-07\n\nVariance Reduction Factor: 74360.2x\n  IS is ~74360x more efficient than crude MC\n  Equivalent to crude MC with 7,436,020,000 paths\n\nIS oversamples crash region by ~594x\n```\n\n**Use for:** Estimating drawdown probabilities, stress testing, pricing deep out-of-the-money puts, risk of ruin calculations.\n\n---\n\n## Tool 3: particle_filter.py\n\n**Question it answers:** As new binary observations arrive one at a time, what is our best real-time estimate of the hidden probability?\n\nImplements a **SIR (Sequential Importance Resampling) Particle Filter** for Bayesian tracking of a hidden probability. The classic application is election night: each county result is a noisy binary observation; the hidden state is the true win probability, which we want to track in real time.\n\nThe hidden state lives in logit space and evolves as a random walk. For each new observation:\n1. **Predict** -- add process noise to each particle\n2. **Reweight** -- update weights via Bernoulli log-likelihood\n3. **Estimate** -- compute weighted mean and 95% CI\n4. **Resample** -- if ESS \u003C N\u002F2, apply systematic resampling\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `run_particle_filter(observations, n_particles, process_noise, ...)` | Full SIR filter, returns filtered probs + CI + ESS |\n| `generate_observations(true_probs, rng)` | Simulate binary data from known truth |\n| `systematic_resample(weights, rng)` | Low-variance resampling step |\n| `logit(p)` and `expit(x)` | Log-odds transform and its inverse |\n\n**Run it**\n\n```bash\npython3 particle_filter.py\n```\n\n**Example output**\n\n```\nScenario: Simulating election night -- tracking hidden win probability\nas county results arrive one at a time.\n\nTrue probability trajectory: 0.500 -> 0.650\nTotal observations: 50 binary county results\n\n Step   Obs    True P    Filtered           95% CI     ESS\n------------------------------------------------------------------\n    1     0     0.500       0.476   (0.309, 0.660)   817.2\n    6     1     0.562       0.509   (0.364, 0.671)   720.1\n   11     1     0.561       0.562   (0.417, 0.693)   598.4\n   26     1     0.609       0.609   (0.484, 0.726)   512.7\n   50     1     0.650       0.641   (0.536, 0.740)   441.3\n\nMean Absolute Error vs true:   0.0289\nFinal filtered estimate:       0.6410\nFinal true probability:        0.6500\n```\n\n**Use for:** Real-time election tracking, live sports betting probability updates, any streaming binary data where the underlying probability is non-stationary.\n\n---\n\n## Tool 4: variance_reduction.py\n\n**Question it answers:** How do you price options accurately without needing 10 million paths?\n\nThree stackable variance reduction techniques for Monte Carlo option pricing. Each exploits a different structural property of the problem. Combined, they routinely achieve **100-500x variance reduction** -- this is table stakes in production quant desks.\n\n**Techniques**\n\n| Method | Mechanism | Typical VR |\n|---|---|---|\n| Antithetic variates | For every draw Z, also use -Z. Paired payoffs are negatively correlated. | 2-4x |\n| Control variates | Use S_T (known expectation under risk-neutral measure) to subtract correlated noise. | 5-20x |\n| Stratified sampling | Partition [0,1] into equal strata; draw one uniform per stratum. Guarantees full coverage. | 2-5x |\n| Combined (all three) | Stack stratified Z values, antithetic pairs, then control variate adjustment. | 100-500x |\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `crude_mc(S0, K, sigma, T, r, n_paths, rng)` | Baseline MC call price + variance |\n| `antithetic_mc(...)` | Antithetic variates pricing |\n| `control_variate_mc(...)` | Control variate adjusted pricing |\n| `stratified_mc(...)` | Stratified sampling pricing |\n| `combined_mc(...)` | All three stacked |\n| `bs_call_price(...)` | Black-Scholes analytical benchmark |\n\n**Run it**\n\n```bash\npython3 variance_reduction.py\n```\n\n**Example output**\n\n```\nOption parameters: S0=100, K=100, sigma=0.20, T=1yr, r=0.05\nPaths per method:  100,000\nBlack-Scholes analytical call price: 10.450584\n\nMethod                  Price     Variance     VR Factor   Error vs BS\n------------------------------------------------------------------------\nCrude MC             10.453142   1.14e-04          1.00x     0.002558\nAntithetic           10.451201   3.12e-05          3.65x     0.000617\nControl Variate      10.450891   6.83e-06         16.69x     0.000307\nStratified           10.450763   2.71e-05          4.21x     0.000179\nCombined             10.450591   3.97e-07        286.97x     0.000007\n```\n\n**Use for:** Pricing European options, any payoff function where variance reduction makes the difference between a usable and an unusable estimate.\n\n---\n\n## Tool 5: copula_sim.py\n\n**Question it answers:** If you hold a portfolio of correlated binary contracts, what is the true probability of a sweep win or a total loss?\n\n**The Gaussian copula is wrong.** It treats extreme co-movements as near-impossible. It contributed to the 2008 financial crisis because CDO pricing assumed Gaussian dependence and wildly underestimated joint default probabilities.\n\nThis tool simulates correlated binary outcomes under three copulas and shows the difference directly.\n\n**Copula comparison**\n\n| Copula | Lower tail (joint loss) | Upper tail (joint win) | Character |\n|---|---|---|---|\n| Gaussian | 0 | 0 | Dangerous default -- understates both extremes |\n| Student-t (df=3) | ~0.20 | ~0.20 | Symmetric: both tails elevated equally |\n| Clayton (theta=2) | 0.707 | 0 | Crash contagion: losses cluster, wins do not |\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `gaussian_copula_sim(corr_matrix, marginal_probs, n_sims, rng)` | Gaussian copula, no tail dependence |\n| `student_t_copula_sim(corr_matrix, df, marginal_probs, n_sims, rng)` | t-copula, symmetric tail dependence |\n| `clayton_copula_sim(theta, marginal_probs, n_sims, rng)` | Clayton copula, lower tail only |\n| `estimate_joint_probs(outcomes, labels)` | P(all win), P(all lose), P(>=k) for any d |\n\n**Run it**\n\n```bash\npython3 copula_sim.py\n```\n\n**Example output**\n\n```\nScenario: 5 correlated swing states, each with marginal P(win) = 0.55\n  Pairwise rho: 0.40   Clayton theta: 2.0   Student-t df: 3\n\nBaseline (independent, no copula):\n  P(sweep all 5) = 0.55^5 = 0.05033\n  P(lose all 5)  = 0.45^5 = 0.01845\n\nCopula         P(sweep)   P(0 wins)   P(>=4)   P(>=3)   AvgCorr\n-------------------------------------------------------------------\nIndependent     0.05033     0.01845      n\u002Fa      n\u002Fa       n\u002Fa\nGaussian        0.07421     0.02931   0.2081   0.4573    0.2401\nStudent-t       0.08103     0.03487   0.2194   0.4631    0.2408\nClayton         0.07289     0.04021   0.2065   0.4538    0.2399\n\nClayton gives HIGHEST P(all lose) due to asymmetric lower tail dependence.\nStudent-t raises BOTH tails symmetrically.\n```\n\n**Use for:** Portfolio construction on prediction markets, understanding blowup risk in correlated positions, stress testing a book of binary contracts.\n\n---\n\n## Tool 6: market_abm.py\n\n**Question it answers:** How does private information get incorporated into a prediction market price, and who profits?\n\nAn **Agent-Based Model (ABM)** of prediction market microstructure with three agent types. Price emerges from collective trading -- no closed-form SDE captures this.\n\n**Agent types**\n\n| Agent | Behavior | Expected PnL |\n|---|---|---|\n| Informed trader | Knows true probability. Trades toward it proportionally to edge. | Positive (systematic) |\n| Noise trader | Random orders. No information content. | Negative (donates to informed) |\n| Market maker | Quotes price, adjusts via Kyle lambda after each net flow. | Near zero |\n\n**Kyle lambda** is the price-impact coefficient: `new_price = old_price + lambda * net_order_flow`. Higher lambda means each order is more informative. The market maker estimates lambda empirically via OLS from realized price changes and flows.\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `simulate_market(true_prob, n_informed, n_noise, n_steps, kyle_lambda, rng)` | Full simulation, returns price trajectory + PnL breakdown |\n| `estimate_kyle_lambda(prices, net_flows)` | OLS recovery of price-impact coefficient |\n| `InformedTrader`, `NoiseTrader`, `MarketMaker` | Agent classes, usable independently |\n\n**Run it**\n\n```bash\npython3 market_abm.py\n```\n\n**Example output**\n\n```\nSimulation 1: Baseline\n  True probability : 0.70   Informed: 5   Noise: 20   Steps: 1000\n\n--- Price Trajectory ---\n  Step     Price   vs True\n     0    0.5000   -0.2000\n   100    0.5912   -0.1088\n   250    0.6378   -0.0622\n   500    0.6821   -0.0179\n  1000    0.6953   -0.0047\n\n--- PnL Breakdown ---\n  Informed traders  : +0.3521\n  Noise traders     : -0.3847\n  Market maker      : +0.0326\n  Total (sum ~= 0)  : +0.0000\n\nKyle lambda -- configured: 0.0500  estimated: 0.0498\n```\n\n**Use for:** Understanding information asymmetry, modeling speed of price discovery, sizing positions when you have information edge, studying market microstructure.\n\n---\n\n## Tool 7: pipeline.py\n\n**Question it answers:** What does the complete quant simulation workflow look like end to end?\n\nConnects all six tools into a single seven-stage pipeline. Runs them in sequence on a shared set of contract parameters and prints a summary table. Each stage degrades gracefully if a sibling module is missing.\n\n**Stages**\n\n| Stage | Tool | What it does |\n|---|---|---|\n| 1 | binary_pricer | MC probability estimation + Brier score vs N(d2) |\n| 2 | variance_reduction | Crude MC vs combined (stratified + antithetic + CV) |\n| 3 | tail_risk | Crude MC vs importance sampling for 30% crash |\n| 4 | copula_sim | Gaussian, Student-t, Clayton for 3-contract portfolio |\n| 5 | market_abm | 500-step ABM, price convergence + PnL attribution |\n| 6 | particle_filter | 30-step streaming filter, prob drifts 0.50 to 0.65 |\n| 7 | summary | Aggregated metrics table across all stages |\n\n**Run it**\n\n```bash\npython3 pipeline.py\n```\n\n**Example summary table output**\n\n```\n  Stage      Tool                     Primary Metric                         Secondary\n  ---------  ------------------------ --------------------------------------  ----------------------------\n  Stage 1    Probability Estimation   MC P(S>K) = 0.4002                    N(d2) = 0.4006\n  Stage 2    Variance Reduction       Combined price = 10.4507              VR factor = 286.9x\n  Stage 3    Tail Risk (IS)           IS P(crash) = 0.021403                VR factor = 41.3x\n  Stage 4    Dependency Modeling      P(all win): Gauss=0.1751              t=0.1893  Clayton=0.1688\n  Stage 5    Market Simulation        Final price=0.6421 (true=0.65)        Informed PnL=+0.2847\n  Stage 6    Real-Time Filtering      Filtered=0.6380  (true=0.6500)        MAE=0.0312\n\n  Pipeline complete. All 6 quantitative simulation tools executed.\n```\n\n---\n\n## Installation\n\nNo package manager required beyond a standard Python environment.\n\n```bash\ngit clone \u003Crepo>\ncd quant-sim-toolkit\npip install numpy scipy\n```\n\nAll tools run from the same directory. `pipeline.py` imports the six sibling modules directly.\n\n---\n\n## Quick reference\n\n```bash\n# Run individual tools\npython3 binary_pricer.py       # Binary contract pricing, convergence table\npython3 tail_risk.py           # Importance sampling vs crude MC\npython3 particle_filter.py     # Particle filter election night demo\npython3 variance_reduction.py  # 5-method comparison table\npython3 copula_sim.py          # 3 copulas x 5 states comparison\npython3 market_abm.py          # ABM price discovery + PnL attribution\n\n# Run the full pipeline\npython3 pipeline.py\n```\n\n---\n\n## Credit\n\nAll seven tools are implementations of techniques from the viral X thread by **@gemchange_ltd**: *\"How to Simulate Like a Quant Desk\"* (2.7M views). The code adds explicit docstrings, modular functions for reuse, and a pipeline connecting all techniques into a single workflow.\n","# Quant Simulation Toolkit\n\nSeven self-contained Python tools for quantitative simulation. Every technique here is drawn from the viral X thread by @gemchange_ltd, **\"How to Simulate Like a Quant Desk\"** (2.7M views). Each file runs standalone with `python3 \u003Cfile>.py` and prints a formatted demo.\n\nDependencies: `numpy`, `scipy`. No other packages needed.\n\n```\nbinary_pricer.py      MC binary option pricing vs Black-Scholes\ntail_risk.py          Importance sampling for rare crash events\nparticle_filter.py    Sequential Monte Carlo for real-time updating\nvariance_reduction.py Antithetic + control variate + stratified sampling\ncopula_sim.py         Gaussian, Student-t, Clayton correlated outcomes\nmarket_abm.py         Agent-based prediction market microstructure\npipeline.py           Full end-to-end pipeline connecting all six tools\n```\n\n---\n\n## Tool 1: binary_pricer.py\n\n**Question it answers:** What is the probability that an asset finishes above a strike price at expiry?\n\nPrices a binary (digital) contract using Monte Carlo simulation of Geometric Brownian Motion under the risk-neutral measure. Compares the result to the Black-Scholes closed-form N(d2) and reports a 95% confidence interval. Also computes the Brier score to evaluate calibration.\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `mc_binary_price(S0, K, sigma, T, r, n_paths, rng)` | MC estimate of P(S_T > K) with 95% CI |\n| `analytical_binary_price(S0, K, sigma, T, r)` | Black-Scholes N(d2) benchmark |\n| `brier_score(predicted_prob, actual_outcome)` | Calibration score, lower is better |\n\n**Run it**\n\n```bash\npython3 binary_pricer.py\n```\n\n**Example output**\n\n```\nContract parameters:\n  S0=100, K=105, sigma=0.25, T=0.5yr, r=0.05\n\nBlack-Scholes analytical price [N(d2)]: 0.400562\n\n    n_paths     MC Prob    CI Width       Error     Time(s)\n------------------------------------------------------------\n      1,000    0.402000    0.030367    0.001438      0.0001\n     10,000    0.401500    0.009590    0.000938      0.0003\n    100,000    0.400630    0.003039    0.000068      0.0018\n\nBrier score (MC[100k] vs analytical): 0.00000000\n  CI width shrinks as O(1\u002Fsqrt(n_paths))\n```\n\n**Use for:** Calibrating prediction market prices, comparing model probability to market-implied probability, Brier score tracking across forecasters.\n\n---\n\n## Tool 2: tail_risk.py\n\n**Question it answers:** How likely is a rare crash event, and can we estimate it without running billions of paths?\n\nCrude Monte Carlo is fundamentally broken for rare events. When P(crash) ~ 0.001, a run of 100,000 paths produces only ~100 hits -- high variance, unstable across runs. **Importance Sampling with exponential tilting** fixes this by shifting the sampling distribution toward the crash region, then correcting for the bias with likelihood ratios.\n\n```\nE_P[f(X)] = E_Q[ f(X) * (dP\u002FdQ)(X) ]\n```\n\nThe optimal tilting parameter `theta` is calculated analytically to center the tilted distribution exactly on the crash threshold, giving ~50% hit rate under the new measure.\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `crude_mc_crash(S0, K_crash, sigma, T, r, n_paths, rng)` | Naive MC estimate of P(S_T \u003C K_crash) |\n| `importance_sampling_crash(..., theta, ...)` | IS estimate with exponential tilting |\n| `optimal_theta(S0, K_crash, sigma, T, r)` | Compute the best tilting parameter |\n\n**Run it**\n\n```bash\npython3 tail_risk.py\n```\n\n**Example output**\n\n```\nScenario: Estimating P(50% crash in 1 year)\n  Asset: S0=$100, Crash at: K=$50 (50% drawdown), sigma=30%, T=1yr\n\nOptimal theta: 2.3702\n\nMethod                         P(crash)       Variance       Std Error\n------------------------------------------------------------------------\nCrude Monte Carlo              0.000840       8.4000e-09     9.1652e-05\nImportance Sampling            0.000837       1.1300e-13     3.3615e-07\n\nVariance Reduction Factor: 74360.2x\n  IS is ~74360x more efficient than crude MC\n  Equivalent to crude MC with 7,436,020,000 paths\n\nIS oversamples crash region by ~594x\n```\n\n**Use for:** Estimating drawdown probabilities, stress testing, pricing deep out-of-the-money puts, risk of ruin calculations.\n\n---\n\n## Tool 3: particle_filter.py\n\n**Question it answers:** As new binary observations arrive one at a time, what is our best real-time estimate of the hidden probability?\n\nImplements a **SIR (Sequential Importance Resampling) Particle Filter** for Bayesian tracking of a hidden probability. The classic application is election night: each county result is a noisy binary observation; the hidden state is the true win probability, which we want to track in real time.\n\nThe hidden state lives in logit space and evolves as a random walk. For each new observation:\n1. **Predict** -- add process noise to each particle\n2. **Reweight** -- update weights via Bernoulli log-likelihood\n3. **Estimate** -- compute weighted mean and 95% CI\n4. **Resample** -- if ESS \u003C N\u002F2, apply systematic resampling\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `run_particle_filter(observations, n_particles, process_noise, ...)` | Full SIR filter, returns filtered probs + CI + ESS |\n| `generate_observations(true_probs, rng)` | Simulate binary data from known truth |\n| `systematic_resample(weights, rng)` | Low-variance resampling step |\n| `logit(p)` and `expit(x)` | Log-odds transform and its inverse |\n\n**Run it**\n\n```bash\npython3 particle_filter.py\n```\n\n**Example output**\n\n```\nScenario: Simulating election night -- tracking hidden win probability\nas county results arrive one at a time.\n\nTrue probability trajectory: 0.500 -> 0.650\nTotal observations: 50 binary county results\n\n Step   Obs    True P    Filtered           95% CI     ESS\n------------------------------------------------------------------\n    1     0     0.500       0.476   (0.309, 0.660)   817.2\n    6     1     0.562       0.509   (0.364, 0.671)   720.1\n   11     1     0.561       0.562   (0.417, 0.693)   598.4\n   26     1     0.609       0.609   (0.484, 0.726)   512.7\n   50     1     0.650       0.641   (0.536, 0.740)   441.3\n\nMean Absolute Error vs true:   0.0289\nFinal filtered estimate:       0.6410\nFinal true probability:        0.6500\n```\n\n**Use for:** Real-time election tracking, live sports betting probability updates, any streaming binary data where the underlying probability is non-stationary.\n\n---\n\n## Tool 4: variance_reduction.py\n\n**Question it answers:** How do you price options accurately without needing 10 million paths?\n\nThree stackable variance reduction techniques for Monte Carlo option pricing. Each exploits a different structural property of the problem. Combined, they routinely achieve **100-500x variance reduction** -- this is table stakes in production quant desks.\n\n**Techniques**\n\n| Method | Mechanism | Typical VR |\n|---|---|---|\n| Antithetic variates | For every draw Z, also use -Z. Paired payoffs are negatively correlated. | 2-4x |\n| Control variates | Use S_T (known expectation under risk-neutral measure) to subtract correlated noise. | 5-20x |\n| Stratified sampling | Partition [0,1] into equal strata; draw one uniform per stratum. Guarantees full coverage. | 2-5x |\n| Combined (all three) | Stack stratified Z values, antithetic pairs, then control variate adjustment. | 100-500x |\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `crude_mc(S0, K, sigma, T, r, n_paths, rng)` | Baseline MC call price + variance |\n| `antithetic_mc(...)` | Antithetic variates pricing |\n| `control_variate_mc(...)` | Control variate adjusted pricing |\n| `stratified_mc(...)` | Stratified sampling pricing |\n| `combined_mc(...)` | All three stacked |\n| `bs_call_price(...)` | Black-Scholes analytical benchmark |\n\n**Run it**\n\n```bash\npython3 variance_reduction.py\n```\n\n**Example output**\n\n```\nOption parameters: S0=100, K=100, sigma=0.20, T=1yr, r=0.05\nPaths per method:  100,000\nBlack-Scholes analytical call price: 10.450584\n\nMethod                  Price     Variance     VR Factor   Error vs BS\n------------------------------------------------------------------------\nCrude MC             10.453142   1.14e-04          1.00x     0.002558\nAntithetic           10.451201   3.12e-05          3.65x     0.000617\nControl Variate      10.450891   6.83e-06         16.69x     0.000307\nStratified           10.450763   2.71e-05          4.21x     0.000179\nCombined             10.450591   3.97e-07        286.97x     0.000007\n```\n\n**Use for:** Pricing European options, any payoff function where variance reduction makes the difference between a usable and an unusable estimate.\n\n---\n\n## Tool 5: copula_sim.py\n\n**Question it answers:** If you hold a portfolio of correlated binary contracts, what is the true probability of a sweep win or a total loss?\n\n**The Gaussian copula is wrong.** It treats extreme co-movements as near-impossible. It contributed to the 2008 financial crisis because CDO pricing assumed Gaussian dependence and wildly underestimated joint default probabilities.\n\nThis tool simulates correlated binary outcomes under three copulas and shows the difference directly.\n\n**Copula comparison**\n\n| Copula | Lower tail (joint loss) | Upper tail (joint win) | Character |\n|---|---|---|---|\n| Gaussian | 0 | 0 | Dangerous default -- understates both extremes |\n| Student-t (df=3) | ~0.20 | ~0.20 | Symmetric: both tails elevated equally |\n| Clayton (theta=2) | 0.707 | 0 | Crash contagion: losses cluster, wins do not |\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `gaussian_copula_sim(corr_matrix, marginal_probs, n_sims, rng)` | Gaussian copula, no tail dependence |\n| `student_t_copula_sim(corr_matrix, df, marginal_probs, n_sims, rng)` | t-copula, symmetric tail dependence |\n| `clayton_copula_sim(theta, marginal_probs, n_sims, rng)` | Clayton copula, lower tail only |\n| `estimate_joint_probs(outcomes, labels)` | P(all win), P(all lose), P(>=k) for any d |\n\n**Run it**\n\n```bash\npython3 copula_sim.py\n```\n\n**Example output**\n\n```\nScenario: 5 correlated swing states, each with marginal P(win) = 0.55\n  Pairwise rho: 0.40   Clayton theta: 2.0   Student-t df: 3\n\nBaseline (independent, no copula):\n  P(sweep all 5) = 0.55^5 = 0.05033\n  P(lose all 5)  = 0.45^5 = 0.01845\n\nCopula         P(sweep)   P(0 wins)   P(>=4)   P(>=3)   AvgCorr\n-------------------------------------------------------------------\nIndependent     0.05033     0.01845      n\u002Fa      n\u002Fa       n\u002Fa\nGaussian        0.07421     0.02931   0.2081   0.4573    0.2401\nStudent-t       0.08103     0.03487   0.2194   0.4631    0.2408\nClayton         0.07289     0.04021   0.2065   0.4538    0.2399\n\nClayton gives HIGHEST P(all lose) due to asymmetric lower tail dependence.\nStudent-t raises BOTH tails symmetrically.\n```\n\n**Use for:** Portfolio construction on prediction markets, understanding blowup risk in correlated positions, stress testing a book of binary contracts.\n\n---\n\n## Tool 6: market_abm.py\n\n**Question it answers:** How does private information get incorporated into a prediction market price, and who profits?\n\nAn **Agent-Based Model (ABM)** of prediction market microstructure with three agent types. Price emerges from collective trading -- no closed-form SDE captures this.\n\n**Agent types**\n\n| Agent | Behavior | Expected PnL |\n|---|---|---|\n| Informed trader | Knows true probability. Trades toward it proportionally to edge. | Positive (systematic) |\n| Noise trader | Random orders. No information content. | Negative (donates to informed) |\n| Market maker | Quotes price, adjusts via Kyle lambda after each net flow. | Near zero |\n\n**Kyle lambda** is the price-impact coefficient: `new_price = old_price + lambda * net_order_flow`. Higher lambda means each order is more informative. The market maker estimates lambda empirically via OLS from realized price changes and flows.\n\n**Key functions**\n\n| Function | What it does |\n|---|---|\n| `simulate_market(true_prob, n_informed, n_noise, n_steps, kyle_lambda, rng)` | Full simulation, returns price trajectory + PnL breakdown |\n| `estimate_kyle_lambda(prices, net_flows)` | OLS recovery of price-impact coefficient |\n| `InformedTrader`, `NoiseTrader`, `MarketMaker` | Agent classes, usable independently |\n\n**Run it**\n\n```bash\npython3 market_abm.py\n```\n\n**Example output**\n\n```\nSimulation 1: Baseline\n  True probability : 0.70   Informed: 5   Noise: 20   Steps: 1000\n\n--- Price Trajectory ---\n  Step     Price   vs True\n     0    0.5000   -0.2000\n   100    0.5912   -0.1088\n   250    0.6378   -0.0622\n   500    0.6821   -0.0179\n  1000    0.6953   -0.0047\n\n--- PnL Breakdown ---\n  Informed traders  : +0.3521\n  Noise traders     : -0.3847\n  Market maker      : +0.0326\n  Total (sum ~= 0)  : +0.0000\n\nKyle lambda -- configured: 0.0500  estimated: 0.0498\n```\n\n**Use for:** Understanding information asymmetry, modeling speed of price discovery, sizing positions when you have information edge, studying market microstructure.\n\n---\n\n## Tool 7: pipeline.py\n\n**Question it answers:** What does the complete quant simulation workflow look like end to end?\n\nConnects all six tools into a single seven-stage pipeline. Runs them in sequence on a shared set of contract parameters and prints a summary table. Each stage degrades gracefully if a sibling module is missing.\n\n**Stages**\n\n| Stage | Tool | What it does |\n|---|---|---|\n| 1 | binary_pricer | MC probability estimation + Brier score vs N(d2) |\n| 2 | variance_reduction | Crude MC vs combined (stratified + antithetic + CV) |\n| 3 | tail_risk | Crude MC vs importance sampling for 30% crash |\n| 4 | copula_sim | Gaussian, Student-t, Clayton for 3-contract portfolio |\n| 5 | market_abm | 500-step ABM, price convergence + PnL attribution |\n| 6 | particle_filter | 30-step streaming filter, prob drifts 0.50 to 0.65 |\n| 7 | summary | Aggregated metrics table across all stages |\n\n**Run it**\n\n```bash\npython3 pipeline.py\n```\n\n**Example summary table output**\n\n```\n  Stage      Tool                     Primary Metric                         Secondary\n  ---------  ------------------------ --------------------------------------  ----------------------------\n  Stage 1    Probability Estimation   MC P(S>K) = 0.4002                    N(d2) = 0.4006\n  Stage 2    Variance Reduction       Combined price = 10.4507              VR factor = 286.9x\n  Stage 3    Tail Risk (IS)           IS P(crash) = 0.021403                VR factor = 41.3x\n  Stage 4    Dependency Modeling      P(all win): Gauss=0.1751              t=0.1893  Clayton=0.1688\n  Stage 5    Market Simulation        Final price=0.6421 (true=0.65)        Informed PnL=+0.2847\n  Stage 6    Real-Time Filtering      Filtered=0.6380  (true=0.6500)        MAE=0.0312\n\n  Pipeline complete. All 6 quantitative simulation tools executed.\n```\n\n---\n\n## Installation\n\nNo package manager required beyond a standard Python environment.\n\n```bash\ngit clone \u003Crepo>\ncd quant-sim-toolkit\npip install numpy scipy\n```\n\nAll tools run from the same directory. `pipeline.py` imports the six sibling modules directly.\n\n---\n\n## Quick reference\n\n```bash\n# Run individual tools\npython3 binary_pricer.py       # Binary contract pricing, convergence table\npython3 tail_risk.py           # Importance sampling vs crude MC\npython3 particle_filter.py     # Particle filter election night demo\npython3 variance_reduction.py  # 5-method comparison table\npython3 copula_sim.py          # 3 copulas x 5 states comparison\npython3 market_abm.py          # ABM price discovery + PnL attribution\n\n# Run the full pipeline\npython3 pipeline.py\n```\n\n---\n\n## Credit\n\nAll seven tools are implementations of techniques from the viral X thread by **@gemchange_ltd**: *\"How to Simulate Like a Quant Desk\"* (2.7M views). The code adds explicit docstrings, modular functions for reuse, and a pipeline connecting all techniques into a single workflow.\n",{"name":5,"slug":24,"tags":25,"author":34,"version":35,"description":7},"quant-sim-toolkit",[26,27,28,29,30,31,32,33],"quant","monte-carlo","simulation","finance","prediction-markets","copula","particle-filter","importance-sampling","marcindudek","1.0.0","master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fq\u002Fquant-sim-toolkit",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":46,"prompt":56,"zipAvailable":57},[47,50,53],{"tool":48,"command":49},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Quant Simulation Toolkit\"",{"tool":51,"command":52},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Quant Simulation Toolkit\"",{"tool":54,"command":55},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill \"Quant Simulation Toolkit\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fq\u002Fquant-sim-toolkit\u002FSKILL.md",true,[],[60,67,74,81,88,95],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]