Kossisoroyce's picture
Upload folder using huggingface_hub
8a98d6d verified
Raw
History Blame Contribute Delete
10.5 kB
"""
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()