File size: 13,202 Bytes
3b01fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
 
 
 
 
 
 
 
 
 
3b01fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
 
 
 
 
 
 
3b01fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
 
 
 
 
 
3b01fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fd88a5
 
 
 
3b01fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
validate_dscr.py — Calculates DSCR and returns GREEN/YELLOW/RED with jurisdiction-calibrated thresholds.

Usage:
    python scripts/validate_dscr.py --noi 850000 --debt_service 620000 --jurisdiction uk
    python scripts/validate_dscr.py --noi 1200000 --debt_service 850000 --jurisdiction usa --asset_type commercial

Output:
    JSON with DSCR value, applicable threshold, margin, and RED/YELLOW/GREEN status.

Sources for thresholds: typical institutional lender requirements by market.
These are reference ranges — actual lender requirements vary. Verify with specific lender.
"""

import argparse
import json
import sys

# ─── DSCR Thresholds by Jurisdiction and Asset Type ──────────────────────────
# Format: min_normal = minimum for GREEN; min_stress = minimum for YELLOW
# Below min_stress = RED (escalate immediately)

THRESHOLDS = {
    # ── USA ──────────────────────────────────────────────────────────────────
    "usa_commercial": {
        "min_normal": 1.25,
        "min_stress": 1.10,
        "note": "US CRE institutional lender standard (CMBS/life company)",
        "source": "Typical US commercial real estate lending",
    },
    "usa_residential": {
        "min_normal": 1.20,
        "min_stress": 1.05,
        "note": "US residential rental / multifamily",
        "source": "Fannie Mae / Freddie Mac multifamily guidelines",
    },
    "usa_industrial": {
        "min_normal": 1.25,
        "min_stress": 1.10,
        "note": "US industrial / logistics",
        "source": "Typical US industrial lending",
    },

    # ── UK ───────────────────────────────────────────────────────────────────
    "uk_commercial": {
        "min_normal": 1.20,
        "min_stress": 1.05,
        "note": "UK CRE standard (clearing banks / debt funds)",
        "source": "Typical UK commercial real estate lending",
    },
    "uk_residential": {
        "min_normal": 1.25,
        "min_stress": 1.10,
        "note": "UK buy-to-let / PRS residential",
        "source": "UK PRA / typical BTL lender requirement",
    },
    "uk_industrial": {
        "min_normal": 1.20,
        "min_stress": 1.05,
        "note": "UK logistics / industrial",
        "source": "Typical UK industrial lending",
    },

    # ── SPAIN ─────────────────────────────────────────────────────────────────
    "spain_commercial": {
        "min_normal": 1.25,
        "min_stress": 1.10,
        "note": "Spain CRE (banca española / European debt funds)",
        "source": "Typical Spain commercial real estate lending",
    },
    "spain_residential": {
        "min_normal": 1.20,
        "min_stress": 1.05,
        "note": "Spain residential rental",
        "source": "Typical Spain residential lending",
    },
    "spain_industrial": {
        "min_normal": 1.25,
        "min_stress": 1.10,
        "note": "Spain industrial / logistics",
        "source": "Typical Spain industrial lending",
    },

    # ── GERMANY ───────────────────────────────────────────────────────────────
    "germany_commercial": {
        "min_normal": 1.20,
        "min_stress": 1.05,
        "note": "Germany CRE (Pfandbrief-eligible lender standard)",
        "source": "Germany Pfandbrief bank / typical CRE lending",
    },
    "germany_residential": {
        "min_normal": 1.20,
        "min_stress": 1.05,
        "note": "Germany residential rental (Wohnimmobilien)",
        "source": "Typical German residential lending",
    },

    # ── FRANCE ────────────────────────────────────────────────────────────────
    "france_commercial": {
        "min_normal": 1.20,
        "min_stress": 1.05,
        "note": "France CRE",
        "source": "Typical France commercial real estate lending",
    },

    # ── INDIA ─────────────────────────────────────────────────────────────────
    "india_commercial": {
        "min_normal": 1.35,
        "min_stress": 1.15,
        "note": "India CRE (aligned with RBI guidelines for CRE lending)",
        "source": "RBI CRE lending guidelines / typical Indian bank standard",
    },
    "india_residential": {
        "min_normal": 1.30,
        "min_stress": 1.10,
        "note": "India residential / housing finance",
        "source": "NHB / typical Indian housing finance company",
    },

    # ── UAE ───────────────────────────────────────────────────────────────────
    "uae_commercial": {
        "min_normal": 1.25,
        "min_stress": 1.10,
        "note": "UAE CRE (local and international bank standard)",
        "source": "Typical UAE commercial real estate lending",
    },
    "uae_residential": {
        "min_normal": 1.25,
        "min_stress": 1.10,
        "note": "UAE residential",
        "source": "UAE Central Bank mortgage regulations",
    },

    # ── INFRASTRUCTURE ────────────────────────────────────────────────────────
    "infrastructure": {
        "min_normal": 1.40,
        "min_stress": 1.20,
        "note": "Infrastructure / project finance (PPP / concession standard)",
        "source": "MDB / project finance lender standard",
    },
    "infrastructure_social": {
        "min_normal": 1.30,
        "min_stress": 1.15,
        "note": "Social infrastructure (hospitals, schools, availability-based)",
        "source": "Typical social infrastructure project finance",
    },

    # ── DEFAULT ───────────────────────────────────────────────────────────────
    "default": {
        "min_normal": 1.25,
        "min_stress": 1.10,
        "note": "Industry default (jurisdiction not specified or not recognized)",
        "source": "General industry reference",
    },
}

# ─── Helper: Resolve threshold key ────────────────────────────────────────────

# Jurisdictions the detector recognises but for which NO calibrated DSCR threshold
# exists. They resolve to "default" and the output says so explicitly
# (threshold_calibrated: false). Kept in sync with data/jurisdiction_matrix.json
# by tests/test_v16.py. v15 listed "singapore" here (no reference file, silently
# defaulted) and rejected "canada"/"netherlands" that the detector supports.
CALIBRATED_JURISDICTIONS = ["usa", "uk", "spain", "germany", "france", "india", "uae"]
REFERENCE_ONLY_JURISDICTIONS = ["canada", "netherlands"]
JURISDICTION_CHOICES = CALIBRATED_JURISDICTIONS + REFERENCE_ONLY_JURISDICTIONS + ["default"]


def resolve_key(jurisdiction: str, asset_type: str) -> str:
    """Return the best matching threshold key."""
    # Direct match
    key = f"{jurisdiction}_{asset_type}"
    if key in THRESHOLDS:
        return key
    # Infrastructure shortcut
    if asset_type in ("infrastructure", "infrastructure_social"):
        return asset_type if asset_type in THRESHOLDS else "infrastructure"
    # Jurisdiction + commercial fallback
    key_commercial = f"{jurisdiction}_commercial"
    if key_commercial in THRESHOLDS:
        return key_commercial
    return "default"


def threshold_is_calibrated(thr_key: str, jurisdiction: str) -> bool:
    """True only when the threshold used is specific to the requested jurisdiction."""
    if thr_key.startswith("infrastructure"):
        return True
    return thr_key.startswith(f"{jurisdiction}_")


# ─── Core Calculation ──────────────────────────────────────────────────────────

def evaluate_dscr(
    noi: float,
    debt_service: float,
    jurisdiction: str = "default",
    asset_type: str = "commercial",
) -> dict:
    if debt_service <= 0:
        return {"error": "debt_service must be greater than 0"}
    if noi < 0:
        return {"error": "NOI is negative — property is loss-making. DSCR not meaningful."}

    dscr = noi / debt_service
    thr_key = resolve_key(jurisdiction, asset_type)
    thr = THRESHOLDS[thr_key]

    margin_vs_normal = dscr - thr["min_normal"]
    margin_vs_stress = dscr - thr["min_stress"]

    # Status determination
    if dscr >= thr["min_normal"]:
        status = "GREEN"
        status_detail = (
            f"DSCR {dscr:.2f}x exceeds minimum normal threshold of {thr['min_normal']:.2f}x "
            f"by {margin_vs_normal:+.2f}x. Adequate debt service coverage."
        )
    elif dscr >= thr["min_stress"]:
        status = "YELLOW"
        status_detail = (
            f"DSCR {dscr:.2f}x is below normal minimum ({thr['min_normal']:.2f}x) "
            f"but above stress minimum ({thr['min_stress']:.2f}x). "
            f"Marginal coverage — review cash flow assumptions and sensitivity."
        )
    else:
        status = "RED"
        status_detail = (
            f"DSCR {dscr:.2f}x is below stress minimum of {thr['min_stress']:.2f}x. "
            f"Debt service coverage is INSUFFICIENT even under stress threshold. "
            f"ESCALATE — do not proceed without restructuring debt or improving NOI."
        )

    # Breakeven calculation
    breakeven_noi = debt_service * thr["min_normal"]
    noi_gap = breakeven_noi - noi

    return {
        "inputs": {
            "noi": noi,
            "debt_service": debt_service,
            "jurisdiction": jurisdiction,
            "asset_type": asset_type,
        },
        "result": {
            "dscr": round(dscr, 3),
            "dscr_formatted": f"{dscr:.2f}x",
        },
        "threshold_applied": {
            "key": thr_key,
            "min_normal": thr["min_normal"],
            "min_stress": thr["min_stress"],
            "note": thr["note"],
            "source": thr["source"],
            "threshold_calibrated": threshold_is_calibrated(thr_key, jurisdiction),
            "calibration_note": (
                "Jurisdiction-specific threshold." if threshold_is_calibrated(thr_key, jurisdiction)
                else f"NO calibrated DSCR threshold exists for '{jurisdiction}'; industry default applied. "
                     "State this limitation in the output and verify with the lender."
            ),
        },
        "margins": {
            "vs_normal_threshold": f"{margin_vs_normal:+.3f}x",
            "vs_stress_threshold": f"{margin_vs_stress:+.3f}x",
        },
        "breakeven": {
            "noi_required_for_green": round(breakeven_noi, 0),
            "noi_gap_to_green": round(noi_gap, 0),
            "noi_gap_pct": f"{(noi_gap / breakeven_noi * 100):.1f}%" if noi_gap > 0 else "0.0% — already GREEN",
        },
        "status": status,
        "status_detail": status_detail,
        "escalation_required": status == "RED",
    }


# ─── CLI ──────────────────────────────────────────────────────────────────────

def main():
    parser = argparse.ArgumentParser(
        description="Calculate DSCR with jurisdiction-calibrated thresholds."
    )
    parser.add_argument("--noi", type=float, required=True, help="Annual Net Operating Income")
    parser.add_argument("--debt_service", type=float, required=True, help="Annual debt service (P&I or IO)")
    parser.add_argument(
        "--jurisdiction",
        default="default",
        choices=JURISDICTION_CHOICES,
        help=("Country/jurisdiction of the property (default: default). "
              "canada/netherlands are accepted but use industry-default thresholds "
              "(threshold_calibrated=false in the output)."),
    )
    parser.add_argument(
        "--asset_type",
        default="commercial",
        choices=["commercial", "residential", "industrial", "infrastructure", "infrastructure_social", "mixed"],
        help="Asset type (default: commercial)",
    )
    args = parser.parse_args()

    result = evaluate_dscr(args.noi, args.debt_service, args.jurisdiction, args.asset_type)
    print(json.dumps(result, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()