credit-survival 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- credit_survival-0.2.0/LICENSE +21 -0
- credit_survival-0.2.0/PKG-INFO +167 -0
- credit_survival-0.2.0/README.md +129 -0
- credit_survival-0.2.0/pyproject.toml +86 -0
- credit_survival-0.2.0/setup.cfg +4 -0
- credit_survival-0.2.0/src/credit_surv/__init__.py +64 -0
- credit_survival-0.2.0/src/credit_surv/data_loader.py +175 -0
- credit_survival-0.2.0/src/credit_surv/models.py +970 -0
- credit_survival-0.2.0/src/credit_survival.egg-info/PKG-INFO +167 -0
- credit_survival-0.2.0/src/credit_survival.egg-info/SOURCES.txt +12 -0
- credit_survival-0.2.0/src/credit_survival.egg-info/dependency_links.txt +1 -0
- credit_survival-0.2.0/src/credit_survival.egg-info/requires.txt +16 -0
- credit_survival-0.2.0/src/credit_survival.egg-info/top_level.txt +1 -0
- credit_survival-0.2.0/tests/test_models.py +530 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dongsoo Jung
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: credit-survival
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Dependency-light survival analysis for corporate credit risk: Cox PH, AFT, Random Survival Forest, C-index and IPCW Brier score in pure numpy/scipy
|
|
5
|
+
Author-email: Dongsoo Jung <jds068888@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/DongsooJung/credit-survival-analysis
|
|
8
|
+
Project-URL: Repository, https://github.com/DongsooJung/credit-survival-analysis
|
|
9
|
+
Project-URL: Issues, https://github.com/DongsooJung/credit-survival-analysis/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/DongsooJung/credit-survival-analysis/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: survival-analysis,credit-risk,cox-proportional-hazards,accelerated-failure-time,random-survival-forest,concordance-index,brier-score,default-prediction
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: numpy>=1.26.0
|
|
25
|
+
Requires-Dist: pandas>=2.1.0
|
|
26
|
+
Requires-Dist: scipy>=1.11.0
|
|
27
|
+
Provides-Extra: parquet
|
|
28
|
+
Requires-Dist: pyarrow>=14.0.0; extra == "parquet"
|
|
29
|
+
Provides-Extra: viz
|
|
30
|
+
Requires-Dist: matplotlib>=3.8.0; extra == "viz"
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Requires-Dist: pytest>=7.4.0; extra == "dev"
|
|
33
|
+
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
|
|
34
|
+
Requires-Dist: ruff<0.18,>=0.17.6; extra == "dev"
|
|
35
|
+
Requires-Dist: build>=1.0.0; extra == "dev"
|
|
36
|
+
Requires-Dist: twine>=5.0.0; extra == "dev"
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
|
|
39
|
+
# Corporate Credit Survival Analysis · 기업 신용 생존분석
|
|
40
|
+
|
|
41
|
+
> 한국 기업 신용위험 평가를 위한 생존모형 라이브러리 — numpy·scipy만으로 구현
|
|
42
|
+
> Dependency-light survival models for Korean corporate credit risk, implemented in pure numpy/scipy
|
|
43
|
+
|
|
44
|
+
[](https://github.com/DongsooJung/credit-survival-analysis/actions/workflows/ci.yml)
|
|
45
|
+
[](https://python.org)
|
|
46
|
+
[](.github/workflows/ci.yml)
|
|
47
|
+
[](#정확성-검증--validation)
|
|
48
|
+
[](LICENSE)
|
|
49
|
+
|
|
50
|
+
## 개요 · Overview
|
|
51
|
+
|
|
52
|
+
전통적 신용평가(로지스틱 회귀)는 부도를 이진 결과로만 다뤄 **사건까지의 시간(time-to-event)** 동학을 무시합니다. 본 저장소는 검열(censoring)을 올바르게 처리하는 생존모형과 생존 ML을, 무거운 의존성 없이 **numpy·scipy만으로** 구현한 신용위험 분석 패키지입니다. 의존성이 3개(numpy, pandas, scipy)뿐이라 폐쇄망 금융 환경에도 설치하기 쉽습니다.
|
|
53
|
+
|
|
54
|
+
Traditional credit scoring treats default as a binary outcome and ignores **time-to-event dynamics**. This package implements censoring-aware survival models and a random survival forest from scratch on numpy/scipy, so the core install has only three dependencies.
|
|
55
|
+
|
|
56
|
+
## 설치 · Installation
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install "git+https://github.com/DongsooJung/credit-survival-analysis"
|
|
60
|
+
# 개발 환경
|
|
61
|
+
git clone https://github.com/DongsooJung/credit-survival-analysis.git
|
|
62
|
+
cd credit-survival-analysis && pip install -e ".[dev]"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## 빠른 시작 · Quick Start
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
import credit_surv as cs
|
|
69
|
+
|
|
70
|
+
df = cs.load_synthetic_credit_panel(n_firms=2000, seed=42) # 참값이 알려진 합성 패널
|
|
71
|
+
covs = ["debt_ratio", "roa"]
|
|
72
|
+
|
|
73
|
+
cox = cs.CoxModel()
|
|
74
|
+
print(cox.fit(df, covs).summary()) # 계수·HR·표준오차·p·C-index·AIC/BIC
|
|
75
|
+
print(cox.check_proportional_hazards()) # Schoenfeld 잔차 비례위험 검정
|
|
76
|
+
|
|
77
|
+
aft = cs.AFTModel("weibull").fit(df, covs) # 시간비(TR), Weibull 형상 k
|
|
78
|
+
rsf = cs.RSFModel(n_estimators=200)
|
|
79
|
+
res = rsf.fit(df[covs], df[["duration", "event"]])
|
|
80
|
+
print(res.concordance_index, res.feature_importance) # OOB C-index, 순열 중요도
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## 구현 현황 · Implementation Status
|
|
84
|
+
|
|
85
|
+
| 기능 | 모듈 | 상태 | 검증 |
|
|
86
|
+
|------|------|------|------|
|
|
87
|
+
| Kaplan-Meier 생존함수 | `models.KaplanMeier` | ✅ 구현 | 교과서 예제 |
|
|
88
|
+
| Cox PH (Breslow 부분우도, 해석적 헤시안, L2 벌점) | `models.CoxModel` | ✅ 구현 | lifelines 계수·표준오차 일치 |
|
|
89
|
+
| Breslow 기저위험 · 개인별 생존곡선 | `CoxModel.predict_survival_function` | ✅ 구현 | 단조성·경계값 |
|
|
90
|
+
| Schoenfeld 잔차 · 비례위험 검정 (rank/identity/log/km) | `CoxModel.check_proportional_hazards` | ✅ 구현 | lifelines 통계량 일치, 위반 데이터 검출 |
|
|
91
|
+
| AFT (Weibull / Log-normal / Log-logistic) | `models.AFTModel` | ✅ 구현 | lifelines 계수·로그우도 일치 |
|
|
92
|
+
| Random Survival Forest (로그순위 분할) | `models.RSFModel` | ✅ 구현 | OOB C-index, 잡음 변수 판별 |
|
|
93
|
+
| OOB 순열 변수중요도 | `RSFModel.feature_importance` | ✅ 구현 | 잡음 변수 ≈ 0 |
|
|
94
|
+
| Harrell's C-index (벡터화, 동점 처리) | `models.concordance_index` | ✅ 구현 | 완전탐색 구현과 일치 |
|
|
95
|
+
| IPCW Brier · 통합 Brier 점수 | `models.brier_score`, `integrated_brier_score` | ✅ 구현 | 해석적 경계값 |
|
|
96
|
+
| 실데이터 로더 (KED·DART parquet) | `data_loader.load_credit_panel` | ✅ 구현 | 필터 단위테스트 (데이터는 비공개) |
|
|
97
|
+
| 시점별 AUC (Uno) | — | 🗺 로드맵 | — |
|
|
98
|
+
| DeepSurv · 공간 frailty · 경쟁위험 | — | 🗺 로드맵 | — |
|
|
99
|
+
|
|
100
|
+
## 정확성 검증 · Validation
|
|
101
|
+
|
|
102
|
+
같은 합성 패널(n=2,000, 사건 608건)을 [lifelines](https://github.com/CamDavidsonPilon/lifelines) 0.30으로 적합한 결과와 대조해, 아래 값을 회귀 테스트(`tests/test_models.py::LIFELINES_REF`)로 고정했습니다. CI는 lifelines를 설치하지 않습니다.
|
|
103
|
+
|
|
104
|
+
| 항목 | 본 패키지 | lifelines | 참값 |
|
|
105
|
+
|------|-----------|-----------|------|
|
|
106
|
+
| Cox β(debt_ratio) / SE | 0.50275 / 0.04239 | 0.50275 / 0.04239 | 0.5 |
|
|
107
|
+
| Cox β(roa) / SE | −0.31371 / 0.04115 | −0.31371 / 0.04115 | −0.3 |
|
|
108
|
+
| Cox 부분 로그우도 | −3978.162 | −3978.162 | — |
|
|
109
|
+
| 비례위험 검정 통계량 (debt_ratio, roa) | 0.0958, 0.5515 | 0.0958, 0.5515 | 귀무가설 참 |
|
|
110
|
+
| Weibull AFT β(debt_ratio) | −0.3394 | −0.3394 | −0.5/1.5 = −0.333 |
|
|
111
|
+
| Weibull 형상 k | 1.496 | 1.496 | 1.5 |
|
|
112
|
+
|
|
113
|
+
검증 데이터(30% 분할) 성능 — [`notebooks/01_credit_survival.ipynb`](notebooks/01_credit_survival.ipynb):
|
|
114
|
+
|
|
115
|
+
| 모형 | C-index | 통합 Brier (IPCW) |
|
|
116
|
+
|------|---------|-------------------|
|
|
117
|
+
| Kaplan-Meier (기준선) | 0.500 | 0.168 |
|
|
118
|
+
| Cox PH | 0.637 | 0.157 |
|
|
119
|
+
| Weibull AFT | 0.637 | 0.157 |
|
|
120
|
+
| Random Survival Forest | 0.626 | 0.160 |
|
|
121
|
+
|
|
122
|
+
데이터가 비례위험 Weibull에서 생성되었으므로 Cox·AFT가 최선이고, RSF는 분포 가정 없이 근접합니다.
|
|
123
|
+
|
|
124
|
+
## 프로젝트 구조 · Repository Structure
|
|
125
|
+
|
|
126
|
+
```
|
|
127
|
+
credit-survival-analysis/
|
|
128
|
+
├── src/credit_surv/
|
|
129
|
+
│ ├── data_loader.py # 실데이터 로더, 합성 패널, long → 생존형식 변환
|
|
130
|
+
│ └── models.py # KM, Cox, AFT, RSF, C-index, Brier
|
|
131
|
+
├── notebooks/01_credit_survival.ipynb # KM → Cox → PH 검정 → AFT → RSF → 검증 비교 (실행 결과 포함)
|
|
132
|
+
├── tests/test_models.py # 64개 테스트, 커버리지 90% 미만이면 CI 실패
|
|
133
|
+
├── docs/ARCHITECTURE.md # 수식과 설계
|
|
134
|
+
└── pyproject.toml
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
## 개발 · Development
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
pip install -e ".[dev]"
|
|
141
|
+
ruff check src tests
|
|
142
|
+
pytest --cov --cov-fail-under=90
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
CI는 Python 3.11·3.12에서 린트·테스트·커버리지를 검사하고, sdist·wheel을 빌드해 `twine check`와 설치 스모크 테스트를 수행합니다.
|
|
146
|
+
|
|
147
|
+
## 참고문헌 · References
|
|
148
|
+
|
|
149
|
+
- Cox, D. R. (1972). Regression models and life-tables. *JRSS-B*, 34(2), 187–202.
|
|
150
|
+
- Breslow, N. (1974). Covariance analysis of censored survival data. *Biometrics*, 30(1), 89–99.
|
|
151
|
+
- Harrell, F. E. et al. (1982). Evaluating the yield of medical tests. *JAMA*, 247(18), 2543–2546.
|
|
152
|
+
- Grambsch, P. M., & Therneau, T. M. (1994). Proportional hazards tests and diagnostics based on weighted residuals. *Biometrika*, 81(3), 515–526.
|
|
153
|
+
- Graf, E. et al. (1999). Assessment and comparison of prognostic classification schemes for survival data. *Statistics in Medicine*, 18(17–18), 2529–2545.
|
|
154
|
+
- Ishwaran, H. et al. (2008). Random survival forests. *Annals of Applied Statistics*, 2(3), 841–860.
|
|
155
|
+
- Hosmer, D. W., Lemeshow, S., & May, S. (2008). *Applied Survival Analysis*. Wiley.
|
|
156
|
+
|
|
157
|
+
## 인용 · Citation
|
|
158
|
+
|
|
159
|
+
[`CITATION.cff`](CITATION.cff)를 참고하세요. GitHub 저장소 화면의 "Cite this repository"에서 BibTeX를 바로 받을 수 있습니다.
|
|
160
|
+
|
|
161
|
+
## 라이선스 · License
|
|
162
|
+
|
|
163
|
+
MIT License
|
|
164
|
+
|
|
165
|
+
## 저자 · Author
|
|
166
|
+
|
|
167
|
+
**정동수 (Dongsoo Jung)** — 서울대학교 박사과정 · 공간계량 & 금융위험
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# Corporate Credit Survival Analysis · 기업 신용 생존분석
|
|
2
|
+
|
|
3
|
+
> 한국 기업 신용위험 평가를 위한 생존모형 라이브러리 — numpy·scipy만으로 구현
|
|
4
|
+
> Dependency-light survival models for Korean corporate credit risk, implemented in pure numpy/scipy
|
|
5
|
+
|
|
6
|
+
[](https://github.com/DongsooJung/credit-survival-analysis/actions/workflows/ci.yml)
|
|
7
|
+
[](https://python.org)
|
|
8
|
+
[](.github/workflows/ci.yml)
|
|
9
|
+
[](#정확성-검증--validation)
|
|
10
|
+
[](LICENSE)
|
|
11
|
+
|
|
12
|
+
## 개요 · Overview
|
|
13
|
+
|
|
14
|
+
전통적 신용평가(로지스틱 회귀)는 부도를 이진 결과로만 다뤄 **사건까지의 시간(time-to-event)** 동학을 무시합니다. 본 저장소는 검열(censoring)을 올바르게 처리하는 생존모형과 생존 ML을, 무거운 의존성 없이 **numpy·scipy만으로** 구현한 신용위험 분석 패키지입니다. 의존성이 3개(numpy, pandas, scipy)뿐이라 폐쇄망 금융 환경에도 설치하기 쉽습니다.
|
|
15
|
+
|
|
16
|
+
Traditional credit scoring treats default as a binary outcome and ignores **time-to-event dynamics**. This package implements censoring-aware survival models and a random survival forest from scratch on numpy/scipy, so the core install has only three dependencies.
|
|
17
|
+
|
|
18
|
+
## 설치 · Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install "git+https://github.com/DongsooJung/credit-survival-analysis"
|
|
22
|
+
# 개발 환경
|
|
23
|
+
git clone https://github.com/DongsooJung/credit-survival-analysis.git
|
|
24
|
+
cd credit-survival-analysis && pip install -e ".[dev]"
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## 빠른 시작 · Quick Start
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import credit_surv as cs
|
|
31
|
+
|
|
32
|
+
df = cs.load_synthetic_credit_panel(n_firms=2000, seed=42) # 참값이 알려진 합성 패널
|
|
33
|
+
covs = ["debt_ratio", "roa"]
|
|
34
|
+
|
|
35
|
+
cox = cs.CoxModel()
|
|
36
|
+
print(cox.fit(df, covs).summary()) # 계수·HR·표준오차·p·C-index·AIC/BIC
|
|
37
|
+
print(cox.check_proportional_hazards()) # Schoenfeld 잔차 비례위험 검정
|
|
38
|
+
|
|
39
|
+
aft = cs.AFTModel("weibull").fit(df, covs) # 시간비(TR), Weibull 형상 k
|
|
40
|
+
rsf = cs.RSFModel(n_estimators=200)
|
|
41
|
+
res = rsf.fit(df[covs], df[["duration", "event"]])
|
|
42
|
+
print(res.concordance_index, res.feature_importance) # OOB C-index, 순열 중요도
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## 구현 현황 · Implementation Status
|
|
46
|
+
|
|
47
|
+
| 기능 | 모듈 | 상태 | 검증 |
|
|
48
|
+
|------|------|------|------|
|
|
49
|
+
| Kaplan-Meier 생존함수 | `models.KaplanMeier` | ✅ 구현 | 교과서 예제 |
|
|
50
|
+
| Cox PH (Breslow 부분우도, 해석적 헤시안, L2 벌점) | `models.CoxModel` | ✅ 구현 | lifelines 계수·표준오차 일치 |
|
|
51
|
+
| Breslow 기저위험 · 개인별 생존곡선 | `CoxModel.predict_survival_function` | ✅ 구현 | 단조성·경계값 |
|
|
52
|
+
| Schoenfeld 잔차 · 비례위험 검정 (rank/identity/log/km) | `CoxModel.check_proportional_hazards` | ✅ 구현 | lifelines 통계량 일치, 위반 데이터 검출 |
|
|
53
|
+
| AFT (Weibull / Log-normal / Log-logistic) | `models.AFTModel` | ✅ 구현 | lifelines 계수·로그우도 일치 |
|
|
54
|
+
| Random Survival Forest (로그순위 분할) | `models.RSFModel` | ✅ 구현 | OOB C-index, 잡음 변수 판별 |
|
|
55
|
+
| OOB 순열 변수중요도 | `RSFModel.feature_importance` | ✅ 구현 | 잡음 변수 ≈ 0 |
|
|
56
|
+
| Harrell's C-index (벡터화, 동점 처리) | `models.concordance_index` | ✅ 구현 | 완전탐색 구현과 일치 |
|
|
57
|
+
| IPCW Brier · 통합 Brier 점수 | `models.brier_score`, `integrated_brier_score` | ✅ 구현 | 해석적 경계값 |
|
|
58
|
+
| 실데이터 로더 (KED·DART parquet) | `data_loader.load_credit_panel` | ✅ 구현 | 필터 단위테스트 (데이터는 비공개) |
|
|
59
|
+
| 시점별 AUC (Uno) | — | 🗺 로드맵 | — |
|
|
60
|
+
| DeepSurv · 공간 frailty · 경쟁위험 | — | 🗺 로드맵 | — |
|
|
61
|
+
|
|
62
|
+
## 정확성 검증 · Validation
|
|
63
|
+
|
|
64
|
+
같은 합성 패널(n=2,000, 사건 608건)을 [lifelines](https://github.com/CamDavidsonPilon/lifelines) 0.30으로 적합한 결과와 대조해, 아래 값을 회귀 테스트(`tests/test_models.py::LIFELINES_REF`)로 고정했습니다. CI는 lifelines를 설치하지 않습니다.
|
|
65
|
+
|
|
66
|
+
| 항목 | 본 패키지 | lifelines | 참값 |
|
|
67
|
+
|------|-----------|-----------|------|
|
|
68
|
+
| Cox β(debt_ratio) / SE | 0.50275 / 0.04239 | 0.50275 / 0.04239 | 0.5 |
|
|
69
|
+
| Cox β(roa) / SE | −0.31371 / 0.04115 | −0.31371 / 0.04115 | −0.3 |
|
|
70
|
+
| Cox 부분 로그우도 | −3978.162 | −3978.162 | — |
|
|
71
|
+
| 비례위험 검정 통계량 (debt_ratio, roa) | 0.0958, 0.5515 | 0.0958, 0.5515 | 귀무가설 참 |
|
|
72
|
+
| Weibull AFT β(debt_ratio) | −0.3394 | −0.3394 | −0.5/1.5 = −0.333 |
|
|
73
|
+
| Weibull 형상 k | 1.496 | 1.496 | 1.5 |
|
|
74
|
+
|
|
75
|
+
검증 데이터(30% 분할) 성능 — [`notebooks/01_credit_survival.ipynb`](notebooks/01_credit_survival.ipynb):
|
|
76
|
+
|
|
77
|
+
| 모형 | C-index | 통합 Brier (IPCW) |
|
|
78
|
+
|------|---------|-------------------|
|
|
79
|
+
| Kaplan-Meier (기준선) | 0.500 | 0.168 |
|
|
80
|
+
| Cox PH | 0.637 | 0.157 |
|
|
81
|
+
| Weibull AFT | 0.637 | 0.157 |
|
|
82
|
+
| Random Survival Forest | 0.626 | 0.160 |
|
|
83
|
+
|
|
84
|
+
데이터가 비례위험 Weibull에서 생성되었으므로 Cox·AFT가 최선이고, RSF는 분포 가정 없이 근접합니다.
|
|
85
|
+
|
|
86
|
+
## 프로젝트 구조 · Repository Structure
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
credit-survival-analysis/
|
|
90
|
+
├── src/credit_surv/
|
|
91
|
+
│ ├── data_loader.py # 실데이터 로더, 합성 패널, long → 생존형식 변환
|
|
92
|
+
│ └── models.py # KM, Cox, AFT, RSF, C-index, Brier
|
|
93
|
+
├── notebooks/01_credit_survival.ipynb # KM → Cox → PH 검정 → AFT → RSF → 검증 비교 (실행 결과 포함)
|
|
94
|
+
├── tests/test_models.py # 64개 테스트, 커버리지 90% 미만이면 CI 실패
|
|
95
|
+
├── docs/ARCHITECTURE.md # 수식과 설계
|
|
96
|
+
└── pyproject.toml
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## 개발 · Development
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
pip install -e ".[dev]"
|
|
103
|
+
ruff check src tests
|
|
104
|
+
pytest --cov --cov-fail-under=90
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
CI는 Python 3.11·3.12에서 린트·테스트·커버리지를 검사하고, sdist·wheel을 빌드해 `twine check`와 설치 스모크 테스트를 수행합니다.
|
|
108
|
+
|
|
109
|
+
## 참고문헌 · References
|
|
110
|
+
|
|
111
|
+
- Cox, D. R. (1972). Regression models and life-tables. *JRSS-B*, 34(2), 187–202.
|
|
112
|
+
- Breslow, N. (1974). Covariance analysis of censored survival data. *Biometrics*, 30(1), 89–99.
|
|
113
|
+
- Harrell, F. E. et al. (1982). Evaluating the yield of medical tests. *JAMA*, 247(18), 2543–2546.
|
|
114
|
+
- Grambsch, P. M., & Therneau, T. M. (1994). Proportional hazards tests and diagnostics based on weighted residuals. *Biometrika*, 81(3), 515–526.
|
|
115
|
+
- Graf, E. et al. (1999). Assessment and comparison of prognostic classification schemes for survival data. *Statistics in Medicine*, 18(17–18), 2529–2545.
|
|
116
|
+
- Ishwaran, H. et al. (2008). Random survival forests. *Annals of Applied Statistics*, 2(3), 841–860.
|
|
117
|
+
- Hosmer, D. W., Lemeshow, S., & May, S. (2008). *Applied Survival Analysis*. Wiley.
|
|
118
|
+
|
|
119
|
+
## 인용 · Citation
|
|
120
|
+
|
|
121
|
+
[`CITATION.cff`](CITATION.cff)를 참고하세요. GitHub 저장소 화면의 "Cite this repository"에서 BibTeX를 바로 받을 수 있습니다.
|
|
122
|
+
|
|
123
|
+
## 라이선스 · License
|
|
124
|
+
|
|
125
|
+
MIT License
|
|
126
|
+
|
|
127
|
+
## 저자 · Author
|
|
128
|
+
|
|
129
|
+
**정동수 (Dongsoo Jung)** — 서울대학교 박사과정 · 공간계량 & 금융위험
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "credit-survival"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Dependency-light survival analysis for corporate credit risk: Cox PH, AFT, Random Survival Forest, C-index and IPCW Brier score in pure numpy/scipy"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
authors = [{ name = "Dongsoo Jung", email = "jds068888@gmail.com" }]
|
|
13
|
+
keywords = [
|
|
14
|
+
"survival-analysis",
|
|
15
|
+
"credit-risk",
|
|
16
|
+
"cox-proportional-hazards",
|
|
17
|
+
"accelerated-failure-time",
|
|
18
|
+
"random-survival-forest",
|
|
19
|
+
"concordance-index",
|
|
20
|
+
"brier-score",
|
|
21
|
+
"default-prediction",
|
|
22
|
+
]
|
|
23
|
+
classifiers = [
|
|
24
|
+
"Development Status :: 4 - Beta",
|
|
25
|
+
"Intended Audience :: Science/Research",
|
|
26
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
27
|
+
"License :: OSI Approved :: MIT License",
|
|
28
|
+
"Operating System :: OS Independent",
|
|
29
|
+
"Programming Language :: Python :: 3",
|
|
30
|
+
"Programming Language :: Python :: 3.11",
|
|
31
|
+
"Programming Language :: Python :: 3.12",
|
|
32
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
33
|
+
]
|
|
34
|
+
# 모형은 numpy·scipy 만으로 구현되어 코어 설치가 가볍다.
|
|
35
|
+
dependencies = [
|
|
36
|
+
"numpy>=1.26.0",
|
|
37
|
+
"pandas>=2.1.0",
|
|
38
|
+
"scipy>=1.11.0",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.optional-dependencies]
|
|
42
|
+
parquet = ["pyarrow>=14.0.0"]
|
|
43
|
+
viz = ["matplotlib>=3.8.0"]
|
|
44
|
+
dev = [
|
|
45
|
+
"pytest>=7.4.0",
|
|
46
|
+
"pytest-cov>=4.1.0",
|
|
47
|
+
"ruff>=0.17.6,<0.18",
|
|
48
|
+
"build>=1.0.0",
|
|
49
|
+
"twine>=5.0.0",
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
[project.urls]
|
|
53
|
+
Homepage = "https://github.com/DongsooJung/credit-survival-analysis"
|
|
54
|
+
Repository = "https://github.com/DongsooJung/credit-survival-analysis"
|
|
55
|
+
Issues = "https://github.com/DongsooJung/credit-survival-analysis/issues"
|
|
56
|
+
Changelog = "https://github.com/DongsooJung/credit-survival-analysis/blob/main/CHANGELOG.md"
|
|
57
|
+
|
|
58
|
+
[tool.setuptools]
|
|
59
|
+
package-dir = { "" = "src" }
|
|
60
|
+
|
|
61
|
+
[tool.setuptools.packages.find]
|
|
62
|
+
where = ["src"]
|
|
63
|
+
|
|
64
|
+
[tool.setuptools.dynamic]
|
|
65
|
+
version = { attr = "credit_surv.__version__" }
|
|
66
|
+
|
|
67
|
+
[tool.pytest.ini_options]
|
|
68
|
+
pythonpath = ["src"]
|
|
69
|
+
testpaths = ["tests"]
|
|
70
|
+
addopts = "-ra"
|
|
71
|
+
|
|
72
|
+
[tool.coverage.run]
|
|
73
|
+
source = ["credit_surv"]
|
|
74
|
+
branch = true
|
|
75
|
+
|
|
76
|
+
[tool.coverage.report]
|
|
77
|
+
show_missing = true
|
|
78
|
+
skip_covered = true
|
|
79
|
+
|
|
80
|
+
[tool.ruff]
|
|
81
|
+
line-length = 100
|
|
82
|
+
target-version = "py311"
|
|
83
|
+
|
|
84
|
+
[tool.ruff.lint]
|
|
85
|
+
select = ["E", "F", "W", "I", "B", "UP"]
|
|
86
|
+
ignore = ["UP007", "UP045", "B905"]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Credit Survival Analysis
|
|
3
|
+
|
|
4
|
+
한국 기업의 신용위험을 생존분석(Survival Analysis)으로 모형화한다.
|
|
5
|
+
|
|
6
|
+
타깃 사건(Event):
|
|
7
|
+
- 부도(default): 회생/파산/대출원리금 90일 이상 연체
|
|
8
|
+
- 신용등급 하락: BBB- → BB+ 등 투기등급 진입
|
|
9
|
+
- 폐업/청산
|
|
10
|
+
|
|
11
|
+
추정 방법 (numpy·scipy 직접 구현):
|
|
12
|
+
1. Kaplan-Meier - 비모수 생존함수
|
|
13
|
+
2. Cox Proportional Hazards - 준모수 회귀 + Schoenfeld 비례위험 검정
|
|
14
|
+
3. AFT (Accelerated Failure Time) - Weibull / log-normal / log-logistic
|
|
15
|
+
4. Random Survival Forest (RSF) - 로그순위 분할, OOB C-index, 순열 중요도
|
|
16
|
+
(로드맵) DeepSurv, 공간 frailty
|
|
17
|
+
|
|
18
|
+
데이터 소스:
|
|
19
|
+
- DART 재무제표
|
|
20
|
+
- 한국기업데이터(KED) 신용평가
|
|
21
|
+
- KIS-Value
|
|
22
|
+
- 통계청 기업통계
|
|
23
|
+
|
|
24
|
+
이론:
|
|
25
|
+
- Cox (1972): Regression models and life-tables
|
|
26
|
+
- Ishwaran et al. (2008): Random Survival Forest
|
|
27
|
+
- Katzman et al. (2018): DeepSurv
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
__version__ = "0.2.0"
|
|
31
|
+
__author__ = "Dongsoo Jung"
|
|
32
|
+
__email__ = "jds068888@gmail.com"
|
|
33
|
+
|
|
34
|
+
from credit_surv.data_loader import ( # noqa: E402
|
|
35
|
+
load_credit_panel,
|
|
36
|
+
load_synthetic_credit_panel,
|
|
37
|
+
to_survival_format,
|
|
38
|
+
)
|
|
39
|
+
from credit_surv.models import ( # noqa: E402
|
|
40
|
+
AFTModel,
|
|
41
|
+
CoxModel,
|
|
42
|
+
KaplanMeier,
|
|
43
|
+
RSFModel,
|
|
44
|
+
SurvivalResult,
|
|
45
|
+
brier_score,
|
|
46
|
+
compare_survival_models,
|
|
47
|
+
concordance_index,
|
|
48
|
+
integrated_brier_score,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
__all__ = [
|
|
52
|
+
"AFTModel",
|
|
53
|
+
"CoxModel",
|
|
54
|
+
"KaplanMeier",
|
|
55
|
+
"RSFModel",
|
|
56
|
+
"SurvivalResult",
|
|
57
|
+
"brier_score",
|
|
58
|
+
"compare_survival_models",
|
|
59
|
+
"concordance_index",
|
|
60
|
+
"integrated_brier_score",
|
|
61
|
+
"load_credit_panel",
|
|
62
|
+
"load_synthetic_credit_panel",
|
|
63
|
+
"to_survival_format",
|
|
64
|
+
]
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""
|
|
2
|
+
신용 생존데이터 로더
|
|
3
|
+
|
|
4
|
+
생존분석 표준 형식:
|
|
5
|
+
columns:
|
|
6
|
+
- firm_id: str
|
|
7
|
+
- duration: float (관측 시작부터 사건/검열까지 기간, 일)
|
|
8
|
+
- event: 0/1 (1=부도, 0=관측 종료까지 생존)
|
|
9
|
+
- covariates: 재무비율, 산업, 거시 변수 등
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import logging
|
|
14
|
+
from typing import Literal, Optional
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
EventType = Literal["default", "downgrade", "delisting"]
|
|
22
|
+
|
|
23
|
+
# 합성 데이터의 진짜 계수 (검증 기준값)
|
|
24
|
+
TRUE_COEF = {"debt_ratio": 0.5, "roa": -0.3}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def load_credit_panel(
|
|
28
|
+
event_type: EventType = "default",
|
|
29
|
+
data_dir: str = "data/processed",
|
|
30
|
+
industries: Optional[list[str]] = None,
|
|
31
|
+
year_range: Optional[tuple[int, int]] = None,
|
|
32
|
+
) -> pd.DataFrame:
|
|
33
|
+
"""
|
|
34
|
+
신용 생존데이터 로드.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
event_type: 'default' | 'downgrade' | 'delisting'
|
|
38
|
+
data_dir: parquet 파일 경로
|
|
39
|
+
industries: KSIC 코드 필터 (예: ['C', 'F'] = 제조·건설)
|
|
40
|
+
year_range: 관측 시작 연도 범위
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
long-format 또는 단일행 형식 DataFrame
|
|
44
|
+
"""
|
|
45
|
+
import os
|
|
46
|
+
|
|
47
|
+
path = os.path.join(data_dir, f"credit_{event_type}.parquet")
|
|
48
|
+
if not os.path.exists(path):
|
|
49
|
+
raise FileNotFoundError(
|
|
50
|
+
f"{path} 없음. 합성 데이터는 load_synthetic_credit_panel() 사용."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
df = pd.read_parquet(path)
|
|
54
|
+
if industries is not None and "industry_ksic" in df.columns:
|
|
55
|
+
df = df[df["industry_ksic"].isin(industries)]
|
|
56
|
+
if year_range is not None and "obs_year" in df.columns:
|
|
57
|
+
lo, hi = year_range
|
|
58
|
+
df = df[(df["obs_year"] >= lo) & (df["obs_year"] <= hi)]
|
|
59
|
+
return df.reset_index(drop=True)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def load_synthetic_credit_panel(
|
|
63
|
+
n_firms: int = 1000,
|
|
64
|
+
max_duration: int = 365 * 5,
|
|
65
|
+
censoring_rate: float = 0.6,
|
|
66
|
+
seed: int = 42,
|
|
67
|
+
) -> pd.DataFrame:
|
|
68
|
+
"""
|
|
69
|
+
Cox 모형 검증용 합성 생존 데이터 생성.
|
|
70
|
+
|
|
71
|
+
True hazard (비례위험):
|
|
72
|
+
h(t|x) = h₀(t) × exp(0.5·debt_ratio - 0.3·roa)
|
|
73
|
+
Weibull baseline 으로 사건시간을 역변환 샘플링한다.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
n_firms: 기업 수
|
|
77
|
+
max_duration: 행정검열 시점(일)
|
|
78
|
+
censoring_rate: 목표 검열 비율(랜덤 dropout으로 근사)
|
|
79
|
+
seed: 난수 시드
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
['firm_id', 'duration', 'event', 'roa', 'debt_ratio', 'industry'] 컬럼
|
|
83
|
+
"""
|
|
84
|
+
rng = np.random.default_rng(seed)
|
|
85
|
+
|
|
86
|
+
# 표준화된 공변량
|
|
87
|
+
debt_ratio = rng.normal(0.0, 1.0, n_firms)
|
|
88
|
+
roa = rng.normal(0.0, 1.0, n_firms)
|
|
89
|
+
industry = rng.choice(["C", "F", "G", "J"], size=n_firms)
|
|
90
|
+
|
|
91
|
+
lp = TRUE_COEF["debt_ratio"] * debt_ratio + TRUE_COEF["roa"] * roa
|
|
92
|
+
|
|
93
|
+
# Weibull baseline: shape k, scale 설정. 역변환 샘플링
|
|
94
|
+
# S(t) = exp(-(lambda * t^k) * exp(lp)), T = (-ln U / (lambda e^lp))^(1/k)
|
|
95
|
+
k = 1.5
|
|
96
|
+
lam = 1.0 / (max_duration ** k) # 평균 사건시간이 관측창과 비슷하도록 스케일
|
|
97
|
+
u = rng.uniform(0.0, 1.0, n_firms)
|
|
98
|
+
event_time = (-np.log(u) / (lam * np.exp(lp))) ** (1.0 / k)
|
|
99
|
+
|
|
100
|
+
# 랜덤 검열 시간 (지수분포) — censoring_rate 근사
|
|
101
|
+
# 행정검열(max_duration)도 함께 적용
|
|
102
|
+
cens_scale = max_duration * (1.0 - censoring_rate) / max(censoring_rate, 1e-3)
|
|
103
|
+
cens_scale = max(cens_scale, max_duration * 0.1)
|
|
104
|
+
censor_time = rng.exponential(cens_scale, n_firms)
|
|
105
|
+
censor_time = np.minimum(censor_time, max_duration)
|
|
106
|
+
|
|
107
|
+
duration = np.minimum(event_time, censor_time)
|
|
108
|
+
event = (event_time <= censor_time).astype(int)
|
|
109
|
+
|
|
110
|
+
df = pd.DataFrame({
|
|
111
|
+
"firm_id": [f"F{i:05d}" for i in range(n_firms)],
|
|
112
|
+
"duration": duration,
|
|
113
|
+
"event": event,
|
|
114
|
+
"roa": roa,
|
|
115
|
+
"debt_ratio": debt_ratio,
|
|
116
|
+
"industry": industry,
|
|
117
|
+
})
|
|
118
|
+
logger.info(
|
|
119
|
+
"합성 패널 생성: n=%d, 사건=%d (%.1f%%), 검열=%.1f%%",
|
|
120
|
+
n_firms, event.sum(), 100 * event.mean(), 100 * (1 - event.mean()),
|
|
121
|
+
)
|
|
122
|
+
return df
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def to_survival_format(
|
|
126
|
+
transactions: pd.DataFrame,
|
|
127
|
+
firm_id_col: str = "firm_id",
|
|
128
|
+
start_col: str = "obs_start",
|
|
129
|
+
event_col: str = "default_date",
|
|
130
|
+
censor_date: Optional[pd.Timestamp] = None,
|
|
131
|
+
) -> pd.DataFrame:
|
|
132
|
+
"""
|
|
133
|
+
Long-format → 생존 표준 (duration, event) 형식 변환.
|
|
134
|
+
|
|
135
|
+
각 기업의 관측 시작일과 사건일(있으면)로 duration·event를 계산한다.
|
|
136
|
+
사건일이 없으면 censor_date(기본: 전체 최대 사건일)로 검열 처리.
|
|
137
|
+
|
|
138
|
+
Args:
|
|
139
|
+
transactions: 기업별 [firm_id, obs_start, default_date(optional)] 포함
|
|
140
|
+
censor_date: 검열 기준일 (None이면 관측된 사건일의 최댓값)
|
|
141
|
+
|
|
142
|
+
Returns:
|
|
143
|
+
['firm_id', 'duration', 'event'] DataFrame
|
|
144
|
+
"""
|
|
145
|
+
df = transactions.copy()
|
|
146
|
+
df[start_col] = pd.to_datetime(df[start_col])
|
|
147
|
+
if event_col in df.columns:
|
|
148
|
+
df[event_col] = pd.to_datetime(df[event_col])
|
|
149
|
+
|
|
150
|
+
# 기업별 첫 관측일 / 사건일
|
|
151
|
+
grouped = df.groupby(firm_id_col)
|
|
152
|
+
start = grouped[start_col].min()
|
|
153
|
+
event_date = (
|
|
154
|
+
grouped[event_col].min()
|
|
155
|
+
if event_col in df.columns
|
|
156
|
+
else pd.Series(pd.NaT, index=start.index)
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
if censor_date is None:
|
|
160
|
+
valid = event_date.dropna()
|
|
161
|
+
censor_date = valid.max() if len(valid) else start.max()
|
|
162
|
+
censor_date = pd.Timestamp(censor_date)
|
|
163
|
+
|
|
164
|
+
end = event_date.where(event_date.notna(), censor_date)
|
|
165
|
+
event = event_date.notna().astype(int)
|
|
166
|
+
duration = (end - start).dt.days.astype(float)
|
|
167
|
+
|
|
168
|
+
out = pd.DataFrame({
|
|
169
|
+
"firm_id": start.index,
|
|
170
|
+
"duration": duration.values,
|
|
171
|
+
"event": event.values,
|
|
172
|
+
}).reset_index(drop=True)
|
|
173
|
+
# 음수/0 duration 방지
|
|
174
|
+
out = out[out["duration"] >= 0].reset_index(drop=True)
|
|
175
|
+
return out
|