{"id":31041704,"url":"https://github.com/rpdevjesco/ubisim","last_synced_at":"2025-09-14T10:39:15.945Z","repository":{"id":309031440,"uuid":"1034948929","full_name":"RPDevJesco/UbiSim","owner":"RPDevJesco","description":"UBI simulation as accurate as I can get it","archived":false,"fork":false,"pushed_at":"2025-08-09T10:46:29.000Z","size":189,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-08-09T12:19:49.139Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RPDevJesco.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-08-09T10:27:19.000Z","updated_at":"2025-08-09T10:46:32.000Z","dependencies_parsed_at":"2025-08-09T12:19:51.989Z","dependency_job_id":"b8036e8b-52f6-4f0b-9ef0-ffbcce58b59e","html_url":"https://github.com/RPDevJesco/UbiSim","commit_stats":null,"previous_names":["rpdevjesco/ubisim"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/RPDevJesco/UbiSim","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FUbiSim","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FUbiSim/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FUbiSim/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FUbiSim/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RPDevJesco","download_url":"https://codeload.github.com/RPDevJesco/UbiSim/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RPDevJesco%2FUbiSim/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":275094398,"owners_count":25404446,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-14T02:00:10.474Z","response_time":75,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-09-14T10:39:13.876Z","updated_at":"2025-09-14T10:39:15.924Z","avatar_url":"https://github.com/RPDevJesco.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"UbiSim — An Economically-Grounded UBI Simulator (C#)\n\nUbiSim is a **deterministic, reproducible** macro-micro simulation that explores the fiscal and real-economy impacts of a Universal Basic Income (UBI) program. It models **households, firms, labor markets, finance, trade, and regions**, calibrates **tax instruments** to a fiscal target, then runs multi-month scenarios and exports **rich CSV outputs**.\n\n---\n\n## Highlights\n\n* **End-to-end UBI scenarios**: No-UBI baseline and multiple calibrated UBI levels.\n* **Automatic tax calibration**: Searches corporate, PIT scale, and VAT to hit a net fiscal target with stability checks.\n* **Bounded, stable dynamics**: Tight clamps on inflation, interest rates, GDP, and migration to avoid blowups.\n* **Reproducible**: Seeded RNG + option to run deterministic (no stochastic sampling).\n* **CSV exports**: Monthly series per scenario + summary across scenarios for post-analysis.\n\n---\n\n## Quick Start\n\n### Prerequisites\n\n* .NET 8 SDK (or .NET 7; project uses modern C# features like `record`)\n* Windows, macOS, or Linux\n\n### Build \u0026 Run\n\n```bash\n# from the solution/project folder\ndotnet build -c Release\n\n# Run a single scenario for 24 months with UBI=$1,000, write monthly CSV\ndotnet run --project . -- --ubi 1000 --months 24 --csv out/monthly_ubi1000.csv --stochastic false --advanced true\n```\n\n\u003e Note the `--` separator before app args.\n\n### Typical Outputs\n\n* Console summary (first/last 6 months + totals)\n* `monthly.csv` (if `--csv` given): per-month indicators\n* `enhanced_out/enhanced_scenario_summary.csv` when running the built-in scenario suite\n\n---\n\n## How to Use\n\n### Single Scenario (custom UBI \u0026 target)\n\n```bash\ndotnet run -- --ubi 1200 --months 18 --target-net 0 \\\n  --csv out/ubi1200_monthly.csv --seed 42 --stochastic true --advanced true\n```\n\n### Scenario Suite (predefined set; writes to `enhanced_out/`)\n\n```bash\ndotnet run -- --months 12 --stochastic false --advanced true\n# If --ubi is omitted, the program runs the suite:\n#   Baseline_NoUBI, UBI_600_Balanced, UBI_1000_Balanced, UBI_1200_Balanced,\n#   UBI_1500_DeficitOK, UBI_800_Surplus\n```\n\n### Command-Line Options\n\n| Flag           | Type    | Default    | Description                                                                               |\n| -------------- | ------- | ---------- | ----------------------------------------------------------------------------------------- |\n| `--ubi`        | decimal | *(unset)*  | Monthly UBI per adult. If set → **single scenario**. If omitted → **scenario suite**.     |\n| `--months`     | int     | `12`       | Number of simulated months.                                                               |\n| `--target-net` | decimal | `0`        | Annualized net fiscal target (e.g., `-200000000000` for deficit tolerance).               |\n| `--stochastic` | bool    | `true`     | Enables stochastic sampling (binomial draws). Set `false` for deterministic expectations. |\n| `--csv`        | string  | *(unset)*  | Path to write monthly CSV for single scenario.                                            |\n| `--summary`    | string  | *(unused)* | Reserved for future extended summaries.                                                   |\n| `--seed`       | int     | `42`       | RNG seed for reproducibility.                                                             |\n| `--advanced`   | bool    | `true`     | Enables advanced behaviors (richer labor, firm, trade, finance, migration dynamics).      |\n\n*Examples (C# invocation snippet)*\n\n```csharp\n// Equivalent to: dotnet run -- --ubi 800 --months 24 --target-net 0 --stochastic false\nvar args = new[] { \"--ubi\", \"800\", \"--months\", \"24\", \"--target-net\", \"0\", \"--stochastic\", \"false\" };\nEnhancedUbiSim.EnhancedProgram.Main(args);\n```\n\n---\n\n## Conceptual Model\n\nThe simulator composes several realistic sub-models with conservative, bounded responses:\n\n* **Tax System**: Progressive PIT brackets (scalable), VAT, corporate tax, capital gains, property, wealth.\n* **Population Cohorts**: Income, savings, participation, education, mobility, spend propensities, tax avoidance.\n* **Business Ecosystem**: Small/Medium/Large firm buckets with counts, revenues, margins, investment behavior, productivity drift.\n* **Labor Market**: Baseline unemployment, mismatch, wage stickiness, union coverage; UBI-linked work incentives.\n* **Financial Sector**: Base interest rates, credit spreads/capacity, asset prices; Taylor-style policy rule.\n* **Trade**: Export/import elasticities vs. competitiveness (price level \u0026 FX), foreign demand growth.\n* **Regions**: 4 macro-regions with cost of living, productivity, unemployment differentials.\n* **Government**: Baseline spending, social programs, debt path, automatic stabilizers.\n* **Migration**: Emigration/immigration sensitive to tax pressure, UBI attraction, unemployment; network effects; re-entry.\n\n### Timeline per Month\n\n1. **Labor update** → unemployment, wage growth, labor supply (Phillips-style effects; UBI \u0026 tax influences).\n2. **Firms update** → revenues, profits, corporate tax, reinvestment, productivity drift.\n3. **Households** → disposable income, consumption (different MPCs for earned vs UBI), VAT, cap-gains, property, wealth taxes; UBI outlays.\n4. **Aggregation** → GDP (C+I+G+NX), output gap, price level/inflation (tight bounds), capacity.\n5. **Finance** → interest rate via Taylor rule, asset prices, credit growth.\n6. **Trade** → exports, imports, exchange rate adjustment.\n7. **Migration** → cohort populations, emigration/immigration counts.\n8. **Government** → total revenue/outlays, net, debt stock.\n\n**Stability Guardrails** (illustrative):\n\n* Price level clamped to `[0.8, 1.5]`; monthly inflation bounded roughly ±0.5%.\n* Nominal GDP bounded `[1T, 4T]` per month for realism and numeric safety.\n* Corporate profits, taxes, migration probabilities all bounded to avoid runaway paths.\n\n---\n\n## Tax Calibration\n\nWhen you specify a fiscal target (`--target-net`), the model:\n\n1. **Coarse grid + fine search** on **corporate tax rate**.\n2. If gap remains large, searches **PIT scale** with a **stability bias** toward 1.0.\n3. Optionally searches **VAT** within a configurable band.\n4. Stops on convergence (gap ≤ tolerance), stagnation, or iteration limits.\n5. Returns the calibrated `TaxPolicy` used for the scenario.\n\nConsole logs show **rounds**, **final gap**, and final **Corp/PIT/VAT**.\n\n---\n\n## Data Structures (C#)\n\nKey `record` types (partial list):\n\n```csharp\npublic record TaxPolicy(List\u003cTaxBracket\u003e Brackets, decimal VatRate, decimal CorpTaxRate,\n                        decimal CapitalGainsRate, decimal PropertyTaxRate, decimal WealthTaxRate);\n\npublic record PopulationCohort(string Name, decimal AvgAnnualIncome, decimal SavingsRate, int Adults,\n                               decimal WorkParticipationRate, decimal UbiSpendPropensity, decimal TaxAvoidanceFactor,\n                               decimal GeographicMobility, decimal AgeMedian, decimal EducationLevel, string RegionPrimary);\n\npublic class EnhancedMonthResult\n{\n    public int MonthIndex { get; set; }\n    public decimal PriceLevel { get; set; }\n    public decimal NominalGDP { get; set; }\n    public decimal RealGDP { get; set; }\n    public decimal UnemploymentRate { get; set; }\n    public decimal InterestRate { get; set; }\n    public decimal ExchangeRate { get; set; }\n    // … government, business, labor, trade, regional, finance fields …\n}\n```\n\n---\n\n## CSV Outputs\n\n### Monthly CSV (one row per month)\n\nColumns include (subset):\n\n* **Macro**: `Month, PriceLevel, NominalGDP, RealGDP, UnemploymentRate, InterestRate, ExchangeRate`\n* **Taxes**: `PersonalIncomeTax, VAT, CorpTax, CapitalGainsTax, PropertyTax, TotalTaxes`\n* **Government**: `UBIOutlays, OtherGovSpending, GovernmentDebt, Net`\n* **Population**: `Emigrants, Immigrants, RemainingTaxpayers, AvgETR`\n* **Firms**: `SmallFirms, MediumFirms, LargeFirms, TotalInvestment, CorporateProfit, TotalCapacity`\n* **Labor**: `AvgWage, LaborForceParticipation`\n* **Trade**: `Exports, Imports, TradeBalance`\n* **Finance/HH**: `TotalSavings, TotalConsumption, AssetPriceIndex, CreditGrowth`\n\n\u003e `Net = TotalTaxes - UBIOutlays - OtherGovSpending` (per month).\n\n### Scenario Summary CSV\n\n* Scenario name, months, UBI level, **NetFiscalPosition** (sum of monthly Nets), **PITScale/CorpRate/VATRate**, totals for **Taxes/UBI/Other**, cumulative **Emigrants/Immigrants**, **FinalTaxpayers**, average **Unemployment**, final **PriceLevel/InterestRate**, final **Firms**, average **TradeBalance**.\n\n---\n\n## Reproducibility\n\n* Set `--seed` and `--stochastic false` to remove randomness entirely (binomial expectations).\n* Or keep `--stochastic true` + a fixed seed for repeatable random draws.\n\n---\n\n## Extending the Simulator\n\n* **Add new taxes**: Extend `TaxPolicy`, compute within `CalculateIndividualResponses` and/or firm updates, add to `TotalTaxes`.\n* **Change firm buckets**: Update `BusinessEecosystem.FirmSizes` and per-category rules (margins, investment).\n* **Richer regions**: Expand `RegionalEconomy.Regions` and modify `UpdateRegionalEconomics`.\n* **Alternative policy levers**: E.g., means-testing via `UbiProgram` (`MeansTestingEnabled`, `PhaseOutThreshold`, `PhaseOutRate`).\n\n---\n\n## Design Choices \u0026 Limitations\n\n* **Not a forecasting tool**: It’s a **scenario sandbox** with plausible responses and guardrails.\n* **Clamps are intentional**: They prevent runaway arithmetic and keep scenarios analyzable.\n* **Stylized agents**: Cohorts and firms are grouped for tractability; micro heterogeneity is aggregated.\n\n---\n\n## Troubleshooting\n\n* **Weird numbers?** Make sure `--advanced true` if you want richer dynamics; check that your `--months` isn’t too small for convergence.\n* **No convergence in calibration**: The console will warn you. Consider loosening the target, increasing months, or allowing VAT to move.\n* **CSV looks huge**: That’s expected for longer runs; filter by columns of interest in your analysis notebook/tooling.\n\n---\n\n## Example Analysis (C# quick parse)\n\n```csharp\nusing System.Globalization;\nvar lines = System.IO.File.ReadAllLines(\"out/monthly_ubi1000.csv\").Skip(1);\nvar avgUnemp = lines.Select(l =\u003e decimal.Parse(l.Split(',')[4], CultureInfo.InvariantCulture)).Average();\nConsole.WriteLine($\"Average monthly unemployment: {avgUnemp:P2}\");\n```\n\n---\n\n## Project Layout\n\n* Single file/program for portability (namespace `EnhancedUbiSim`).\n* Entry point: `EnhancedProgram.Main(args)`\n* Major sections: **Data Structures**, **Results**, **Calibration**, **Simulation Engine**, **IO/CSV**, **CLI Parsing**.\n\n---\n\n## Contributing\n\nIssues and PRs welcome! Ideas:\n\n* Alternative **Phillips curve** or **Taylor rule** formulations.\n* More granular **industry** or **cohort** segmentation.\n* Deeper **migration** modeling (visa frictions, wage differentials, amenity shocks).\n* Visualization scripts (JS or C#) and notebooks for post-processing.\n\n---\n\n## FAQ\n\n**Q: Can I run without UBI to get a baseline?**\nYes—omit `--ubi` to run the scenario suite which includes `Baseline_NoUBI`.\n\n**Q: How “real” are the numbers?**\nThey’re **stylized and bounded**. Calibrations target internal consistency and comparative insights, not point predictions.\n\n**Q: Does means-testing work?**\nThe model supports it (`UbiProgram.MeansTestingEnabled`, `PhaseOutThreshold/Rate`), but the scenario runner keeps it off by default to isolate pure UBI effects.\n\n**Q: How do I hit a surplus/deficit?**\nUse `--target-net` with positive (surplus) or negative (deficit) annualized goals; calibration adjusts Corp/PIT/VAT within bounds.\n\n---\n\n\u003cimg width=\"3515\" height=\"315\" alt=\"image\" src=\"https://github.com/user-attachments/assets/33936ee7-7573-4515-863f-89545ac7a6de\" /\u003e\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frpdevjesco%2Fubisim","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frpdevjesco%2Fubisim","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frpdevjesco%2Fubisim/lists"}