Metadata-Version: 2.3
Name: koreaalpha-core
Version: 0.2.0
Summary: Korean stock market portfolio analysis engine — Sharpe, MDD, backtest, benchmarks, Korean trading calendar
Project-URL: Homepage, https://github.com/dankang21/koreaalpha-core
Project-URL: Repository, https://github.com/dankang21/koreaalpha-core
Project-URL: Issues, https://github.com/dankang21/koreaalpha-core/issues
Author-email: Daniel Kang <dankang21@gmail.com>
License: MIT License
        
        Copyright (c) 2026 Daniel Kang
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: all-weather,backtest,benchmark,finance,investment,korea,kospi,mdd,portfolio,sharpe-ratio,stock
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: korean-holidays>=0.1.0
Requires-Dist: numpy>=1.26.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.9.0; extra == 'dev'
Description-Content-Type: text/markdown

# koreaalpha-core

**Korean stock market portfolio analysis engine**

한국 주식시장 특화 포트폴리오 분석 엔진. 순수 수학/통계 계산 라이브러리입니다.

[![Python](https://img.shields.io/pypi/pyversions/koreaalpha-core)](https://pypi.org/project/koreaalpha-core/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Tests](https://img.shields.io/badge/tests-83%20passed-brightgreen)]()

## Features

- **Portfolio Metrics (28개)** — CAGR, Sharpe, Sortino, MDD, Calmar, Beta, VaR, CVaR, Alpha, Omega, Skewness, Kurtosis 등
- **Rolling Indicators** — Rolling Sharpe, Volatility, Beta (차트 시각화용)
- **Backtesting** — 리밸런싱, 거래비용, 슬리피지, 한국 거래일 기반, 배당 재투자
- **Benchmark Comparison** — 순수 비교 로직 + 등급(A+~F) 계산 (벤치마크 데이터는 서비스에서 정의)
- **Fundamental** — PER, PBR, ROE, ROA, FCF yield (적자 PER 음수 반환 지원)
- **Korean Market** — 한국 거래일 자동 계산, 증권거래세, 배당세, 해외양도세, 세후 수익률
- **Zero pandas dependency** — numpy만 사용, 경량

## Installation

```bash
pip install -e .  # 로컬 설치 (private 패키지)
```

## Quick Start

### Portfolio Metrics

```python
from koreaalpha_core import calculate_all_metrics

prices = [1000, 1020, 1015, 1050, 1080, 1070, 1100, ...]
metrics = calculate_all_metrics(prices)

metrics.cagr           # 연평균 성장률
metrics.sharpe_ratio   # 샤프 비율
metrics.sortino_ratio  # 소르티노 비율
metrics.mdd            # 최대 낙폭
metrics.volatility     # 연환산 변동성
metrics.calmar_ratio   # CAGR / |MDD|
```

### Rolling Indicators

```python
from koreaalpha_core import calculate_returns, rolling_sharpe, rolling_volatility

returns = calculate_returns(prices)
rs = rolling_sharpe(returns, window=60)     # 60일 이동 샤프
rv = rolling_volatility(returns, window=20) # 20일 이동 변동성
```

### Risk Metrics

```python
from koreaalpha_core import calculate_var, calculate_cvar, calculate_skewness, drawdown_series

var = calculate_var(returns, 0.95)    # 95% VaR
cvar = calculate_cvar(returns, 0.95)  # 95% CVaR (Expected Shortfall)
sk = calculate_skewness(returns)      # 왜도 (음수 = 급락 리스크)
dd = drawdown_series(prices)          # 전체 Drawdown 시계열
```

### Benchmark Comparison

```python
from koreaalpha_core import compare_with_benchmark

# 벤치마크 이름과 가격 데이터를 서비스에서 전달
result = compare_with_benchmark(
    user_prices=[...],
    benchmark_prices=[...],
    benchmark_name="올웨더 포트폴리오",
)
print(f"등급: {result.grade}")       # A+, A, B+, B, C, D, F
print(f"Sharpe 차이: {result.sharpe_diff:+.4f}")
print(f"CAGR 차이: {result.cagr_diff:+.2%}")
```

### Backtesting

```python
from koreaalpha_core import run_backtest, BacktestConfig

result = run_backtest(
    asset_prices={"삼성전자": [...], "SK하이닉스": [...]},
    allocations={"삼성전자": 0.6, "SK하이닉스": 0.4},
    config=BacktestConfig(
        initial_capital=10_000_000,
        rebalance_period="quarterly",      # monthly/quarterly/yearly/none
        transaction_cost_pct=0.0015,
        use_kr_trading_days=True,          # 한국 거래일 기반 리밸런싱
        dividend_reinvest=True,            # 배당 재투자
        dividend_yields={"삼성전자": 0.02},
    ),
    dates=["20240102", "20240103", ...],
)
print(f"최종 가치: {result.portfolio_values[-1]:,.0f}원")
print(f"Sharpe: {result.metrics.sharpe_ratio:.2f}")
```

### Korean Market

```python
from datetime import date
from koreaalpha_core import (
    is_kr_trading_day, count_trading_days,
    calc_transaction_cost, calc_dividend_tax, calc_after_tax_return,
)

# 거래일 (korean-holidays 패키지 위임 — 아무 연도든 자동 계산)
is_kr_trading_day(date(2030, 1, 1))  # False (신정)
count_trading_days(date(2026, 1, 1), date(2026, 12, 31))  # ~248일

# 거래 비용 (세율은 파라미터로 override 가능)
cost = calc_transaction_cost(10_000_000, is_sell=True)  # 기본 0.18%
cost = calc_transaction_cost(10_000_000, is_sell=True, securities_tax_rate=0.0015)  # 세율 변경

# 배당소득세
tax = calc_dividend_tax(25_000_000)
# {"gross": 25000000, "tax": 3850000, "net": 21150000, "is_over_threshold": True}
tax = calc_dividend_tax(25_000_000, tax_rate=0.14)  # 세율 override

# 세후 수익률
result = calc_after_tax_return(0.10, 100_000_000, dividend_income=5_000_000)
# {"gross_return": 0.1, "after_tax_return": 0.09923, "total_tax": 770000}
```

### Fundamental Analysis

```python
from koreaalpha_core import calculate_all_fundamentals

metrics = calculate_all_fundamentals(
    price=55000, eps=5000, bps=40000,
    net_income=30e9, equity=200e9,
    total_assets=400e9, total_liabilities=200e9,
    revenue=300e9, operating_income=45e9,
    fcf=25e9, market_cap=330e12,
)
print(f"PER: {metrics.per}")           # 11.0 (적자 시 음수 반환)
print(f"ROE: {metrics.roe:.2%}")       # 15.00%
print(f"부채비율: {metrics.debt_ratio:.2%}")  # 100.00%
```

### More

```python
from koreaalpha_core import (
    calculate_alpha,           # Jensen's Alpha
    calculate_information_ratio,  # 정보비율
    calculate_omega_ratio,     # Omega Ratio
    calculate_tail_ratio,      # Tail Ratio
    monthly_returns,           # 월별 수익률 매트릭스
    annual_returns,            # 연도별 수익률
    longest_streak,            # 최장 연속 승/패
    correlation_matrix,        # N×N 상관계수 매트릭스
    grade_portfolio,           # 벤치마크 대비 등급 (A+~F)
    compare_with_multiple,     # 여러 벤치마크 동시 비교
)
```

## Architecture

```
korean-holidays (PyPI, MIT)
  └── 음력 변환 + 대체휴일 자동 계산
       ↑
koreaalpha-core (private, Proprietary)
  ├── portfolio/metrics.py   — 28개 분석 함수
  ├── portfolio/backtest.py  — 백테스트 엔진
  ├── portfolio/benchmark.py — 순수 비교 로직 (데이터 없음)
  ├── stock/fundamental.py   — 펀더멘탈 지표
  ├── kr_market.py           — 거래비용/세금 (파라미터화)
  ├── utils/                 — 포맷팅/검증
  └── 83개 테스트
```

## Design Principles

- **순수 계산 라이브러리** — API 호출, DB 접속, 인증 없음
- **데이터와 로직 분리** — 벤치마크 정의, 공휴일, 색상은 서비스 레벨에서 관리
- **세율은 기본값 + override** — 정책 변경 시 호출 측에서 파라미터로 변경
- **pandas 미의존** — numpy만 사용, 경량
- **한국 시장 기본값** — TRADING_DAYS=248, 무위험수익률=3.5%

## Comparison with Alternatives

| Feature | koreaalpha-core | quantstats | empyrical |
|---------|:---:|:---:|:---:|
| Korean trading calendar | O | X | X |
| Transaction tax (parameterized) | O | X | X |
| Dividend/CGT tax calculator | O | X | X |
| Backtesting with KR holidays | O | X | X |
| VaR/CVaR/Skewness/Kurtosis | O | O | O |
| Rolling indicators | O | O | X |
| Fundamental analysis | O | X | X |
| pandas-free | O | X | X |
| Data-logic separation | O | X | X |

## Disclaimer

이 라이브러리는 투자 분석을 위한 기술적 도구이며, 투자 권유 또는 금융 서비스를 제공하지 않습니다. 투자 판단의 책임은 이용자에게 있습니다.

This library is a technical tool for investment analysis and does not provide investment advice or financial services.

## License

MIT License. See [LICENSE](LICENSE).
