Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions docs/PAPER_MONTH1_REVIEW_AND_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,22 +129,46 @@ KS11 +0.71% ┘ = 균등가중 10종목 vs 반도체 쏠림 시총
C안(현상 유지)이 차선인 이유: 61% 배치로 60일을 완주해도 "설계와 다른 것"의 기록이라
평가 가치가 낮다. 게다가 이번 달로 C의 비용(-1.5%p/월 수준)이 실측됐다.

### 자본 숫자는 결정 시점에 재계산할 것 (2026-07-06 추가)

위 표의 숫자는 작성 시점(7/2, 하이닉스 242.4만) 시세다. 7/6 시세(232.2만)로는 **32M이
34M보다 우수**(배치율 77.4% vs 74.5%, 여유 +10.2%)로 뒤집혔다 — 정수 절사의 톱니 효과
때문에 최적 자본은 시세와 함께 움직인다. 그래서 고정 숫자 대신 도구와 기준으로 결정한다:

```powershell
# 결정 시점의 실시간 시세로 자본별 채움율 재계산 (읽기 전용)
.venv\Scripts\python.exe tools/capital_slot_simulator.py
.venv\Scripts\python.exe tools/capital_slot_simulator.py --capital 32000000 # 단일 상세
```

**선택 기준**: ① 미체결 0개, ② 총 배치율이 설계 대비 -5%p 이내(헬스 ATTENTION 임계값과
동일), ③ 하이닉스 채움율 ≤ 92% (가격이 +8~10% 올라도 미체결로 안 돌아갈 여유) — 를
만족하는 **최소 자본**. live 투입 예정 실자본을 이미 안다면 그 금액이 항상 최우선이다.

### 실행 절차 (#427 도구로 준비 완료 — 가역·비파괴)

```powershell
# 1) config/baskets.yaml의 kr_diversified_hold에 한 줄 추가: initial_capital: 34000000
# 1) config/baskets.yaml의 kr_diversified_hold에 한 줄 추가: initial_capital: <결정 금액>
# 2) dry-run으로 이전 대상 확인
.venv\Scripts\python.exe tools/restart_basket_track_record.py --basket kr_diversified_hold
# 3) 적용 — 기존 17일 기록은 @archived-<날짜> 키로 이전(삭제 아님, --undo 가능)
.venv\Scripts\python.exe tools/restart_basket_track_record.py --basket kr_diversified_hold --apply
# 4) 다음 일일 사이클(10:07)부터 새 자본으로 초기 매입, 트랙레코드 0/60 재시작
```

**재시작일 주의 — 사이클을 하루 여러 번 돌리지 말 것**: 6/10의 진입 타이밍 비용(-1%p)은
그날 사이클이 4회 수동 실행돼(10:01~13:58) 하루에 61%를 몰아 산 것이 원인이었다. 정상
자동화(1일 1사이클)에서는 회전 상한(15%/일)이 초기 매입을 5~6거래일에 걸쳐 자연 분할한다
— P2-9(분할 진입 기능)는 별도 코드가 필요 없다. 재시작 당일 결과가 "일부만 매수"로 보여도
정상이며, 배치율 게이지가 수렴 과정을 보여준다. (11:00/14:00 재시도 크론은 스냅샷 결측
시에만 재실행하므로 진입을 가속하지 않는다.)

**트레이드오프를 정직하게**: 17일 기록을 아카이브하고 0/60부터 다시 센다. 아깝지만 —
(a) 17일은 전체의 28%이고, (b) 그 17일은 "설계와 다른 배치"의 기록이며, (c) 평가 문서가
말하듯 늦출수록 버리는 기록만 커진다. 지금이 손실 최소 시점이다.
**순서 주의**: 재시작 후 또 6/26류 결측이 나면 커버리지 게이트(95%)가 다시 위험해지므로,
P0-1(하트비트·재시도)을 먼저 머지하고 재시작하는 순서를 권장한다 (§5 일정).
→ (2026-07-06) P0-1 머지 + 재시도 크론 설정 완료 — 재시작 전제조건 충족.

---

Expand Down Expand Up @@ -230,7 +254,7 @@ P0-1(하트비트·재시도)을 먼저 머지하고 재시작하는 순서를
| # | 항목 | 축 | 내용 |
|---|---|---|---|
| 8 | kr_balanced_5050 병행 트랙레코드 | 안정성 | 50/50 배분을 같은 기간 paper로 병행 — 승격 시점에 "80% vs 50%" 실측 비교군 확보. 기능은 이미 구현됨(enabled만). |
| 9 | 분할 진입 옵션 (기본 off) | 수익성 | 6/10 하루 일괄 매입의 타이밍 비용(-1%p) 재발 방지용으로 초기 매입 2~3분할 옵션. 상승장 기회비용이라는 반대급부를 문서에 명시하고 기본은 끈다 — 재시작·live 첫 매입에만 검토. |
| 9 | ~~분할 진입 옵션~~ → **코드 불필요로 종결** (2026-07-06) | 수익성 | 원인 재분석 결과 6/10 타이밍 비용(-1%p)은 그날 사이클 4회 수동 실행으로 하루 61% 집중 매입한 것이 원인. 정상 자동화(1일 1사이클)는 회전 상한 15%/일이 초기 매입을 5~6거래일 자연 분할한다 — 별도 기능 대신 §3 재시작 절차에 "하루 여러 번 돌리지 말 것" 명시로 대체. |
| 10 | 승격 게이트 현황판 완성 | 편의성 | #423 대시보드에 4개 축(기간/커버리지/미해결 주문/비용) 진행률 게이지. |
| 11 | 월간 리허설 유지 | 안정성 | 금요일 복원 리허설 + KIS 모의서버 live 경로 리허설(게이트 통과 전 실계좌 불가는 유지). |

Expand Down Expand Up @@ -299,7 +323,11 @@ P0-1(하트비트·재시도)을 먼저 머지하고 재시작하는 순서를
.venv\Scripts\python.exe main.py --mode health
# 배포 전 점검
.venv\Scripts\python.exe main.py --mode deploy_check
# 자본별 슬롯 채움 시뮬레이션 (자본 결정 지원, 실시간 시세, 읽기 전용)
.venv\Scripts\python.exe tools/capital_slot_simulator.py
# 트랙레코드 재시작 (자본 결정 후)
.venv\Scripts\python.exe tools/restart_basket_track_record.py --basket kr_diversified_hold # dry-run
.venv\Scripts\python.exe tools/restart_basket_track_record.py --basket kr_diversified_hold --apply # 적용
# 주간 요약 리포트 (금 16:00 크론 설정됨 — 수동 실행도 가능)
.venv\Scripts\python.exe main.py --mode weekly_report
```
74 changes: 74 additions & 0 deletions tests/test_capital_slot_simulator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""tools/capital_slot_simulator.py — 자본별 슬롯 채움 계산(순수 함수) 단위 테스트."""

from tools.capital_slot_simulator import format_simulation, simulate_slot_fills


HOLDINGS = {"A": 0.5, "B": 0.5}


class TestSimulateSlotFills:
def test_basic_fill(self):
# 자본 10M, 주식 80% → 슬롯 4M씩. A 1주 1M → 4주(100%), B 1주 3M → 1주(75%)
out = simulate_slot_fills(HOLDINGS, 10_000_000, 0.8, {"A": 1_000_000, "B": 3_000_000})
by = {s["symbol"]: s for s in out["slots"]}
assert by["A"]["shares"] == 4 and by["A"]["fill_ratio"] == 1.0
assert by["B"]["shares"] == 1 and round(by["B"]["fill_ratio"], 2) == 0.75
assert out["unfillable_count"] == 0
# 배치율 = (4M + 3M) / 10M = 70%
assert round(out["deployment_ratio"], 2) == 0.70

def test_unfillable_when_share_exceeds_slot(self):
# B 1주 5M > 슬롯 4M → 미체결
out = simulate_slot_fills(HOLDINGS, 10_000_000, 0.8, {"A": 1_000_000, "B": 5_000_000})
by = {s["symbol"]: s for s in out["slots"]}
assert by["B"]["unfillable"] is True
assert "1주" in by["B"]["reason"]
assert out["unfillable_count"] == 1

def test_unfillable_when_slot_below_min_trade(self):
# 슬롯 4M < 최소거래 5M → 미체결 (가격은 저렴해도)
out = simulate_slot_fills(
HOLDINGS, 10_000_000, 0.8, {"A": 1_000, "B": 1_000}, min_trade_amount=5_000_000,
)
assert out["unfillable_count"] == 2
assert all("최소거래" in s["reason"] for s in out["slots"])

def test_missing_price_is_unknown_not_unfillable(self):
out = simulate_slot_fills(HOLDINGS, 10_000_000, 0.8, {"A": 1_000_000}) # B 가격 없음
by = {s["symbol"]: s for s in out["slots"]}
assert by["B"]["unfillable"] is False
assert by["B"]["reason"] == "가격 조회 불가"
assert out["unknown_count"] == 1

def test_weights_renormalized(self):
# 비중 합 2.0 → 정규화 후 각 50%
out = simulate_slot_fills({"A": 1.0, "B": 1.0}, 10_000_000, 1.0, {"A": 1, "B": 1})
assert all(round(s["weight"], 2) == 0.5 for s in out["slots"])

def test_month1_hynix_case(self):
# 실측 재현: 자본 10M·주식 80%·10종목 → 하이닉스 슬롯 80만 < 1주 204.8만 → 미체결
holdings = {f"S{i}": 0.1 for i in range(9)}
holdings["000660"] = 0.1
prices = {f"S{i}": 100_000 for i in range(9)}
prices["000660"] = 2_048_000
out = simulate_slot_fills(holdings, 10_000_000, 0.8, prices)
hynix = next(s for s in out["slots"] if s["symbol"] == "000660")
assert hynix["unfillable"] is True
# 34M이면 슬롯 272만 ≥ 1주 → 채움
out34 = simulate_slot_fills(holdings, 34_000_000, 0.8, prices)
hynix34 = next(s for s in out34["slots"] if s["symbol"] == "000660")
assert hynix34["shares"] == 1 and hynix34["unfillable"] is False


class TestFormatSimulation:
def test_table_contains_key_lines(self):
out = simulate_slot_fills(HOLDINGS, 10_000_000, 0.8, {"A": 1_000_000, "B": 5_000_000})
text = format_simulation("kr_x", 10_000_000, out)
assert "kr_x" in text and "10,000,000" in text
assert "미체결 1개" in text
assert "총 배치율" in text

def test_all_fillable_message(self):
out = simulate_slot_fills(HOLDINGS, 10_000_000, 0.8, {"A": 1_000_000, "B": 1_000_000})
text = format_simulation("kr_x", 10_000_000, out)
assert "전 슬롯 매수 가능" in text
173 changes: 173 additions & 0 deletions tools/capital_slot_simulator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
"""자본 규모별 바스켓 슬롯 채움 시뮬레이터 — 자본 결정(#422 A안) 지원 도구.

배경(docs/PAPER_MONTH1_REVIEW_AND_PLAN.md §3): 자본이 작으면 고가 종목 슬롯이
정수 주식 절사로 못 채워진다(예: 자본 1,000만 → 하이닉스 슬롯 80만 < 1주 2백만대).
문서의 자본별 표는 작성 시점 시세로 고정이라, 결정 시점의 **실시간 시세**로
재계산해주는 읽기 전용 도구다. 주문·DB 변경 없음.

사용:
.venv\\Scripts\\python.exe tools/capital_slot_simulator.py # 기본 스윕
.venv\\Scripts\\python.exe tools/capital_slot_simulator.py --capital 34000000 # 단일 자본 상세
.venv\\Scripts\\python.exe tools/capital_slot_simulator.py --basket kr_diversified_hold --capitals 30000000,34000000,62000000
"""

import argparse
import sys
from pathlib import Path
from typing import Any

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from loguru import logger # noqa: E402


def simulate_slot_fills(
holdings: dict[str, float],
capital: float,
stock_fraction: float,
prices: dict[str, float],
min_trade_amount: float = 0.0,
) -> dict[str, Any]:
"""자본 capital에서 각 슬롯의 채움율을 계산한다(순수 함수).

슬롯 금액 = capital × stock_fraction × (목표비중/비중합). 채움 주수 = floor(슬롯/가격).
1주도 못 사거나 슬롯이 min_trade_amount 미만이면 미체결(unfillable)로 표시한다
— BasketRebalancer의 매수 판정과 같은 기준. 가격이 없거나 0 이하인 종목은
판정 불가(unknown)로 분리한다(미체결로 오표기 방지).

반환: {"slots": [{symbol, weight, slot_amount, price, shares, fill_amount,
fill_ratio, unfillable, reason}...], "deployment_ratio", # 총자산 대비
"design_fraction", "unfillable_count", "unknown_count"}
"""
total_w = sum(float(w) for w in holdings.values())
slots: list[dict[str, Any]] = []
filled_total = 0.0
unfillable = 0
unknown = 0

for symbol, weight in holdings.items():
wn = (float(weight) / total_w) if total_w > 0 else 0.0
slot_amount = float(capital) * float(stock_fraction) * wn
price = float(prices.get(symbol) or 0)
row: dict[str, Any] = {
"symbol": symbol, "weight": wn, "slot_amount": slot_amount,
"price": price, "shares": 0, "fill_amount": 0.0, "fill_ratio": 0.0,
"unfillable": False, "reason": "",
}
if price <= 0:
row["reason"] = "가격 조회 불가"
unknown += 1
else:
shares = int(slot_amount // price)
if slot_amount < min_trade_amount:
row["unfillable"] = True
row["reason"] = f"슬롯 {slot_amount:,.0f} < 최소거래 {min_trade_amount:,.0f}"
unfillable += 1
elif shares <= 0:
row["unfillable"] = True
row["reason"] = f"1주 {price:,.0f} > 슬롯 {slot_amount:,.0f}"
unfillable += 1
else:
row["shares"] = shares
row["fill_amount"] = shares * price
row["fill_ratio"] = (shares * price) / slot_amount if slot_amount > 0 else 0.0
filled_total += shares * price
slots.append(row)

return {
"slots": slots,
"deployment_ratio": (filled_total / capital) if capital > 0 else 0.0,
"design_fraction": float(stock_fraction),
"unfillable_count": unfillable,
"unknown_count": unknown,
}


def format_simulation(basket_name: str, capital: float, result: dict[str, Any]) -> str:
"""시뮬레이션 결과를 사람이 읽는 표로 포맷한다(순수 함수)."""
lines = [
"=" * 72,
f" 자본 {capital:,.0f}원 — 바스켓 '{basket_name}' 슬롯 채움 시뮬레이션",
"=" * 72,
f" {'종목':<8} {'비중':>5} {'슬롯금액':>12} {'1주가격':>12} {'주수':>4} {'채움율':>7} 비고",
]
for s in result["slots"]:
mark = "❌" if s["unfillable"] else ("❓" if s["price"] <= 0 else " ")
lines.append(
f" {s['symbol']:<8} {s['weight']:>5.0%} {s['slot_amount']:>12,.0f} "
f"{s['price']:>12,.0f} {s['shares']:>4} {s['fill_ratio']:>7.1%} {mark}{s['reason']}"
)
dep = result["deployment_ratio"]
design = result["design_fraction"]
lines.append("-" * 72)
lines.append(
f" 총 배치율 {dep:.1%} / 설계 {design:.0%} ({(dep - design) * 100:+.1f}%p) · "
f"미체결 {result['unfillable_count']}개"
+ (f" · 가격불명 {result['unknown_count']}개" if result["unknown_count"] else "")
)
if result["unfillable_count"] == 0 and result["unknown_count"] == 0:
lines.append(" → 이 자본이면 전 슬롯 매수 가능 (절사 잔여만 남음)")
lines.append("=" * 72)
return "\n".join(lines)


def main() -> int:
parser = argparse.ArgumentParser(description="자본 규모별 바스켓 슬롯 채움 시뮬레이터 (읽기 전용)")
parser.add_argument("--basket", type=str, default=None,
help="대상 바스켓 (미지정 시 enabled 바스켓, 정확히 1개여야 함)")
parser.add_argument("--capital", type=float, default=None, help="단일 자본 금액")
parser.add_argument(
"--capitals", type=str,
default="10000000,30000000,32000000,34000000,40000000,62000000",
help="쉼표 구분 자본 스윕 (기본: 문서 §3 표의 구간)",
)
args = parser.parse_args()

from config.config_loader import Config
from core.basket_rebalancer import BasketRebalancer

config = Config.get()
basket_name = args.basket
if not basket_name:
enabled = BasketRebalancer.get_enabled_baskets()
if len(enabled) != 1:
logger.error("대상 바스켓이 모호합니다 (enabled={}) — --basket으로 지정하세요.", enabled)
return 1
basket_name = enabled[0]

basket_cfg = BasketRebalancer._load_baskets_config().get(basket_name)
if not basket_cfg:
logger.error("바스켓 '{}' 설정 없음 (config/baskets.yaml)", basket_name)
return 1
holdings = basket_cfg.get("holdings") or {}
min_trade = float((basket_cfg.get("rebalance") or {}).get("min_trade_amount", 0) or 0)

min_cash = (config.risk_params.get("diversification") or {}).get("min_cash_ratio", 0.20)
max_stock = 1.0 - float(min_cash)
tsw = basket_cfg.get("target_stock_weight")
stock_fraction = max_stock if tsw is None else max(0.0, min(float(tsw), max_stock))

# 현재가 조회 (읽기 전용) — 실제 사이클과 동일 소스(BasketRebalancer 시세 경로) 재사용.
rebalancer = BasketRebalancer(basket_name=basket_name, config=config)
prices: dict[str, float] = rebalancer._fetch_current_prices()
missing = [s for s in holdings if s not in prices]
if missing:
logger.warning("가격 조회 실패 종목: {} — 해당 슬롯은 '가격 조회 불가'로 표시", missing)

capitals = (
[float(args.capital)] if args.capital
else [float(c) for c in args.capitals.split(",") if c.strip()]
)
for capital in capitals:
result = simulate_slot_fills(holdings, capital, stock_fraction, prices, min_trade)
print(format_simulation(basket_name, capital, result))

print(
"\n참고: 실효 배치율은 여기서 계산한 값에서 리밸런싱 회전 상한(1일 15%)에 따라\n"
"수 거래일에 걸쳐 수렴한다. 자본 결정 후 절차는 docs/PAPER_MONTH1_REVIEW_AND_PLAN.md §3."
)
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading