주요 변경:
- tools/build_rebalance_engine_v1.py: REBALANCE_ENGINE_V1 신규
* account_snapshot 직접 합산(_build_snap_position_map) → 소수주 분리 행 병합
* 레짐 소스 macro.REGIME_PRELIM 최우선 (GAS 와 동일)
- src/gas_adapter_parts/gdf_06_rebalance.gs: runRebalanceSheet_() 신규
* Logger.log / getSpreadsheet_() 로 run_all 연동 수정
- src/gas_adapter_parts/gdc_01_fetch_fundamentals.gs
* _mergePositionRecord_(): 소수주 중복 행 합산 신규
* parseInt → parseFloat (qty, availQty)
- src/gas_adapter_parts/gdf_01_price_metrics.gs
* 미보유 종목 SELL_READY → WATCH_EXIT_SIGNAL
- spec/41_release_dag.yaml: build_rebalance_sheet 노드 추가 (step_count 63)
- spec/51_formula_lifecycle_registry.yaml: REBALANCE_ENGINE_V1 등록
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
| `regime_size_scale` | **[N1 POSITION_SIZE_REGIME_SCALE_V1]** GAS 산출 국면 매수 스케일(0.25~1.2). buy_qty_inputs_json에 이미 적용됨. LLM 재계산·무시 금지. |
| `regime_cash_uplift_min_pct` | **[N5 REGIME_CASH_UPLIFT_V1]** 국면 상향 적용 후 실제 현금 최소 비율. cash_floor_min_pct보다 높을 수 있음. LLM이 이 값을 낮추거나 무시 금지. |
| `single_position_weight_gate` | **[O1 SINGLE_POSITION_WEIGHT_CAP_V1]** OVERWEIGHT_TRIM → 해당 종목 추가 BUY 금지. `single_position_weight_json`에서 초과 종목 확인. |
| `semiconductor_cluster_gate` | **[O2 SEMICONDUCTOR_CLUSTER_GATE_V1]** CLUSTER_BLOCK → 005930·000660 신규 BUY 모두 금지. combined_pct가 상한 초과. |
| `portfolio_drawdown_gate` | **[O3 PORTFOLIO_DRAWDOWN_GATE_V1]** DRAWDOWN_FORCE_RISK_OFF → 신규 BUY 전면 금지. DRAWDOWN_CAUTION → 신규 매수 보류 권고. |
| `win_loss_streak_state` | **[O4 WIN_LOSS_STREAK_GUARD_V1]** EDGE_CRITICAL/EDGE_DEGRADED/EDGE_WEAK → 매수 스케일 이미 적용됨. LLM 복원 금지. |
| `position_count_gate` | **[O5 POSITION_COUNT_LIMIT_V1]** POSITION_COUNT_BLOCK → 신규 BUY 종목 추가 금지. 기존 HOLD/SELL만 허용. |
| `stop_breach_gate` | **[P1 STOP_BREACH_ALERT_V1]** BREACH → 해당 종목 즉각 매도 검토. APPROACHING → 손절가 근접 경보. `stop_breach_alert_json`에서 gap_pct 확인. |
| `tp_trigger_gate` | **[P2 TP_TRIGGER_ALERT_V1]** TRIGGERED → `tp_trigger_alert_json`의 tp1_qty/tp2_qty를 그대로 매도 수량 사용. LLM 임의 조정 금지. |
| `heat_concentration_gate` | **[P3 HEAT_CONCENTRATION_ALERT_V1]** HEAT_CONCENTRATED → 해당 종목 추가 매수 금지. `heat_concentration_json`에서 heat_share_pct 확인. |
| `portfolio_health_label` | **[P5 PORTFOLIO_HEALTH_SCORE_V1] 보고서 첫 줄 필수 표시.** CRITICAL → 긴급 주의 섹션 먼저 출력. `portfolio_health_blocked_json`에서 활성 게이트 열거. |
| `allowed_actions` | 이 목록의 주문 유형만 생성 가능. |
| `blocked_actions` | 이 목록의 주문 유형은 어떤 이유로도 생성 금지. |
**H2 — 매도후보 순위 (`sell_priority_lock = true`):**
| harness 필드 | LLM 의무 |
|---|---|
| `sell_candidates_json` | GAS 산출 tier·score 순위 그대로 출력. 재정렬·점수 변경 절대 금지. |
| `sell_priority_lock` | `true` → 산문으로 순위 재해석·변경 금지. |
| `clamp_label` (각 후보) | 값이 있으면 `[CLAMP 발동: raw=N → 100]` 표기 필수. |
**H3 — 수량 (`quantities_lock = true`):**
| harness 필드 | LLM 의무 |
|---|---|
| `sell_quantities_json` | GAS 산출 Sell_Qty 그대로 사용. `CAPTURE_REQUIRED`는 그대로 기재. |
| `buy_qty_inputs_json` | `final_qty`가 있으면 매수수량으로 사용. `NO_BUY_QUANTITY`이면 수량 출력 금지. |
| `quantities_lock` | `true` → 수량 재계산·역산 절대 금지. |
**H4 — 가격 (`prices_lock = true`):**
| harness 필드 | LLM 의무 |
|---|---|
| `prices_json` | `stop_price`·`tp1_price`·`tp2_price` 그대로 HTS 표에 기재. |
| `prices_lock` | `true` → tick 재정규화·가격 임의 조정 절대 금지. |
| `cash_ledger_basis` | D2_ONLY | D+2 정산현금 단독 기준 확인 |
> **PENDING_EXPORT 해석 금지:** `json_validation_status=PENDING_EXPORT`를 "검증 완료" 또는 "데이터 유효"로 서술하는 것은 오류다. 로컬 스크립트 PASS(npm run validate-data-sample)와 이 필드는 별개 개념이다.
**외부 시장 데이터 격리 [G3]:**
| 구분 | 허용 범위 | 금지 사항 |
|---|---|---|
| `prices_json` 하네스 가격 | 주문 판단·주문표·QEH_AUDIT_BLOCK 전용 | 외부 웹 가격으로 대체 금지 |
| 외부 웹·뉴스 가격 | Section B 해설에만 참고 인용 | Section A 원장·주문표 혼입 금지 |
| 가격 불일치 발생 시 | 하네스 가격 우선, Section B에 "외부 ±N% 차이" 메모 | 외부 가격으로 판단·주문 생성 금지 |
| `follow_through_json` | 추격 확인 상태를 `alpha_lead_table`에 병기. 확인 실패 시 BUY/ADD_ON 산문 허용 금지. | `BLOCKED_FOLLOW_THROUGH` |
| `distribution_risk_json` | `anti_distribution_table`에 그대로 출력. 설거지 위험 HIGH면 BUY/ADD_ON 차단. `pre_distribution_warning=EARLY_WARNING`이면 보고서에 별도 경고 섹션 필수. | `APEX_DISTRIBUTION_MISSING` |
| `profit_preservation_json` | `profit_preservation_table`에 그대로 출력. 수익 보호 상태를 임의 완화 금지. `auto_trailing_stop`이 있으면 손절가 원장에 반드시 반영. | `APEX_PROFIT_LOCK_MISSING` |
| `cash_raise_plan_json` | `smart_cash_raise_table`에 즉시매도·반등대기·보호수량을 분리 출력. | `APEX_CASH_RAISE_MISSING` |
| `smart_sell_quantities_json` | 확정 수량만 사용. `CAPTURE_REQUIRED`는 숫자로 바꾸지 않는다. | `INVALID_QTY_RECALC` |
| `rebound_sell_trigger_json` | 반등 대기 매도 조건을 WATCH/계획으로만 표시. 즉시 HTS 수량에 합산 금지. | `INVALID_REBOUND_SELL` |
| `execution_quality_json` | `execution_quality_table`에 tick/liquidity/gap 검산 결과 출력. PASS가 아니면 주문표 PASS 금지. | `APEX_EXECUTION_QUALITY_MISSING` |
| `buy_permission_json` | BUY_PERMISSION_MATRIX_V1 결과가 BLOCKED이면 모든 BUY 주문표 차단. | `INVALID_BUY_PERMISSION` |
| `limit_price_policy_json` | 지정가·호가 상태를 그대로 사용. 라운드피겨·심리적 가격으로 조정 금지. | `INVALID_PRICE_MUTATION` |
| `backdata_feature_bank_json` | `backdata_feature_bank_table`에 그대로 출력. GAS 자동 수집 원장을 performance 수동 입력보다 우선한다. | `BACKDATA_MISSING` |
- 이전 대화, 기억, positions 탭 수동입력, GAS Account_Holding_Qty(MANUAL_ENTRY)에서 수량 재사용
- stop_price 입력을 위해 positions 탭 수동 갱신 요구
- "이전에 ○○주라고 했으니" 형태의 추정 수량 기재
- 보유수량 없이 분할매도(1차/2차) 수량 산출
- 매도수량 없이 주문금액만 산출 후 역산으로 수량 제시
---
## CRITICAL — 복수 매도 후보 처리 (stage_0)
SELL/TRIM/EXIT 후보가 2개 이상이거나 현금 < 목표인 경우:
1.**`?view=sell_priority` 결과를 먼저 출력** (GAS runSellPriority() 엔드포인트)
2.`sell_priority_decision_table` 출력 후 tier 1→2→3→4→9 순서로 후보 선정
3. sell_priority_decision_table 없이 특정 종목을 1차 매도 대상으로 확정 금지
**코어 주도주 보호:** SK하이닉스·삼성전자는 tier=9 (마지막 순위). 상승추세 중 1차 대상 선정 금지.
---
## 분석 절차
1. Read `RetirementAssetPortfolio.yaml` first.
2. Apply source-of-truth files in manifest order.
3. Run the decision process through `spec/09_decision_flow.yaml`.
4. Apply `spec/risk/risk_control.yaml`, `spec/risk/portfolio_exposure.yaml`, and `spec/08_scoring_rules.yaml` hard filters before scoring.
5. Classify market regime using `spec/11_market_regime.yaml`.
6. Apply `spec/10_portfolio_rules.yaml` before any position sizing.
7. Use `schemas/output_schema.json` for JSON output and `RetirementAssetPortfolioReportTemplate.yaml` for human-readable reports.
8. Every decision must cite rule paths in `rules_used`.
9. If data is missing, do not infer numbers. Use `INSUFFICIENT_DATA` and fill `prohibited_calculations`.
10. Render in two phases: first complete a schema-valid structured payload, then map only those values into the human-readable tables.
11. For human-readable reports, output the required tables in the sequence from `spec/07_output_schema.yaml:recommendation_grade.display_policy.output_sequence`.
12. Do not create free-form section headers or paragraph summaries that replace required tables. Put rationale inside table columns such as `근거`, `매도사유`, or `다음확인사항`.
13. Use only schema enum values for `order_type`, `mode`, and `validation_status`; map them to Korean display labels only after validation.
14. When the user asks for learning-oriented context, add `market_context_learning_note` after the order validation and HTS tables. Use it only for explanation; do not create new prices, quantities, cash figures, or decisions in that section.
15. Do not use free-form order terms such as `부분감액`, `1차 감액`, `부분정리`, `전량`, or `전량매도` in order/action/mode columns. Use canonical enum values and integer quantities instead.
16. When two or more SELL/TRIM/ROTATE candidates exist, output `sell_priority_decision_table` before HTS-ready order tables and sort by `portfolio_exposure_framework.sell_priority_engine`.
17. Always populate `decision_trace` and render `decision_trace_table` before any final action table. Do not use a rule or rationale in the final answer unless it appears in `decision_trace` or `rules_used`.
## 필수 출력 요소
-`BUY`, `HOLD`, `SELL`, `TRIM`, `ROTATE`, `AVOID`, `WATCH`, or `INSUFFICIENT_DATA`
-`capture_read_ledger` and the 4-stage order validation result before any HTS-ready order table
-`decision_trace` / `decision_trace_table` for reproducible rule application
-`sell_priority_decision_table` when multiple sell/trim/rotate candidates compete
- optional `market_context_learning_note` when educational context is requested
- final `engine_feedback_loop_report` using `proposal_evaluation_history`; compare prior proposals with next-day results and include improvement proposals without changing current orders.
- next source to check when validation fails
## 보고서 출력 구조: Section A / B / C [2026-05-19_LLM_SERVICE_LAYER_V1 S2]
모든 분석 보고서는 아래 3개 섹션으로 **순서대로** 구성한다. 섹션 순서 변경 금지.
---
### [Section A] 하드-하네스 원장 (The Ledger)
**오너: 하네스 + LLM as Reporter/Clerk**
포함 내용 (순서 고정):
1.`routing_serving_trace` (라우팅·번들·프롬프트·JSON 검증 상태) ← QEH 이전 필수
2.`QEH_AUDIT_BLOCK` (공식 검산 표)
3.`PROACTIVE_RADAR_BLOCK` (선제 매도 레이더 결과) ← 보유 포지션 분석 시 필수
4.`capture_read_ledger` (계좌 판독 원장)
5.`data_completeness_matrix`
6.`backdata_feature_bank_table` (GAS 자동 수집 백데이터 우선)
18.**`comprehensive_proposal_table`** (PROPOSAL_TABLE, HS010-B) — **항상 필수 출력. PENDING_EXPORT·BLOCKED 무관하게 생략 금지.**`comprehensive_proposal_json` 기반으로 전체 보유 종목 판단 자료를 표로 출력한다.
`comprehensive_proposal_json`을 아래 형식으로 항상 출력한다. `json_validation_status=PENDING_EXPORT`이거나 `order_blueprint_json`이 전부 BLOCKED여도 이 표는 반드시 출력한다. 판단은 사용자가 하므로, 판단에 필요한 모든 수치를 제공하는 것이 시스템의 역할이다.
| 종목 | composite_verdict | 참고 손절가 | 참고 익절1 (TP1 상태) | 참고 익절2 (TP2 상태) | 즉시 매도 수량 | 단계 매도 수량 | 예상 회수 금액 |
Use this prompt when reviewing a proposed recommendation or document change.
Review priority:
1. Identify violations of `spec/risk/risk_control.yaml` and `spec/risk/portfolio_exposure.yaml`.
2. Identify missing data gates from `spec/02_data_contract.yaml`.
3. Check hard filters and rule IDs in `spec/08_scoring_rules.yaml`.
4. Verify decision order against `spec/09_decision_flow.yaml`.
5. Verify portfolio/account constraints against `spec/10_portfolio_rules.yaml`.
6. Verify market regime classification against `spec/11_market_regime.yaml`.
7. Validate output against `schemas/output_schema.json` when JSON output exists.
8. Verify human report rendering against `spec/07_output_schema.yaml:human_report` and `RetirementAssetPortfolioReportTemplate.yaml:output_format_templates.rendering_contract`.
9. Verify APEX harness sections before any HTS order table:
You are tasked with generating the weekly retirement portfolio rebalancing report.
Strictly adhere to the following rules:
1. Copy calculated values exactly. Do not recalculate any prices, weights, or quantities.
2. If `rebalance_required` is true, you must render the `portfolio_rebalance_playbook` section.
3. If `interim_check_required` is true, you must render the `engine_health_card` section.
4. Keep the reporting format standardized.
## Layout Order
1. engine_health_card
2. global_gate_and_cash_defense
3. sell_priority_table_if_any
4. portfolio_rebalance_playbook
5. ticker_action_matrix
6. data_missing_and_harness_update_list
7. weekly_operating_cadence
8. risk_disclaimer_and_next_run_commands
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.