Datasets:

Modalities:
Text
Formats:
text
Size:
< 1K
Libraries:
Datasets
License:
File size: 49,027 Bytes
51d901a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
# Environment Simulator Logic

This document defines the complete simulation framework for the CFO environment, including **backend state tracking**, **financial statement generation**, **fundraising success simulation**, and **stochastic evaluation design**. All modules share a common monthly time axis `t = 0, 1, 2, ..., T`, and the agent only observes information up to the current time `t`.

---

## Module A: Backend Tracking (Ledger)

### Purpose

Maintain a running ledger of the company's financial state at each month. The system tracks **two parallel views**:

1. **P&L Ledger** (accrual basis) — revenue and costs recognized when *earned/incurred*
2. **Cash Ledger** (cash basis) — actual money entering/leaving the bank account

The ledger is **append-only** and the agent can only read `[0, t]` — no future information is visible.

**Simulation boundaries** (from `config.json`):
- Start date: `company_config.initial_date` (e.g., 2005-01-01)
- Max duration: `environment_config.max_episode_months` (e.g., 300 months)
- The simulation runs from `t = 0` to at most `t = max_episode_months`, or until cash goes negative.

### A.1 Core State Variables

At each month `t`, the backend tracks:

**Business State:**

| Field | Description | Source / Logic |
|-------|-------------|----------------|
| `t` | Month index (0-based) | System clock |
| `date` | Calendar month-end date | `combined_economic_data_2015_2025.csv` |
| `active_users` | Monthly active borrowers | Simulated (see A.2) |
| `net_new_users` | New borrowers this month | `Users(t) − Users(t-1)` |
| `loan_portfolio_gross` | Total outstanding loans (gross) | Running balance (see A.6) |
| `allowance` | Allowance for credit losses | Running balance (see A.6) |
| `lending_rate` | Annual lending rate | `Tsy2Y(t)/100 + Baa_Yield(t)/100` |

**P&L (Accrual Basis):**

| Field | Description | Source / Logic |
|-------|-------------|----------------|
| `revenue` | Interest income accrued | `Loan_Portfolio_Gross × Lending_Rate / 12` |
| `credit_loss_provision` | Expected loan losses | `Revenue × (1 − Gross_Margin) × Provision_Share` |
| `cogs` | Cost of goods sold | `Revenue × (1 − Gross_Margin)` |
| `gross_profit` | Gross profit | `Revenue − COGS` |
| `opex` | Operating expenses | `Gross_Profit − EBITDA` |
| `ebitda` | EBITDA | `Revenue × EBITDA_Margin` |
| `interest_expense` | Interest on company's debt | Sum of `principal × rate / 12` per debt instrument |
| `net_income` | Bottom line | `EBITDA − Interest_Expense − Taxes` |

**Cash (Bank Account):**

| Field | Description | Source / Logic |
|-------|-------------|----------------|
| `cash_balance` | Actual bank balance | Previous + all cash inflows − all cash outflows |
| `cash_in_interest` | Borrower interest payments received | `Revenue(t-1) × Collection_Rate` (lagged) |
| `cash_in_principal` | Borrower principal repayments | `Loan_Portfolio_Gross(t-1) / Avg_Loan_Term × Collection_Rate` (lagged) |
| `cash_out_originations` | New loans funded | `max(0, Net_New_Users(t)) × Avg_Loan_Size` (immediate) |
| `cash_out_servicing` | Servicing cost payments | `Servicing_Costs(t-1)` (lagged) |
| `cash_out_opex` | Operating cost payments | `OpEx(t-1)` (lagged) |
| `cash_out_debt_interest` | Debt interest paid | Same month |
| `cash_out_debt_repayment` | Debt principal paid | Scheduled payment |
| `cash_in_fundraising` | Funds received from raises | Same month (if success) |

**Balance Sheet Running Balances:**

| Field | Description | Source / Logic |
|-------|-------------|----------------|
| `interest_receivable` | Accrued revenue awaiting collection | `Revenue(t)` — cleared next month |
| `principal_receivable` | Scheduled repayment awaiting cash | `Loan_Portfolio_Gross(t) / Avg_Loan_Term` |
| `accounts_payable` | Accrued costs awaiting payment | `OpEx(t) + Servicing_Costs(t)` — paid next month |
| `write_offs` | Bad loans removed from books | `Credit_Loss_Provision(t-4)` — non-cash |

**Ownership & Capital:**

| Field | Description | Source / Logic |
|-------|-------------|----------------|
| `total_debt` | Outstanding debt principal | Cumulative from fundraising events |
| `total_equity_raised` | Cumulative equity raised | Cumulative from fundraising events |
| `shares_outstanding` | Current total shares | Updated on equity raises |

### A.2 Revenue & User Simulation

Revenue and users evolve monthly based on indicators from `combined_economic_data_2015_2025.csv`.

> **Adjusted Columns Convention:** The simulation uses `adj_Monthly_User_Growth` (not the original `Monthly_User_Growth`) to drive user growth. The `adj_` columns contain amplified growth bumps at three checkpoint periods (months 23-36, 53-62, 106-117) that create cash liquidity traps for the lending company. Original columns are preserved in the CSV for reference. Similarly, fundraising probabilities use `adj_P_debt` and `adj_P_equity` from `fundraising_success_probabilities_2015_2025.csv`.

**Active Users (Borrowers):**

```
Users(t)     = Users(t-1) × (1 + adj_Monthly_User_Growth(t) / 100)
Net_New(t)   = Users(t) − Users(t-1)
```

**Loan Portfolio (Gross) — Running Balance:**

The gross loan portfolio is tracked as a running balance (see A.6 for full logic):

```
Loan_Portfolio_Gross(t) = Loan_Portfolio_Gross(t-1)
                        + New_Originations(t)
                        − Scheduled_Principal_Repayment(t)
                        − Write_Offs(t)
```

> `Avg_Loan_Size` = $10,000 (fixed, from `config.json → company_config.average_loan_size`)
> At t=0: `Loan_Portfolio_Gross(0) = initial_customers × Avg_Loan_Size`

**Revenue (Interest Income) — Accrual:**

The company earns interest on its gross loan portfolio. The lending rate = risk-free base rate + credit spread:

```
Lending_Rate(t) = Tsy2Y(t) / 100 + Baa_Yield(t) / 100
Revenue(t)      = Loan_Portfolio_Gross(t) × Lending_Rate(t) / 12
```

> `Tsy2Y(t)` = 2-Year Treasury yield from `combined_economic_data_2015_2025.csv`
> `Baa_Yield(t)` = ICE BofA Corporate Bond OAS (credit spread) from `combined_economic_data_2015_2025.csv`
> `loan_term_years` = 2 (from `config.json → company_config.loan_term_years`)
> Divide by 12 because rates are annual but revenue is monthly
>
> **Why Tsy2Y?** The base rate matches the loan duration — 2-year loans use the 2-Year Treasury yield as the risk-free benchmark.
>
> **Why Baa_Yield?** This is the market credit spread (OAS), not an absolute yield. It captures the risk premium the market demands for lending — widens during crises (e.g., 2.58% in Mar 2020), tightens in calm periods (e.g., 0.77% in Sep 2025). Both components are fully dynamic from the environment.

**Cost Breakdown — Accrual:**

```
COGS(t)                  = Revenue(t) × (1 − Gross_Margin(t) / 100)
  └─ Credit_Loss_Provision(t) = COGS(t) × Provision_Share
  └─ Servicing_Costs(t)       = COGS(t) × (1 − Provision_Share)
Gross_Profit(t)          = Revenue(t) − COGS(t)
EBITDA(t)                = Revenue(t) × EBITDA_Margin(t) / 100
OpEx(t)                  = Gross_Profit(t) − EBITDA(t)
```

> `Provision_Share` = 0.40 (from `config.json`) — 40% of COGS is credit loss provision (non-cash), 60% is servicing costs

### A.3 Accrual vs. Cash: Timing Lags

A lending company has significant timing differences between when items appear on the P&L and when cash actually moves. This section explains each lag.

#### Interest Revenue → Cash Collection (lag: **1 month**)

Interest income is *accrued* on the P&L in the month it's earned. But cash arrives when borrowers make their monthly payment, which involves processing time (ACH settlement, payment posting). Additionally, not all borrowers pay — some are delinquent or default.

```
Cash_In_Interest(t) = Revenue(t-1) × Collection_Rate
```

> `Collection_Rate` = 0.96 (96%, from `config.json`) — 4% of accrued interest is never collected
> At `t=0`, there is no prior month, so `Cash_In_Interest(0) = 0`

#### Principal Repayments → Cash In (lag: **1 month**)

When borrowers make monthly payments, part goes to interest (above) and part repays principal. Principal repayments are NOT revenue — they reduce the loan asset on the balance sheet. But they are real cash inflows.

```
Monthly_Principal_Rate = 1 / Avg_Loan_Term_Months
Cash_In_Principal(t)   = Loan_Portfolio_Gross(t-1) × Monthly_Principal_Rate × Collection_Rate
```

> `Avg_Loan_Term_Months` = 24 (from `config.json`) — 2-year loan term
> This is cash coming back from the existing portfolio each month

#### New Loan Originations → Cash Out (lag: **0 months, immediate**)

When new borrowers are onboarded, the company must fund their loans immediately from its bank account. This is the biggest cash drain for a growing lender — it is NOT an expense on the P&L (it becomes an asset), but it consumes cash.

```
Cash_Out_Originations(t) = max(0, Net_New_Users(t)) × Avg_Loan_Size
```

> If users decline (negative growth), no origination cash outflow occurs
> This creates the key tension: **fast growth = high P&L revenue but heavy cash burn**

#### Credit Loss Provision → Write-off (lag: **4 months**, non-cash)

Credit losses are *provisioned* on the P&L when loans are originated or risk is assessed. This is a **non-cash** accrual that increases the Allowance for Credit Losses (a contra-asset on the Balance Sheet).

When a borrower becomes 90-120+ days delinquent (roughly 4 months later), the loan is **written off**. A write-off is a **Balance Sheet reclassification only** — it does NOT cause cash to leave the bank:

```
Write_Off(t) = Credit_Loss_Provision(t-4)

Balance Sheet entry:
  Loan Portfolio (Gross)         ↓ by Write_Off amount
  Allowance for Credit Losses    ↓ by Write_Off amount
  Loan Portfolio (Net)           unchanged (gross and allowance both decrease)
```

> At early months (`t < 4`), no write-offs have matured yet, so `Write_Off = 0`
> The cash impact of defaults is already captured through `Collection_Rate < 100%`: borrowers who default stop making interest and principal payments, so `Cash_In_Interest` and `Cash_In_Principal` are reduced accordingly.

#### Operating Expenses → Cash Out (lag: **1 month**)

OpEx includes salaries, technology, marketing, rent, etc. Salaries are paid same-month, but vendor invoices are typically net-30. Blended across all OpEx:

```
Cash_Out_OpEx(t) = OpEx(t-1)
```

> At `t=0`, `Cash_Out_OpEx(0) = 0`

#### Servicing Costs → Cash Out (lag: **1 month**)

The non-provision portion of COGS (payment processing, customer support, loan servicing):

```
Cash_Out_Servicing(t) = Servicing_Costs(t-1)
```

> `servicing_lag_months` = 1 (from `config.json`)

#### Company Debt Interest → Cash Out (lag: **0 months, same month**)

Interest the company owes on its own debt (from fundraising) is accrued and paid in the same month.

```
Cash_Out_Debt_Interest(t) = Interest_Expense(t)
```

#### Company Debt Repayment → Cash Out (lag: **0 months, scheduled**)

Principal repayments on the company's debt follow the amortization schedule.

```
Cash_Out_Debt_Repayment(t) = scheduled amount per debt_instruments table
```

> Repayment type: `environment_config.debt_repayment_type` (default: `"amortizing"`)
> Default maturity: `environment_config.debt_maturity_months` (default: 36 months)

#### Fundraising Proceeds → Cash In (lag: **0 months, immediate**)

When a fundraising round succeeds, cash arrives immediately.

```
Cash_In_Fundraising(t) = Amount_Raised (if success, else 0)
```

#### Summary Table

| P&L Item (Accrual) | Cash Event | Lag | Rate/Adjustment |
|---------------------|------------|-----|-----------------|
| Revenue (interest accrued) | Borrower interest payments received | **t+1** | × Collection_Rate (96%) |
| *(not on P&L)* | Borrower principal repayments received | **t+1** | × Collection_Rate (96%) |
| *(not on P&L)* | New loan originations funded | **t+0** | immediate, full amount |
| Credit Loss Provision | Write-off (BS reclassification, **non-cash**) | **t+4** | Gross ↓, Allowance ↓, Net unchanged |
| Servicing Costs (COGS) | Servicing payments | **t+1** | accrued amount |
| OpEx | Vendor/salary payments | **t+1** | accrued amount |
| Interest Expense (debt) | Debt interest paid | **t+0** | same month |
| *(not on P&L)* | Debt principal repayment | **t+0** | per schedule |
| *(not on P&L)* | Fundraising proceeds | **t+0** | if success |

### A.4 Cash Balance Update

Each month, the **actual bank balance** is updated using **cash-basis** items only:

```
Cash(t) = Cash(t-1)

        + Cash_In_Interest(t)            Revenue(t-1) × Collection_Rate
        + Cash_In_Principal(t)           Loan_Portfolio_Gross(t-1) / Avg_Loan_Term × Collection_Rate
        + Cash_In_Fundraising(t)         if fundraising succeeds this month

        − Cash_Out_Originations(t)       Net_New_Users(t) × Avg_Loan_Size
        − Cash_Out_Servicing(t)          Servicing_Costs(t-1)
        − Cash_Out_OpEx(t)               OpEx(t-1)
        − Cash_Out_Debt_Interest(t)      Interest_Expense(t)
        − Cash_Out_Debt_Repayment(t)     per amortization schedule
```

> **Key insight:** A lending company can be **profitable on the P&L but cash-negative** if it grows quickly. New loan originations drain cash immediately, while interest income trickles in over months. This forces the CFO agent to balance growth ambition with liquidity management — and fundraise at the right time.

### A.5 Storage Schema

**P&L Ledger** (accrual basis, one row per month-end):

```
pnl_ledger (
    t                      INT PRIMARY KEY,
    date                   DATE,       -- month-end date (e.g., 2015-01-31)
    active_users           BIGINT,
    net_new_users            BIGINT,
    lending_rate             DECIMAL,

    -- P&L items (accrual)
    revenue                  DECIMAL,
    credit_loss_provision    DECIMAL,
    servicing_costs          DECIMAL,
    cogs                     DECIMAL,
    gross_profit             DECIMAL,
    opex                     DECIMAL,
    ebitda                   DECIMAL,
    interest_expense         DECIMAL,
    net_income               DECIMAL,

    -- Balance Sheet running balances
    loan_portfolio_gross     DECIMAL,    -- running balance (see A.6)
    allowance                DECIMAL,    -- running balance (see A.6)
    interest_receivable      DECIMAL,    -- Revenue(t), cleared at t+1
    principal_receivable     DECIMAL,    -- scheduled repayment, cleared at t+1
    accounts_payable         DECIMAL,    -- OpEx(t) + Servicing_Costs(t), cleared at t+1
    write_offs               DECIMAL     -- Credit_Loss_Provision(t-4), non-cash
)
```

**Cash Ledger** (cash basis, one row per month-end):

```
cash_ledger (
    t                        INT PRIMARY KEY,
    date                     DATE,       -- month-end date (e.g., 2015-01-31)
    cash_in_interest         DECIMAL,    -- Revenue(t-1) × Collection_Rate
    cash_in_principal        DECIMAL,    -- portfolio principal repayments
    cash_in_fundraising      DECIMAL,    -- 0 unless fundraising succeeds
    cash_out_originations    DECIMAL,    -- new loans funded
    cash_out_servicing       DECIMAL,    -- Servicing_Costs(t-1)
    cash_out_opex            DECIMAL,    -- OpEx(t-1)
    cash_out_debt_interest   DECIMAL,    -- same month
    cash_out_debt_repayment  DECIMAL,    -- per schedule
    net_cash_flow            DECIMAL,    -- sum of all above
    cash_balance             DECIMAL     -- running bank balance
)
```

**Auxiliary tables:**

```
debt_instruments (
    id                  INT PRIMARY KEY,
    issued_at           INT,       -- month t when issued
    principal           DECIMAL,
    rate                DECIMAL,   -- annual interest rate
    maturity_months     INT,
    remaining_principal DECIMAL
)

equity_rounds (
    id              INT PRIMARY KEY,
    issued_at       INT,       -- month t when issued
    amount_raised   DECIMAL,
    shares_issued   BIGINT,
    price_per_share DECIMAL,
    investor_label  TEXT
)

capital_summary (
    t                    INT PRIMARY KEY,
    total_debt           DECIMAL,
    total_equity_raised  DECIMAL,
    shares_outstanding   BIGINT
)
```

### A.6 Loan Portfolio & Allowance Tracking

The loan portfolio and allowance are tracked as **running balances** to ensure the Balance Sheet always balances.

**Loan Portfolio (Gross):**

```
Loan_Portfolio_Gross(t) = Loan_Portfolio_Gross(t-1)
                        + New_Originations(t)
                        − Scheduled_Principal_Repayment(t)
                        − Write_Offs(t)
```

Where:
- `New_Originations(t)` = `max(0, Net_New_Users(t)) × Avg_Loan_Size`
- `Scheduled_Principal_Repayment(t)` = `Loan_Portfolio_Gross(t-1) / Avg_Loan_Term_Months`
- `Write_Offs(t)` = `Credit_Loss_Provision(t - 4)` (bad loans removed from books after ~4 months delinquent)

**Allowance for Credit Losses:**

```
Allowance(t) = Allowance(t-1)
             + Credit_Loss_Provision(t)       provision added (from P&L)
             − Write_Offs(t)                  used up when loan is written off
```

> When a write-off occurs, **both** Gross and Allowance decrease by the same amount, so **Net is unchanged**. This is a reclassification, not a new loss — the loss was already recognized when the provision was booked.

**Interest Receivable:**

```
Interest_Receivable(t) = Revenue(t)
```

> Accrued this month, collected next month. Cleared when Cash_In_Interest arrives at t+1.
> Uncollected portion (1 − Collection_Rate) is absorbed by the Allowance.

**Principal Receivable:**

```
Principal_Receivable(t) = Scheduled_Principal_Repayment(t)
```

> Scheduled this month, cash arrives next month. Uncollected portion absorbed by Allowance.

**Accounts Payable:**

```
Accounts_Payable(t) = OpEx(t) + Servicing_Costs(t)
```

> Accrued this month, paid next month (1-month lag).

### A.7 Initial Balance Sheet (t = 0)

At simulation start, the company begins with a pre-existing state. All values must satisfy `A = L + E`:

```
Assets:
  Cash                    = initial_cash                           (from config.json)
  Interest Receivable     = 0                                      (no prior accrual)
  Principal Receivable    = 0                                      (no prior schedule)
  Loan Portfolio (Gross)  = initial_customers × Avg_Loan_Size
  Allowance               = 0                                      (no provisions yet)
  Loan Portfolio (Net)    = Loan Portfolio (Gross)
  ────────────────────────────────
  Total Assets            = initial_cash + initial_customers × Avg_Loan_Size

Liabilities:
  Total Debt              = initial_debt                           (from config.json, default 0)
  Accounts Payable        = 0                                      (no prior accrual)
  ────────────────────────────────
  Total Liabilities       = initial_debt

Equity:
  Paid-in Capital         = Total Assets − Total Liabilities       (founders funded everything)
  Retained Earnings       = 0                                      (no prior income)
  ────────────────────────────────
  Total Equity            = Paid-in Capital

Cap Table:
  Shares Outstanding      = initial_shares_outstanding             (from config.json, default 10,500,000)
  Implied Share Price     = initial_share_price                    (from config.json, default $10.0)

Balance check: A = L + E ✓
```

> With `initial_cash = $15M` and `initial_customers = 5,000 × $10K = $50M`, Total Assets = $65M, Paid-in Capital = $65M.
> `initial_shares_outstanding = 10,000,000` — matches pre-ESOP Cap Table (Founders 8M + Seed 2M). Implied share price $6.50 × 10M = $65M = Paid-in Capital.

### A.8 Balance Sheet Reconciliation

Every monthly event must maintain `A = L + E`. Here is how each event type preserves the equation:

**1. New loan origination** (Cash → Loan Portfolio):
```
Cash ↓ $X    |  Loan Portfolio (Gross) ↑ $X
Assets net: unchanged  |  L+E: unchanged  ✓
```

**2. Interest revenue accrual** (P&L → Balance Sheet):
```
Interest Receivable ↑ $Y         (Asset ↑)
Revenue → Net Income → RE ↑ $Y  (Equity ↑)
A ↑ = E ↑  ✓
```

**3. Interest cash collection at t+1** (Receivable → Cash):
```
Cash ↑ $Y × 96%                   (Asset ↑)
Interest Receivable ↓ $Y          (Asset ↓)
Uncollected $Y × 4%:
  Allowance ↓ $Y × 4%             (contra-asset ↓ = Asset ↑)
  ... net: absorbed by existing allowance
A net: unchanged  |  L+E: unchanged  ✓
```

**4. Credit loss provision** (P&L → Allowance):
```
Allowance ↑ $Z                    (contra-asset ↑ = Net Assets ↓)
COGS → Net Income → RE ↓ $Z      (Equity ↓)
A ↓ = E ↓  ✓
```

**5. Loan write-off** (BS reclassification, non-cash):
```
Loan Portfolio (Gross) ↓ $W       (Asset ↓)
Allowance ↓ $W                    (contra-asset ↓ = Asset ↑)
Loan Portfolio (Net): unchanged    (↓ and ↑ cancel)
A: unchanged  |  L+E: unchanged  ✓
```

**6. OpEx / Servicing accrual** (P&L → AP):
```
Accounts Payable ↑ $V             (Liability ↑)
OpEx → Net Income → RE ↓ $V      (Equity ↓)
L ↑ by $V, E ↓ by $V → L+E: unchanged  |  A: unchanged  ✓
```

**7. OpEx / Servicing cash payment at t+1**:
```
Cash ↓ $V                         (Asset ↓)
Accounts Payable ↓ $V             (Liability ↓)
A ↓ = L ↓  ✓
```

**8. Principal repayment scheduled** (Loan → Receivable):
```
Loan Portfolio (Gross) ↓ $P       (Asset ↓)
Principal Receivable ↑ $P         (Asset ↑)
A: unchanged  |  L+E: unchanged  ✓
```

**9. Principal cash collection at t+1**:
```
Cash ↑ $P × 96%                   (Asset ↑)
Principal Receivable ↓ $P         (Asset ↓)
Uncollected $P × 4%:
  Allowance ↓ $P × 4%             (absorbed by existing allowance)
A net: unchanged  |  L+E: unchanged  ✓
```

**10. Fundraising (equity):**
```
Cash ↑ $F                         (Asset ↑)
Paid-in Capital ↑ $F              (Equity ↑)
A ↑ = E ↑  ✓
```

**11. Fundraising (debt):**
```
Cash ↑ $F                         (Asset ↑)
Total Debt ↑ $F                   (Liability ↑)
A ↑ = L ↑  ✓
```

**12. Debt interest payment** (same month, accrual = cash):
```
Cash ↓ $I                         (Asset ↓)
Interest Expense → RE ↓ $I       (Equity ↓)
A ↓ = E ↓  ✓
```

**13. Debt principal repayment:**
```
Cash ↓ $D                         (Asset ↓)
Total Debt ↓ $D                   (Liability ↓)
A ↓ = L ↓  ✓
```

### A.9 Visibility Rule

At time `t`, the agent can query:
- `pnl_ledger WHERE t <= current_t`
- `cash_ledger WHERE t <= current_t`
- `capital_summary WHERE t <= current_t`
- `debt_instruments WHERE issued_at <= current_t`
- `equity_rounds WHERE issued_at <= current_t`

No future rows are ever exposed.

---

## Module B: Financial Statement Simulation

### Purpose

Generate the three core financial statements (**Income Statement**, **Balance Sheet**, **Cash Flow Statement**) on demand, triggered by specific agent actions.

### B.1 Triggers

There are two actions that trigger financial statement generation:

| Action | Triggers | Output |
|--------|----------|--------|
| `book_closing` | End-of-period close | 3 financial statements (IS, BS, CF) |
| `fund_raising_request` | Fundraising attempt | 3 financial statements + updated Cap Table |

### B.2 Action: `book_closing`

**When:** Agent decides to close the books at current month `t`.

**Reporting period:** Always **Year-to-Date (YTD)** — from January of the current year through the current month. For example, if `t` falls in August 2017, the reporting period is Jan 2017 – Aug 2017.

```
ytd_start = January of the year that date(t) falls in
ytd_end   = date(t)
```

**Process:**

```
1. Determine YTD period:
   ytd_start = first month of the current calendar year
   ytd_end   = current month t

2. Freeze both ledgers at month t

3. Generate:
   a. Income Statement   (YTD: ytd_start to t)
   b. Balance Sheet       (snapshot: as of t)
   c. Cash Flow Statement (YTD: ytd_start to t)

4. Store statements as a versioned snapshot

5. Return statements to the agent
```

**Income Statement** (YTD: `[ytd_start, t]`):

| Line Item | Source |
|-----------|--------|
| Revenue | `SUM(pnl_ledger.revenue)` from ytd_start to t |
| Cost of Goods Sold | `SUM(pnl_ledger.cogs)` from ytd_start to t |
| Gross Profit | Revenue − COGS |
| Operating Expenses | `SUM(pnl_ledger.opex)` from ytd_start to t |
| EBITDA | Gross Profit − OpEx |
| Interest Expense | `SUM(pnl_ledger.interest_expense)` from ytd_start to t |
| Pre-tax Income | EBITDA − Interest Expense |
| Tax (simplified %) | Pre-tax Income × tax_rate |
| Net Income | Pre-tax Income − Tax |

> Example: book_closing in March 2018 → Income Statement covers Jan–Mar 2018
> Example: book_closing in December 2018 → full-year Income Statement for 2018

**Balance Sheet** (snapshot at `t`):

| Line Item | Source |
|-----------|--------|
| **Assets** | |
| Cash & Equivalents | `cash_ledger.cash_balance` at t |
| Interest Receivable | `Revenue(t)` — accrued this month, cash arrives at t+1 |
| Principal Receivable | `Loan_Portfolio_Gross(t) / Avg_Loan_Term` — scheduled repayment, cash arrives at t+1 |
| Loan Portfolio (Gross) | Running balance (see A.6) |
| Less: Allowance for Credit Losses | Running balance (see A.6) |
| Loan Portfolio (Net) | Gross − Allowance |
| **Total Assets** | Sum of above |
| **Liabilities** | |
| Total Debt | `SUM(debt_instruments.remaining_principal)` at t |
| Accounts Payable | `OpEx(t) + Servicing_Costs(t)` — accrued this month, paid at t+1 |
| **Total Liabilities** | Sum of above |
| **Equity** | |
| Paid-in Capital | Initial capital + `SUM(equity_rounds.amount_raised)` |
| Retained Earnings | Cumulative `SUM(pnl_ledger.net_income)` from t=0 to t |
| **Total Equity** | Paid-in Capital + Retained Earnings |

> Balance Sheet is always a point-in-time snapshot — not affected by the YTD period.
> Balance check: Total Assets = Total Liabilities + Total Equity
>
> **Why Interest Receivable?** Revenue is accrued in month t (P&L), but cash arrives in t+1. Without this asset, the balance sheet would have equity (via retained earnings) increasing without a matching asset increase. Interest Receivable bridges the 1-month gap.
>
> **Why Principal Receivable?** Same logic — principal repayments are scheduled at t but cash arrives at t+1. This is the portion of the loan portfolio that is "due this month" and waiting for payment processing.

**Cash Flow Statement** (YTD: `[ytd_start, t]`, built from `cash_ledger`):

| Section | Line Items | Source |
|---------|-----------|--------|
| **Operating Activities** | | |
| Interest received from borrowers | `SUM(cash_in_interest)` ytd_start to t | cash_ledger |
| Servicing & OpEx paid | `−SUM(cash_out_servicing + cash_out_opex)` ytd_start to t | cash_ledger |
| *Net Cash from Operations* | *Sum of above* | |
| **Investing Activities** | | |
| New loans originated | `−SUM(cash_out_originations)` ytd_start to t | cash_ledger |
| Principal repayments received | `+SUM(cash_in_principal)` ytd_start to t | cash_ledger |
| *Net Cash from Investing* | *Sum of above* | |
| **Financing Activities** | | |
| Debt raised | `+SUM(cash_in_fundraising)` where type=debt, ytd_start to t | cash_ledger |
| Equity raised | `+SUM(cash_in_fundraising)` where type=equity, ytd_start to t | cash_ledger |
| Debt interest paid | `−SUM(cash_out_debt_interest)` ytd_start to t | cash_ledger |
| Debt principal repaid | `−SUM(cash_out_debt_repayment)` ytd_start to t | cash_ledger |
| *Net Cash from Financing* | *Sum of above* | |
| **Net Change in Cash** | Operating + Investing + Financing | |
| **Beginning Cash** | `cash_ledger.cash_balance` at ytd_start − 1 (prior year-end) | |
| **Ending Cash** | Beginning + Net Change | |

> **Cross-check with Balance Sheet:** Ending Cash on the CF Statement MUST equal Cash & Equivalents on the Balance Sheet. Both are sourced from `cash_ledger.cash_balance` at t.
>
> **Cross-check with Income Statement:** Net Income (IS) + non-cash items (provision) − working capital changes (ΔReceivables, ΔPayables) ≈ Net Cash from Operations (CF). This is the indirect method relationship and can be verified as a sanity check.

### B.3 Action: `fund_raising_request`

**When:** Agent requests debt or equity fundraising.

**Input parameters from agent:**

| Parameter | Description |
|-----------|-------------|
| `type` | `"debt"` or `"equity"` |
| `amount` | Requested amount |
| `terms` | Rate / valuation / maturity (depending on type) |

**Process:**

```
1. Generate YTD financial statements (same as book_closing, steps 1-5)
   → These represent the company's state "as presented to investors"

2. Determine fundraising success:
   a. Look up P_debt or P_equity for current month t
      (from Module C: Fundraising Success Simulation)
   b. Draw random number r ~ Uniform(0, 1)
   c. success = (r < P_success)

3. If SUCCESS:
   a. For DEBT:
      - Insert into debt_instruments (principal, rate, maturity)
      - Update ledger.total_debt
      - Update ledger.cash_balance += amount_raised
   b. For EQUITY:
      - Calculate new shares: shares_new = amount / price_per_share
      - Insert into equity_rounds
      - Update shares_outstanding += shares_new
      - Update cap_table (recalculate all ownership %)
      - Update ledger.total_equity_raised
      - Update ledger.cash_balance += amount_raised

4. If FAILURE:
   - No changes to ledger, debt_instruments, or equity_rounds
   - Return failure notice to agent
   - Agent may retry in a future month

5. Return:
   - Financial statements (always)
   - Fundraising result (success/failure)
   - Updated cap table (if equity success)
```

### B.4 Cap Table Update Logic (Equity Only)

On a successful equity raise:

```
new_shares = amount_raised / price_per_share
total_shares_after = shares_outstanding + new_shares

For each existing shareholder:
    new_ownership% = their_shares / total_shares_after

New investor:
    ownership% = new_shares / total_shares_after
```

**Example:**

| Before | Shares | % | | After ($2M at $20M val) | Shares | % |
|--------|--------|---|-|------------------------|--------|---|
| Founders | 8,000,000 | 76% | | Founders | 8,000,000 | 72.7% |
| Seed | 2,000,000 | 19% | | Seed | 2,000,000 | 18.2% |
| ESOP | 500,000 | 5% | | ESOP | 500,000 | 4.5% |
| | | | | Series A | 500,000 | 4.5% |
| **Total** | **10,500,000** | **100%** | | **Total** | **11,000,000** | **100%** |

### B.5 Statement Versioning

Each generation is stored with metadata:

```
financial_snapshots (
    snapshot_id      INT PRIMARY KEY,
    trigger          TEXT,         -- 'book_closing' or 'fund_raising_request'
    t                INT,          -- month index when generated
    date             DATE,         -- month-end date (e.g., 2018-03-31)
    ytd_start_date   DATE,         -- YTD period start (e.g., 2018-01-31)
    fiscal_year      INT,          -- e.g., 2018
    months_in_period INT,          -- e.g., 3 for Jan-Mar
    income_stmt      JSON/BLOB,    -- YTD: ytd_start to t
    balance_sheet    JSON/BLOB,    -- Point-in-time snapshot at t
    cashflow_stmt    JSON/BLOB,    -- YTD: ytd_start to t
    cap_table        JSON/BLOB,    -- NULL for book_closing
    balance_check    BOOLEAN       -- Total Assets = Total Liabilities + Total Equity
)
```

> Example: book_closing called in March 2018 →
> `date = 2018-03-31`, `ytd_start_date = 2018-01-31`, `fiscal_year = 2018`, `months_in_period = 3`

---

## Module C: Fundraising Success Simulation

Fundraising probability is determined by two layers:

1. **Macro layer** — base probability from CSV, driven by market conditions (VIX, interest rates)
2. **Company-state layer** — modifiers that reduce probability based on the company's own financial state

```
P_adjusted = P_base_csv × company_modifier
```

### C.1 Macro Layer: Base Probabilities

#### Debt
- Key driver: **SOFR / Fed Funds** (lower rate → higher success probability)
- Use SOFR when available (Apr 2018+), fallback to FEDFUNDS

```
P_debt_base = 1 − (Rate − Rate_min) / (Rate_max − Rate_min)
```

#### Equity
- Key driver: **VIX** (lower VIX → higher success probability)

```
P_equity_base = 1 − (VIX − VIX_min) / (VIX_max − VIX_min)
```

### C.2 Company-State Layer: Difficulty Progression

#### Equity: Round-Count Decay

Each completed equity round makes the next one harder (models "Series A is easier than Series D"):

```
equity_modifier = equity_round_decay ^ num_completed_equity_rounds
P_equity = P_equity_base × equity_modifier
```

With `equity_round_decay = 0.75` (configurable in `environment_config`):

| Completed Rounds | Modifier | Effect |
|------------------|----------|--------|
| 0 (first raise)  | 1.00x    | No penalty |
| 1                | 0.75x    | |
| 2                | 0.56x    | |
| 3                | 0.42x    | |
| 4                | 0.32x    | |
| 5                | 0.24x    | |
| 6+               | ~0.18x   | Nearly impossible |

#### Debt: Leverage Penalty on Probability

High leverage ratio (total_debt / total_equity) reduces debt approval odds. Below a safe threshold, no penalty applies; above it, the modifier declines linearly to zero:

```
leverage_ratio = total_debt / (paid_in_capital + retained_earnings)

if leverage_ratio <= debt_safe_leverage:
    debt_modifier = 1.0
else:
    excess = leverage_ratio - debt_safe_leverage
    debt_modifier = max(0, 1 - debt_leverage_prob_decay × excess)

P_debt = P_debt_base × debt_modifier
```

With `debt_safe_leverage = 0.5` and `debt_leverage_prob_decay = 1.5`:

| Leverage | Modifier | Effect |
|----------|----------|--------|
| 0.0–0.5  | 1.00x    | Safe zone, no penalty |
| 0.7      | 0.70x    | |
| 1.0      | 0.25x    | |
| 1.17+    | 0.00     | Impossible |

#### Debt: Leverage Spread on Cost

Higher leverage increases the interest rate the company pays, on top of the market rate:

```
base_rate = (Tsy2Y + Baa_Yield) / 100
leverage_spread = max(0, leverage_ratio - debt_safe_leverage) × debt_leverage_spread_bps / 10000
cost_rate = base_rate + leverage_spread
```

With `debt_leverage_spread_bps = 500` (5% per unit of excess leverage):

| Leverage | Spread | Effect |
|----------|--------|--------|
| 0.3      | +0.0%  | Below safe threshold |
| 0.7      | +1.0%  | |
| 1.0      | +2.5%  | |

### C.3 Simulate Success

For each fundraising attempt at month `t`:

```python
prob = P_base_csv × company_modifier   # adjusted probability
roll = random()
success = roll < prob
```

### C.4 Amount Raised & Cost

**Amount Raised (on success):**

```
fill_rate = Uniform(0.7, 1.0)
Amount_Raised = Fund_Ask × fill_rate
```

**Cost:**

```
Debt_Cost   = (Tsy2Y + Baa_Yield) / 100 + leverage_spread   (annual interest rate, includes company risk)
Equity_Cost = Fund_Ask / Implied_Valuation                    (dilution %)
```

### C.5 Deferred Settlement

Fundraising results are not immediate. Upon submission, the outcome (success/failure) and delivery month are determined but not revealed to the agent:

```
delivery_month = current_month + randint(fundraising_delivery_min, fundraising_delivery_max)
```

The agent receives a "submitted" confirmation. At the delivery month, a notification is sent with the result:
- **If approved:** funds are deposited, balance sheet updated, cap table refreshed (for equity)
- **If declined:** no changes, agent may retry

Config parameters: `fundraising_delivery_min = 1`, `fundraising_delivery_max = 6` (in `environment_config`).

### C.6 Configuration Parameters

All fundraising difficulty parameters are in `config.json → environment_config`:

```json
"equity_round_decay": 0.75,
"debt_safe_leverage": 0.5,
"debt_leverage_prob_decay": 1.5,
"debt_leverage_spread_bps": 500,
"fundraising_delivery_min": 1,
"fundraising_delivery_max": 6
```

### C.7 Historical Reference (2015–2025)

#### Normalization Parameters

| Metric | Min | Max |
|--------|-----|-----|
| Rate (SOFR/FEDFUNDS) | 0.01% | 5.34% |
| VIX | 10.13 | 57.74 |

#### Summary Statistics

| Metric | P_debt | P_equity |
|--------|--------|----------|
| Min | 0.00 | 0.00 |
| Max | 1.00 | 1.00 |
| Mean | 0.63 | 0.83 |

#### Notable Periods

| Event | Date | Probability | Driver |
|-------|------|-------------|--------|
| **Best for Debt** | Apr 2021 | P_debt = 1.00 | Rate = 0.01% (near-zero rates) |
| **Worst for Debt** | Jul 2024 | P_debt = 0.00 | Rate = 5.34% (peak rates) |
| **Best for Equity** | Oct 2017 | P_equity = 1.00 | VIX = 10.13 (lowest volatility) |
| **Worst for Equity** | Mar 2020 | P_equity = 0.00 | VIX = 57.74 (COVID crash) |

> Data source: `fundraising_success_probabilities_2015_2025.csv`

---

## Module D: Stochastic Simulation & Evaluation Design

### D.1 Deterministic vs. Stochastic Components

当前模拟器中各环节可分为两类:

#### 确定性逻辑(Deterministic)— 不应加入随机性

这些要素由环境数据或会计公式直接驱动,是"游戏规则"本身,加入随机性会破坏逻辑一致性:

| 组件 | 原因 |
|------|------|
| 宏观经济指标 (Tsy2Y, Baa_Yield, VIX, FEDFUNDS 等) | 来自真实历史数据,是所有 agent 面对的相同环境 |
| Lending Rate = Tsy2Y + Baa_Yield | 纯公式,由环境决定 |
| Revenue = Portfolio × Rate / 12 | 会计恒等式,给定 portfolio 和 rate 后无歧义 |
| COGS / Gross Profit / EBITDA / OpEx 分解 | 给定 margin 后是纯算术 |
| 所有 Timing Lag 结构 (1 month, 4 month) | 系统规则,不应随机化 |
| Cash Balance 更新公式 | 会计恒等式 |
| 三表生成与配平 (IS, BS, CF) | 会计规则,不容差异 |
| P_debt / P_equity 计算 | 由环境指标确定的概率值本身是确定的 |

#### 可引入随机性(Stochastic)— 增加 episode 间差异

这些要素在现实中本身存在波动,加入噪声可以测试 agent 在不确定环境中的鲁棒性:

| 组件 | 当前设计 | 随机化方案 | 理由 |
|------|----------|-----------|------|
| **Fundraising 成功/失败** | `random() < P_success` | 保持不变(已经是随机的) | 核心随机性来源 |
| **Collection Rate** | 固定 0.96 | `clip(N(0.96, σ₁), 0.85, 1.0)` 每月独立抽样 | 真实中催收率受经济环境和借款人行为波动 |
| **User Growth** | 直接用 CSV 中的 `Monthly_User_Growth` | `Monthly_User_Growth(t) + N(0, σ₂)` | 用户增长有行业噪声,同一经济环境下不同公司有差异 |
| **Gross Margin** | 直接用 CSV 中的 `Gross_Margin` | `Gross_Margin(t) + N(0, σ₃)` | 信用损失和服务成本有月度波动 |
| **EBITDA Margin** | 直接用 CSV 中的 `EBITDA_Margin` | `EBITDA_Margin(t) + N(0, σ₄)` | 运营效率有随机波动 |
| **Fundraising 到账金额** | `Fund_Ask × P_success` (全额或零) | `Fund_Ask × Uniform(0.7, 1.0)` (部分到账) | 现实中很少恰好拿到全额 |

> 注意:Lending Rate、Revenue 公式、Cash Formula、三表逻辑**不加噪声**。这些是确定性的"物理定律"。随机性只加在输入参数上,公式本身保持精确。

### D.2 噪声参数 (Noise Parameters)

所有噪声参数集中管理,写入 `config.json → stochastic_config````
stochastic_config: {
    "enabled": true,                  -- 开关:false 时退化为完全确定性
    "seed": null,                     -- 全局种子,null 表示使用 episode_id
    "n_episodes": 1000,               -- 每个 agent 的运行次数

    "collection_rate_std": 0.04,      -- σ₁: Collection Rate 标准差
    "user_growth_std": 0.5,           -- σ₂: Monthly User Growth 标准差 (百分点)
    "gross_margin_std": 2.0,          -- σ₃: Gross Margin 标准差 (百分点)
    "ebitda_margin_std": 1.5,         -- σ₄: EBITDA Margin 标准差 (百分点)
    "fundraising_fill_range": [0.7, 1.0]  -- 到账比例的均匀分布范围
}
```

### D.3 可比性保证:Common Random Numbers (CRN)

**核心问题:** 加入随机性后,如何确保 Agent A 和 Agent B 的结果是可比的?

**方案:种子控制 + 配对比较 (Paired Comparison with CRN)**

```
对于 episode i = 1, 2, ..., 1000:
    seed_i = base_seed + i
    rng_i  = RandomGenerator(seed_i)

    用 rng_i 预生成该 episode 的所有随机序列:
      collection_rates[0..T]    ← N(0.96, σ₁) per month
      user_growth_noise[0..T]   ← N(0, σ₂) per month
      gross_margin_noise[0..T]  ← N(0, σ₃) per month
      ebitda_margin_noise[0..T] ← N(0, σ₄) per month
      fundraising_rolls[0..T]   ← Uniform(0, 1) per month  (用于判定成功/失败)
      fundraising_fills[0..T]   ← Uniform(0.7, 1.0) per month

    Agent A 和 Agent B 在 episode i 中面对**完全相同**的随机序列
    唯一的差异来自 agent 的决策(何时融资、融多少、选 debt 还是 equity)
```

> **关键:** 随机序列是环境的属性,不是 agent 的属性。同一 episode 中所有 agent 面对相同的"天气",区别只在于他们如何应对。

**为什么这有效?**

1. **消除运气差异:** 如果 Agent A 碰巧遇到高 Collection Rate 的 episode 而 Agent B 没有,比较不公平。CRN 确保两者面对同样的随机环境
2. **降低所需样本量:** 配对比较的方差远小于独立比较。Var(A-B|paired) << Var(A) + Var(B)。1000 次可能就足够,而独立比较可能需要 10000+
3. **可复现:** 给定 seed,任何 episode 都可以精确复现,便于 debug

### D.4 评估指标与统计方法

**每个 episode 产出一个 score:**

```
Score_i = (TTM_Revenue × Valuation_Multiple) + Cash_Balance    if cash never went negative
Score_i = 0                                                     if cash went negative at any point
```

> `Valuation_Multiple` = 10 (from `config.json → environment_config.valuation_multiple`)
> TTM = Trailing Twelve Months revenue (sum of last 12 months from `pnl_ledger.revenue`)

**跨 episode 聚合:**

| 指标 | 计算 | 用途 |
|------|------|------|
| Mean Score | `mean(Score_1..Score_N)` | 主要排名指标 |
| Survival Rate | `count(Score > 0) / N` | agent 避免现金危机的能力 |
| Std Dev | `std(Score_1..Score_N)` | 策略稳定性 |
| Median Score | `median(Score_1..Score_N)` | 抗极端值的稳健指标 |
| 5th Percentile | `quantile(Score, 0.05)` | 最差情况表现(tail risk) |

**Agent 间比较:**

```
对于每个 episode i:
    Δ_i = Score_A_i − Score_B_i       (配对差值)

统计检验:
    H₀: mean(Δ) = 0  (两个 agent 无差异)
    H₁: mean(Δ) ≠ 0

    使用 paired t-test 或 Wilcoxon signed-rank test
    报告 p-value 和 95% confidence interval for mean(Δ)
```

> 因为使用了 CRN,配对差值 Δ_i 的方差很小,即使两个 agent 的平均表现差异不大也能检测出来。

### D.5 实验流程

```
输入:
  agents = [Agent_A, Agent_B, Agent_C, ...]
  N = 1000
  base_seed = 42

流程:
  for i in 1..N:
      env_i = generate_environment(seed = base_seed + i)
        → 预生成所有月份的随机参数
        → 加载确定性的宏观数据

      for agent in agents:
          reset agent state
          score_i[agent] = run_episode(agent, env_i)

输出:
  for each agent:
      mean, std, median, survival_rate, p5, p95

  for each agent pair (A, B):
      paired_diff = score[A] − score[B]
      t_stat, p_value = paired_ttest(paired_diff)
      → "Agent A is significantly better/worse than Agent B (p < 0.05)"
```

---

## System Flow Diagram

```
  ──── Every month (automatic) ────


    Module A: update both ledgers
    ┌──────────────────────────────────┐
    │  1. Compute Users(t), Revenue(t) │  ← P&L ledger (accrual)
    │     COGS(t), OpEx(t), etc.       │
    │                                  │
    │  2. Compute cash flows with lags │  ← Cash ledger (bank account)
    │     Revenue(t-1) → cash in       │
    │     New loans(t) → cash out      │
    │     OpEx(t-1) → cash out         │
    │                                  │
    │  3. Update BS running balances   │  ← Loan Portfolio, Allowance,
    │     Provision(t-4) → write-off   │     Receivables, Payables
    │     (non-cash BS reclassification)│
    │                                  │
    │  4. Update cash_balance          │
    └──────────────────────────────────┘


  Agent decides action at month t

           ├──── action = "book_closing"
           │         │
           │         ▼
           │    Freeze both ledgers [0, t]
           │         │
           │         ▼
           │    Generate 3 statements
           │    (IS from pnl_ledger,
           │     BS from both,
           │     CF from cash_ledger)
           │         │
           │         ▼
           │    Return to agent

           └──── action = "fund_raising_request"


                Generate 3 statements (same as above)


              Module C: evaluate P_success

                ┌────┴────┐
                ▼         ▼
            SUCCESS    FAILURE
                │         │
                ▼         │
          Update:         │
          - cash_ledger   │
          - capital_summary│
          - debt/equity   │
          - cap table     │
                │         │
                ▼         ▼
            Return results to agent
```

---

## Data Dependencies

| Module | Reads From | Writes To |
|--------|-----------|----------|
| **A: Tracking** | `data_paths.combined_econ_data` (Tsy2Y, Baa_Yield, Gross_Margin, EBITDA_Margin, **adj_Monthly_User_Growth**) + `company_config` (loan params, lag params) | `pnl_ledger`, `cash_ledger`, `capital_summary`, `debt_instruments`, `equity_rounds` |
| **B: Statements** | `pnl_ledger`, `cash_ledger`, `capital_summary`, `debt_instruments`, `equity_rounds` | `financial_snapshots` |
| **C: Fundraising** | `data_paths.fundraising_probs` (**adj_P_debt**, **adj_P_equity**) | Results fed into Module A & B |
| **D: Stochastic** | `stochastic_config` (noise params, seed, n_episodes) | Pre-generated random sequences per episode |

---

## Appendix: Accounting Review — Issues Found & Fixed

在设计三表配平检查时,发现并修正了以下三个问题:

### Issue 1: Write-off 被错误归类为现金流出

**原始设计:** `Cash_Out_Writeoffs(t) = Credit_Loss_Provision(t-4)` 作为现金流出项出现在 cash_ledger 和现金流量表中。

**问题:** Write-off 是资产负债表内部的重新分类(Gross ↓, Allowance ↓, Net 不变),不会导致现金离开银行账户。违约对现金的影响已经通过 `Collection_Rate < 100%` 体现——违约借款人停止支付利息和本金,导致 `Cash_In_Interest``Cash_In_Principal` 减少。将 write-off 同时计入现金流出会造成**重复计算****修正:** 从 cash_ledger、A.4 现金公式、现金流量表中移除 `Cash_Out_Writeoffs`。Write-off 仅作为资产负债表非现金操作保留在 A.6 的 running balance 逻辑中。

### Issue 2: 缺少 Interest Receivable 和 Principal Receivable

**原始设计:** 资产负债表资产端只有 Cash、Loan Portfolio、Other Assets。

**问题:** Revenue 在月 t 通过 P&L 确认(accrual),增加 Retained Earnings(Equity ↑),但现金要到 t+1 才到账。如果资产端没有对应的 Receivable,则 Equity 增加了但 Asset 没有同步增加,**A ≠ L + E**。同理,本金还款在 t 月安排但 t+1 到账,Loan Portfolio Gross 已经减少但 Cash 尚未增加,中间需要 Principal Receivable 来桥接。

**修正:** 在资产负债表中新增 `Interest Receivable = Revenue(t)` 和 `Principal Receivable = Loan_Portfolio_Gross(t) / Avg_Loan_Term`,并在 A.6 中定义其清算逻辑。

### Issue 3: Accounts Payable 不完整

**原始设计:** `Accounts Payable = OpEx(t)` — 仅包含运营费用。

**问题:** Servicing Costs(COGS 中的非 provision 部分)同样有 1 个月的现金滞后(月 t 确认,t+1 支付)。如果只计入 OpEx 的应付而遗漏 Servicing Costs,则 P&L 确认的 Servicing_Costs 减少了 Equity(通过 RE),但负债端没有对应增加,**L + E 不等式被打破****修正:** 扩展为 `Accounts_Payable(t) = OpEx(t) + Servicing_Costs(t)`