File size: 10,516 Bytes
8a98d6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Credit Access Patterns in Africa - Dataset Generator

DAG Structure:
    country → formal_credit_availability, interest_rates
    urban_rural → credit_institution_access
    income_quintile → credit_score, loan_eligibility
    employment_status → income_stability, loan_amount
    credit_history → approval_probability
    collateral → loan_amount, approval
    loan_purpose → interest_rate, approval
    approval → loan_disbursed, loan_amount_final

Parameter Evidence Table:
| Parameter | Value | Source |
|-----------|-------|--------|
| Formal credit access SSA | 15% | World Bank Findex 2025 |
| Informal credit access | 35% | World Bank Findex 2025 |
| Bank loan interest rates | 15-25% | World Bank 2024 |
| Microfinance rates | 25-45% | CGAP 2024 |
| Informal lender rates | 50-120% | FSD Kenya 2024 |
| Collateral requirement | 65% of formal loans | World Bank 2024 |
| Approval rate formal | 45% | World Bank 2024 |
| Approval rate informal | 75% | FSD Kenya 2024 |
| Credit bureau coverage | 12% SSA | World Bank 2024 |
| Default rate | 8-15% | IMF 2024 |
"""

import numpy as np
import pandas as pd
from pathlib import Path

COUNTRIES = [
    "Kenya", "Uganda", "Nigeria", "Ghana", "Tanzania", "Ethiopia",
    "Malawi", "Zambia", "Senegal", "Rwanda", "Niger", "Mali",
    "DRC", "Mozambique", "South Africa"
]

YEARS = list(range(2018, 2026))

COUNTRY_CREDIT_ACCESS = {
    "Kenya": 0.22, "Uganda": 0.15, "Tanzania": 0.14, "Ghana": 0.18,
    "Nigeria": 0.16, "Ethiopia": 0.08, "Malawi": 0.12, "Zambia": 0.15,
    "Senegal": 0.14, "Rwanda": 0.18, "Niger": 0.06, "Mali": 0.10,
    "DRC": 0.05, "Mozambique": 0.08, "South Africa": 0.35
}

CREDIT_SOURCES = ["commercial_bank", "microfinance", "sacco", "digital_lender", 
                  "informal_lender", "family_friends", "employer"]
LOAN_PURPOSES = ["business", "agriculture", "education", "housing", 
                 "consumption", "emergency", "asset_purchase", "debt_consolidation"]
COLLATERAL_TYPES = ["property", "vehicle", "equipment", "savings", "guarantor", "none"]


def generate_scenario(n_samples: int, seed: int, scenario: str) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    
    country = rng.choice(COUNTRIES, n_samples)
    year = rng.choice(YEARS, n_samples)
    
    urban_rural = np.where(rng.random(n_samples) < 0.42, "urban", "rural")
    
    gender = rng.choice(["male", "female"], n_samples, p=[0.48, 0.52])
    
    age = rng.integers(18, 70, n_samples)
    age_group = pd.cut(age, bins=[17, 25, 35, 45, 55, 70],
                       labels=["18-24", "25-34", "35-44", "45-54", "55+"])
    
    income_quintile = rng.choice(["lowest", "second", "middle", "fourth", "highest"],
                                  n_samples, p=[0.25, 0.22, 0.20, 0.18, 0.15])
    
    education = rng.choice(
        ["none", "primary", "secondary", "tertiary"],
        n_samples, p=[0.18, 0.32, 0.35, 0.15]
    )
    
    employment_status = rng.choice(
        ["employed_formal", "employed_informal", "self_employed", "farmer", "unemployed"],
        n_samples, p=[0.12, 0.23, 0.30, 0.22, 0.13]
    )
    
    monthly_income = rng.lognormal(
        mean=np.log(200) + np.select(
            [income_quintile == "lowest", income_quintile == "second",
             income_quintile == "middle", income_quintile == "fourth",
             income_quintile == "highest"],
            [-1.2, -0.5, 0.0, 0.5, 1.2]
        ) + np.where(urban_rural == "urban", 0.4, 0.0),
        sigma=0.7,
        size=n_samples
    )
    
    income_stability = rng.integers(1, 11, n_samples)
    income_stability = np.clip(
        income_stability + 
        np.where(employment_status == "employed_formal", 3, 0) +
        np.where(employment_status == "unemployed", -4, 0),
        1, 10
    )
    
    credit_history = rng.choice(
        ["none", "limited", "good", "excellent"],
        n_samples, p=[0.45, 0.30, 0.18, 0.07]
    )
    
    has_bank_account = (rng.random(n_samples) < 0.45).astype(int)
    
    credit_score = rng.integers(0, 851, n_samples)
    credit_score = np.clip(
        credit_score +
        np.where(income_quintile == "highest", 100, 0) +
        np.where(credit_history == "good", 80, 0) +
        np.where(credit_history == "excellent", 150, 0) +
        np.where(credit_history == "none", -100, 0),
        0, 850
    )
    
    credit_need = (rng.random(n_samples) < 
        0.40 + 
        np.where(employment_status == "self_employed", 0.15, 0.0) +
        np.where(employment_status == "farmer", 0.10, 0.0) -
        np.where(income_quintile == "highest", 0.10, 0.0)
    ).astype(int)
    
    preferred_source = np.empty(n_samples, dtype=object)
    preferred_source[credit_need == 0] = "none"
    need_mask = credit_need == 1
    
    for i in range(n_samples):
        if credit_need[i] == 1:
            if has_bank_account[i]:
                preferred_source[i] = rng.choice(CREDIT_SOURCES, p=[0.35, 0.18, 0.12, 0.15, 0.08, 0.10, 0.02])
            else:
                preferred_source[i] = rng.choice(CREDIT_SOURCES, p=[0.05, 0.15, 0.10, 0.10, 0.25, 0.30, 0.05])
    
    loan_amount_requested = np.zeros(n_samples)
    req_mask = credit_need == 1
    loan_amount_requested[req_mask] = rng.lognormal(
        mean=np.log(500) + np.log(monthly_income[req_mask] + 1) * 0.4,
        sigma=0.6,
        size=req_mask.sum()
    )
    
    collateral_available = np.empty(n_samples, dtype=object)
    collateral_available[credit_need == 0] = "none"
    collateral_available[req_mask] = rng.choice(
        COLLATERAL_TYPES, req_mask.sum(),
        p=[0.10, 0.05, 0.08, 0.15, 0.20, 0.42]
    )
    
    loan_purpose = np.empty(n_samples, dtype=object)
    loan_purpose[credit_need == 0] = "none"
    loan_purpose[req_mask] = rng.choice(
        LOAN_PURPOSES, req_mask.sum(),
        p=[0.30, 0.18, 0.12, 0.10, 0.12, 0.08, 0.07, 0.03]
    )
    
    approval_prob = np.zeros(n_samples)
    approval_prob[req_mask] = np.clip(
        0.30 +
        np.where(credit_score[req_mask] > 650, 0.25, 0.0) +
        np.where(credit_score[req_mask] > 750, 0.15, 0.0) +
        np.where(income_stability[req_mask] > 6, 0.10, 0.0) +
        np.where(has_bank_account[req_mask] == 1, 0.10, 0.0) +
        np.where(collateral_available[req_mask] != "none", 0.15, 0.0) -
        np.where(credit_score[req_mask] < 450, 0.20, 0.0),
        0.05, 0.95
    )
    
    approved = np.zeros(n_samples, dtype=int)
    approved[req_mask] = (rng.random(req_mask.sum()) < approval_prob[req_mask]).astype(int)
    
    loan_disbursed = np.zeros(n_samples)
    loan_disbursed[approved == 1] = loan_amount_requested[approved == 1] * rng.uniform(0.8, 1.0, approved.sum())
    
    interest_rate = np.zeros(n_samples)
    int_mask = approved == 1
    base_rates = np.select(
        [np.isin(preferred_source[int_mask], ["commercial_bank"]),
         np.isin(preferred_source[int_mask], ["microfinance", "sacco"]),
         np.isin(preferred_source[int_mask], ["digital_lender"]),
         np.isin(preferred_source[int_mask], ["informal_lender"]),
         np.isin(preferred_source[int_mask], ["family_friends", "employer"])],
        [0.18, 0.32, 0.45, 0.80, 0.05],
        default=0.25
    )
    interest_rate[int_mask] = base_rates + rng.uniform(-0.05, 0.05, int_mask.sum())
    
    loan_term_months = np.zeros(n_samples, dtype=int)
    loan_term_months[int_mask] = rng.choice([6, 12, 18, 24, 36, 48], int_mask.sum(), 
                                            p=[0.15, 0.35, 0.20, 0.18, 0.08, 0.04])
    
    monthly_payment = np.zeros(n_samples)
    monthly_payment[int_mask] = (
        loan_disbursed[int_mask] * (1 + interest_rate[int_mask]) / loan_term_months[int_mask]
    )
    
    repayment_status = np.empty(n_samples, dtype=object)
    repayment_status[approved == 0] = "not_applicable"
    repay_mask = approved == 1
    repayment_status[repay_mask] = rng.choice(
        ["current", "late_30_days", "late_60_days", "defaulted", "paid_off"],
        repay_mask.sum(),
        p=[0.55, 0.15, 0.08, 0.07, 0.15]
    )
    
    application_rejection_reason = np.empty(n_samples, dtype=object)
    application_rejection_reason[approved == 1] = "not_applicable"
    reject_mask = (credit_need == 1) & (approved == 0)
    application_rejection_reason[reject_mask] = rng.choice(
        ["insufficient_income", "no_credit_history", "no_collateral", 
         "employment_status", "existing_debt", "documentation_issues"],
        reject_mask.sum(),
        p=[0.25, 0.22, 0.20, 0.15, 0.10, 0.08]
    )
    
    df = pd.DataFrame({
        "country": country,
        "year": year,
        "urban_rural": urban_rural,
        "gender": gender,
        "age": age,
        "age_group": age_group,
        "income_quintile": income_quintile,
        "education": education,
        "employment_status": employment_status,
        "monthly_income_usd": np.round(monthly_income, 2),
        "income_stability": income_stability,
        "credit_history": credit_history,
        "has_bank_account": has_bank_account,
        "credit_score": credit_score,
        "credit_need": credit_need,
        "preferred_credit_source": preferred_source,
        "loan_amount_requested_usd": np.round(loan_amount_requested, 2),
        "collateral_available": collateral_available,
        "loan_purpose": loan_purpose,
        "approved": approved,
        "loan_disbursed_usd": np.round(loan_disbursed, 2),
        "interest_rate": np.round(interest_rate, 3),
        "loan_term_months": loan_term_months,
        "monthly_payment_usd": np.round(monthly_payment, 2),
        "repayment_status": repayment_status,
        "rejection_reason": application_rejection_reason,
        "scenario": scenario
    })
    
    return df


def main():
    output_dir = Path(__file__).parent
    
    scenarios = [
        ("low_burden", 4000, 42),
        ("moderate_burden", 5000, 43),
        ("high_burden", 6000, 44)
    ]
    
    all_dfs = []
    for scenario_name, n, seed in scenarios:
        df = generate_scenario(n, seed, scenario_name)
        all_dfs.append(df)
        
        output_path = output_dir / f"credit_access_{scenario_name}.csv"
        df.to_csv(output_path, index=False)
        print(f"Generated {output_path}: {len(df)} records")
    
    combined = pd.concat(all_dfs, ignore_index=True)
    combined_path = output_dir / "credit_access_combined.csv"
    combined.to_csv(combined_path, index=False)
    print(f"Generated {combined_path}: {len(combined)} records")


if __name__ == "__main__":
    main()