From 7ea1a214875eb75be46ccdd562f7c65f65a5a424 Mon Sep 17 00:00:00 2001 From: gahusb Date: Sat, 16 May 2026 03:00:11 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20web-ai=20V1=20assets=20=E2=86=92=20?= =?UTF-8?q?signal=5Fv1/=20(graduation=20prep)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Atomic mv of root V1 assets (main_server.py + modules/ + data/ + tests/ + entry scripts + docs + logs) into signal_v1/ subdirectory. load_dotenv() updated to load web-ai/.env explicitly via Path. Adds web-ai/CLAUDE.md (workspace guide) and web-ai/start.bat (signal_v1 entry wrapper). Prepares for signal_v2/ Phase 2. Tests: signal_v1/tests/unit baseline preserved (no regression). Co-Authored-By: Claude Opus 4.7 (1M context) --- CLAUDE.md | 702 +----------------- signal_v1/CLAUDE.md | 696 +++++++++++++++++ README.md => signal_v1/README.md | 0 .../backtest_runner.py | 0 backtester.py => signal_v1/backtester.py | 0 main_server.py => signal_v1/main_server.py | 0 {modules => signal_v1/modules}/__init__.py | 0 .../modules}/analysis/ai_council.py | 0 .../modules}/analysis/backtest.py | 0 .../modules}/analysis/deep_learning.py | 0 .../modules}/analysis/ensemble.py | 0 .../modules}/analysis/evaluator.py | 0 .../modules}/analysis/macro.py | 3 +- .../modules}/analysis/market_regime.py | 0 .../modules}/analysis/model_validator.py | 0 .../modules}/analysis/technical.py | 0 {modules => signal_v1/modules}/bot.py | 0 {modules => signal_v1/modules}/config.py | 3 +- .../modules}/services/kis.py | 0 .../modules}/services/llm_client.py | 0 .../modules}/services/news.py | 0 .../modules}/services/news_snapshot.py | 0 .../modules}/services/ollama.py | 0 .../modules}/services/telegram.py | 0 .../modules}/services/telegram_bot/runner.py | 3 +- .../modules}/services/telegram_bot/server.py | 0 .../services/telegram_bot/skill_runner.py | 0 .../modules}/strategy/daily_ledger.py | 0 .../modules}/strategy/process.py | 0 .../modules}/strategy/risk_gate.py | 0 {modules => signal_v1/modules}/utils/ipc.py | 0 .../modules}/utils/market_calendar.py | 0 .../modules}/utils/monitor.py | 0 .../modules}/utils/performance_db.py | 0 .../modules}/utils/process_tracker.py | 0 .../theme_manager.py | 0 .../warmup_and_restart.py | 0 .../watchlist_manager.py | 3 +- start.bat | 3 + 39 files changed, 722 insertions(+), 691 deletions(-) create mode 100644 signal_v1/CLAUDE.md rename README.md => signal_v1/README.md (100%) rename backtest_runner.py => signal_v1/backtest_runner.py (100%) rename backtester.py => signal_v1/backtester.py (100%) rename main_server.py => signal_v1/main_server.py (100%) rename {modules => signal_v1/modules}/__init__.py (100%) rename {modules => signal_v1/modules}/analysis/ai_council.py (100%) rename {modules => signal_v1/modules}/analysis/backtest.py (100%) rename {modules => signal_v1/modules}/analysis/deep_learning.py (100%) rename {modules => signal_v1/modules}/analysis/ensemble.py (100%) rename {modules => signal_v1/modules}/analysis/evaluator.py (100%) rename {modules => signal_v1/modules}/analysis/macro.py (98%) rename {modules => signal_v1/modules}/analysis/market_regime.py (100%) rename {modules => signal_v1/modules}/analysis/model_validator.py (100%) rename {modules => signal_v1/modules}/analysis/technical.py (100%) rename {modules => signal_v1/modules}/bot.py (100%) rename {modules => signal_v1/modules}/config.py (98%) rename {modules => signal_v1/modules}/services/kis.py (100%) rename {modules => signal_v1/modules}/services/llm_client.py (100%) rename {modules => signal_v1/modules}/services/news.py (100%) rename {modules => signal_v1/modules}/services/news_snapshot.py (100%) rename {modules => signal_v1/modules}/services/ollama.py (100%) rename {modules => signal_v1/modules}/services/telegram.py (100%) rename {modules => signal_v1/modules}/services/telegram_bot/runner.py (97%) rename {modules => signal_v1/modules}/services/telegram_bot/server.py (100%) rename {modules => signal_v1/modules}/services/telegram_bot/skill_runner.py (100%) rename {modules => signal_v1/modules}/strategy/daily_ledger.py (100%) rename {modules => signal_v1/modules}/strategy/process.py (100%) rename {modules => signal_v1/modules}/strategy/risk_gate.py (100%) rename {modules => signal_v1/modules}/utils/ipc.py (100%) rename {modules => signal_v1/modules}/utils/market_calendar.py (100%) rename {modules => signal_v1/modules}/utils/monitor.py (100%) rename {modules => signal_v1/modules}/utils/performance_db.py (100%) rename {modules => signal_v1/modules}/utils/process_tracker.py (100%) rename theme_manager.py => signal_v1/theme_manager.py (100%) rename warmup_and_restart.py => signal_v1/warmup_and_restart.py (100%) rename watchlist_manager.py => signal_v1/watchlist_manager.py (99%) create mode 100644 start.bat diff --git a/CLAUDE.md b/CLAUDE.md index b8fd00a..a9cae82 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,696 +1,24 @@ -# 🀖 AI Trading Bot — 프로젝튞 섀계 묞서 (CLAUDE.md) +# web-ai — Workspace 가읎드 -> **최종 갱신**: 2026-03-19 -> **런타임**: Windows (Python 3.x, PyTorch CUDA, FastAPI, Ollama) -> **하드웚얎**: AMD 9800X3D + RTX 5070 Ti (16 GB VRAM) +Windows AI ëšžì‹  (AMD 9800X3D + RTX 5070 Ti) 의 두 시귞널 파읎프띌읞 컚테읎너. ---- +## 디렉토늬 구조 -## 1. 시슀템 아킀텍처 개요 - -``` -┌──────────────────────────────────────────────────────────────────┐ -│ main_server.py │ -│ FastAPI (uvicorn, port 8000) — 프로섞슀 맀니저 & REST API 서버 │ -│ ┌──────────────┐ ┌─────────────────┐ ┌──────────────────────┐ │ -│ │ Trading Bot │ │ Telegram Bot │ │ ProcessWatchdog │ │ -│ │ (Process #1) │ │ (Process #2) │ │ (Daemon Thread) │ │ -│ └──────┬───────┘ └────────┬────────┘ └──────────┬───────────┘ │ -│ │ │ │ │ -│ └─── Shared Memory (IPC) ───┘ Health Check / Restart │ -│ + Command Queue │ -└──────────────────────────────────────────────────────────────────┘ -``` - -### 1.1 멀티 프로섞슀 구성 - -| 프로섞슀 | 역할 | 진입점 | -|---------|------|--------| -| **Main Server (Uvicorn)** | FastAPI REST API 서버, 프로섞슀 였쌀슀튞레읎터 | `main_server.py` | -| **Trading Bot** | 자동맀맀 메읞 룚프 (슀쌀쀄러, 분석, 죌묞) | `modules/bot.py` → `AutoTradingBot.loop()` | -| **Telegram Bot** | 사용자 읞터랙션 (명령얎 처늬, 알늌) | `modules/services/telegram_bot/runner.py` | -| **ProcessWatchdog** | 자식 프로섞슀 헬슀첎크 & 자동 재시작 (30쎈 간격) | `modules/utils/process_tracker.py` | - -### 1.2 프로섞슀 간 통신 (IPC) - -``` -┌─────────────┐ SharedMemory (128KB) ┌──────────────┐ -│ Trading Bot │ ─── write_status() ───────► │ Telegram Bot │ -│ │ ◄── read_status() ──────── │ │ -│ │ │ │ -│ │ multiprocessing.Queue │ │ -│ │ ◄── send_command() ──────── │ │ -│ │ (텔레귞랚 → 뮇 명령) │ │ -└─────────────┘ └──────────────┘ -``` - -- **SharedMemory** (`web_ai_bot_ipc`, 128KB): 메읞 뎇읎 상태 데읎터(잔고, GPU, 맀크로 지표 등)륌 JSON윌로 Ʞ록, 텔레귞랚 뎇읎 읜Ʞ -- **Command Queue** (`multiprocessing.Queue`): 텔레귞랚 → 메읞 뮇 양방향 명령 채널 (`restart`, `evaluate` 등) -- **Lock** (`multiprocessing.Lock`): SharedMemory 동시 ì ‘ê·Œ 볎혞 -- **IPC Staleness**: 600쎈 (10분 읎상 였래된 데읎터는 묎시) - -### 1.3 서버 생명죌Ʞ (Lifespan) - -```python -# main_server.py > lifespan() -1. Config.validate() # 환겜변수 검슝 -2. ProcessTracker.check_and_kill_zombies() # 좀비 프로섞슀 정늬 -3. 전역 객첎 쎈Ʞ화 (OllamaManager, KISClient, NewsCollector) -4. Shared Resources 생성 (Lock, Queue, Event) -5. Trading Bot 프로섞슀 생성 & 시작 -6. Telegram Bot 프로섞슀 생성 & 시작 -7. ProcessWatchdog 시작 (30쎈 간격 헬슀첎크) -8. → yield (서버 정상 욎영) -9. [종료] shutdown_event 섀정 → 자식 종료 → SharedMemory 핎제 -``` - ---- - -## 2. 디렉토늬 구조 - -``` -web-ai/ -├── main_server.py # [Entry Point] FastAPI + 프로섞슀 맀니저 -├── warmup_and_restart.py # LSTM 사전학습 + 뮇 자동 시작 슀크늜튞 -├── watchlist_manager.py # 뉎슀 êž°ë°˜ 음음 Watchlist 자동 업데읎튞 -├── backtester.py # 전략 백테슀팅 CLI -├── theme_manager.py # 종목별 테마/섹터 ꎀ늬 -├── .env # 환겜변수 (KIS, Telegram, Ollama 등) -│ -├── modules/ -│ ├── __init__.py -│ ├── config.py # [Config] 환겜변수 & 상수 정의 -│ ├── bot.py # [Core] AutoTradingBot (상태 ëšžì‹  & 슀쌀쀄러) -│ │ -│ ├── analysis/ # [AI Brain] 분석 엔진 -│ │ ├── deep_learning.py # Attention-LSTM (7D 플처, PyTorch GPU) -│ │ ├── technical.py # Ʞ술적 지표 (RSI, MACD, BB, ADX, OBV...) -│ │ ├── macro.py # 거시겜제 분석 (KOSPI/KOSDAQ/MSI) -│ │ ├── ensemble.py # 적응형 앙상랔 (3신혞 가쀑치 자동조정) -│ │ ├── evaluator.py # 죌간 성곌 평가 + LLM 전묞가 팹널 -│ │ └── backtest.py # 백테슀팅 프레임워크 (Sharpe, MDD 등) -│ │ -│ ├── strategy/ # [Decision] 맀맀 의사결정 -│ │ └── process.py # 워컀 프로섞슀용 분석 핚수 (병렬 처늬) -│ │ -│ ├── services/ # [I/O] 왞부 서비슀 연동 -│ │ ├── kis.py # 한국투자슝권 REST API (동Ʞ + 비동Ʞ) -│ │ ├── ollama.py # Ollama LLM 읞터페읎슀 (GPU 충돌 방지) -│ │ ├── news.py # Google News RSS 크례링 (동Ʞ + 비동Ʞ) -│ │ ├── telegram.py # 텔레귞랚 메시지 발송 (Fire-and-forget) -│ │ └── telegram_bot/ -│ │ ├── server.py # 텔레귞랚 뮇 서버 (명령얎 핞듀러) -│ │ └── runner.py # 텔레귞랚 뮇 독늜 프로섞슀 싀행Ʞ -│ │ -│ └── utils/ # [Util] 유틞늬티 -│ ├── ipc.py # SharedMemory + Command Queue IPC -│ ├── process_tracker.py # PID 추적 & 좀비 정늬 & Watchdog -│ ├── monitor.py # CPU/GPU/RAM 서킷 람레읎컀 -│ └── performance_db.py # 음별 슀냅샷 & 맀맀 Ʞ록 영구 저장 -│ -├── data/ # [Runtime Data] -│ ├── watchlist.json # 현재 감시 종목 늬슀튞 -│ ├── daily_trade_history.json # 음음 맀맀 Ʞ록 -│ ├── kis_token.json # KIS OAuth 토큰 캐시 -│ ├── peak_prices.json # 튞레음링 슀탑용 최고가 -│ ├── ensemble_history.json # AdaptiveEnsemble 가쀑치 + 맀맀 히슀토늬 (종목별) -│ ├── models/ # LSTM 첎크포읞튞 (종목별 .pt 파음) -│ └── performance/ # 성곌 데읎터 (daily_snapshots, trade_records) -│ -└── tests/ # 테슀튞 -``` - ---- - -## 3. 핵심 몚듈 상섞 - -### 3.1 AutoTradingBot (`modules/bot.py`) - -**메읞 튞레읎딩 룚프** — 장 시작(09:00) ~ 장 마감(15:30) 사읎에 자동 싀행 - -``` -[v3.1 죌요 Ʞ능] -├── ATR êž°ë°˜ 동적 손절/익절 + 튞레음링 슀탑 -├── Kelly Criterion 포지션 사읎징 (싀전 승률·손익비 êž°ë°˜, Half-Kelly) -├── AdaptiveEnsemble 연동 (맀도 후 가쀑치 자동 학습) -├── 당음 누적 맀수 추적 (_today_buy_total) - KIS T+2 믞찚감 볎완 -├── 사읎큎당 최대 맀수 종목 수 제한 (MAX_BUY_PER_CYCLE) -├── ProcessPoolExecutor 병렬 분석 (워컀 1개, OOM 대응 자동 재시작) -├── 음별 자산 슀냅샷 (09:05~09:15) -├── 죌간 성곌 평가 (월요음 아칚) -├── CPU 서킷 람레읎컀 연동 -└── IPC Command Queue 폎링 (텔레귞랚 명령 처늬) -``` - -**잔고 추적 로직 (v3.1 — 곌맀수 방지)**: -``` -KIS get_balance() → raw_deposit (dnca_tot_amt) - ↓ -max_daily_buy = raw_deposit × MAX_DAILY_BUY_RATIO (80%) -tracking_deposit = max_daily_buy - effective_today_buy - ↑ - max(kis_today_buy, self._today_buy_total) - (KIS thdt_buy_amt vs 로컬 누적 쀑 큰 값) -``` -- `_today_buy_total`: 읞슀턎슀 변수, 사읎큎 간 유지 (09:00 늬셋) -- `_buy_scores`: BUY 시 신혞 점수 저장 → SELL 시 `record_trade()` 전달 - -**run_cycle() 흐멄**: -1. 시슀템 헬슀 첎크 (CPU/GPU/RAM) -2. 거시겜제 분석 (KOSPI/KOSDAQ/MSI) -3. 위험 상태별 ë¶„êž° (SAFE/CAUTION/DANGER) -4. Watchlist 종목 OHLCV 수집 (KIS 비동Ʞ 배치) -5. 잔고 조회 + 당음 누적 맀수 찚감 → 싀제 가용 예수ꞈ 계산 -6. `ProcessPoolExecutor`로 종목 병렬 분석 (Kelly Criterion + Ensemble 가쀑치) -7. 앙상랔 점수 êž°ë°˜ 맀수/맀도 판당 (사읎큎당 MAX_BUY_PER_CYCLE 제한) -8. 죌묞 싀행 & 결곌 텔레귞랚 알늌 -9. 맀도 시 `record_trade()` → Ensemble 가쀑치 학습 -10. IPC 상태 갱신 - -### 3.2 AI 분석 파읎프띌읞 - -``` - ┌─────────────────────┐ - │ analyze_stock_ │ - │ process() │ - │ (strategy/process)│ - └─────────┬───────────┘ - │ - ┌─────────────────────┌────────────────────┐ - â–Œ â–Œ â–Œ -┌───────────────┐ ┌────────────────┐ ┌─────────────────┐ -│ Technical │ │ Deep Learning │ │ LLM (Ollama) │ -│ Analyzer │ │ LSTM │ │ Sentiment │ -│ (Ʞ술적 지표) │ │ (죌가 예잡) │ │ (뉎슀 감성분석) │ -├──────────────── ├───────────────── ├────────────────── -│ RSI 25% │ │ Attention-LSTM │ │ qwen2.5:7b │ -│ 읎격도 15% │ │ 4L×512H │ │ JSON 포맷 요청 │ -│ MACD 15% │ │ 7찚원 플처 │ │ 뉎슀+지표 통합 │ -│ Stochastic 5% │ │ 60음 시퀀슀 │ │ 감성+신뢰도 │ -│ BB 15% │ │ GPU 가속 │ │ │ -│ ADX 15% │ │ 종목별 몚덞 │ │ │ -│ MTF 10% │ │ (ModelRegistry)│ │ │ -│ OBV ±볎너슀 │ │ │ │ │ -└───────┬───────┘ └───────┬────────┘ └───────┬─────────┘ - │ │ │ - └──────────┬────────┘ │ - â–Œ │ - ┌─────────────────┐ │ - │ AdaptiveEnsemble│ ◄───────────────────┘ - │ (학습형 가쀑치) │ - ├────────────────── - │ get_weights() │ ← 곌거 맀맀 결곌 반영 - │ (ADX+macro+conf)│ 크Ʞ 가쀑 정확도 Ʞ쀀 - │ 겜계: 0.10~0.65 │ Water-Filling 정규화 - │ Kelly Fraction │ ← 승률·손익비 êž°ë°˜ - └────────┬────────┘ - â–Œ - ┌────────────────┐ - │ 맀수/맀도/홀드 │ - │ 최종 판당 │ - └────────────────┘ -``` - -#### 3.2.1 Deep Learning — Attention-LSTM (`analysis/deep_learning.py`) - -| 항목 | 값 | -|------|-----| -| **아킀텍처** | 4-Layer Stacked LSTM + Attention + FC | -| **Hidden Size** | 512 | -| **Input Features** | 7 (close, open, high, low, volume_norm, rsi_14, macd_hist) | -| **시퀀슀 Ꞟ읎** | 60음 | -| **학습 에포크** | 최대 200 (Early Stopping patience=15) | -| **빠륞 재학습** | 30 에포크 (첎크포읞튞 졎재 시) | -| **쿚닀욎** | 1200쎈 (20분, 동음 종목 재학습 방지) | -| **ModelRegistry** | LRU 방식, 최대 5개 몚덞 동시 적재 | -| **첎크포읞튞** | `data/models/{ticker}_v3.pt` | -| **GPU ꎀ늬** | LSTM 학습 시 Ollama 자동 얞로드/늬로드 | - -#### 3.2.2 Ʞ술적 분석 (`analysis/technical.py`) - -`TechnicalAnalyzer.get_technical_score()` → 0.0 ~ 1.0 통합 점수 - -| 지표 | 비쀑 | 섀명 | +| 겜로 | 역할 | 상태 | |------|------|------| -| RSI (14음) | 25% | Wilder 방식, 30 읎하 곌맀도/70 읎상 곌맀수 | -| 읎동평균 읎격도 | 15% | 20음 MA 대비 현재가 위치 | -| MACD | 15% | 12/26/9, 히슀토귞랚 방향 | -| Stochastic | 5% | Fast %K/%D (14/3/3) | -| Bollinger Bands | 15% | 20음/2σ, %B 위치 + 밮드폭 | -| ADX | 15% | 추섞 강도 (>25 강한 추섞) | -| Multi-Timeframe | 10% | 5음/20음/60음 추섞 음ꎀ성 | -| OBV | ±0.1 볎너슀 | 거래량 êž°ë°˜ 맀집/분산 감지 | +| `signal_v1/` | V1 자첎 자동맀맀 시슀템 (main_server.py + Trading Bot + Telegram Bot + LSTM + Ollama + KIS 자동죌묞) | 욎영 쀑. Confidence Signal Pipeline V2 Phase 6 에서 deprecation 예정 | +| `signal_v2/` | V2 신혞 파읎프띌읞 (stock pull worker + Chronos-2 + signal API client) | Phase 2 에서 ì‹ ì„€ | +| `.env` | V1 + V2 환겜변수 공유 | KIS_*, TELEGRAM_*, STOCK_API_URL, WEBAI_API_KEY 등 | +| `start.bat` | V1 진입 (signal_v1 디렉토늬 안 main_server.py 싀행) | V2 별도 start 슀크늜튞는 signal_v2/start.bat | -추가 Ʞ능: -- `calculate_atr()` → ATR êž°ë°˜ 동적 손절/익절 -- `calculate_dynamic_sl_tp()` → 변동성 적응형 SL/TP -- `calculate_obv()` → 슀마튞 빾니 닀읎버전슀 감지 +## 욎영 가읎드 -#### 3.2.3 거시겜제 분석 (`analysis/macro.py`) +- V1 시작: `start.bat` 또는 `cd signal_v1 && python main_server.py` +- V2 시작 (Phase 2 읎후): `cd signal_v2 && python -m uvicorn main:app --port 8001` +- 둘 ë‹€ 동시 싀행 가능 (포튞 분늬: V1=8000, V2=8001) -```python -MacroAnalyzer.get_macro_status(kis_client) → { - "status": "SAFE" | "CAUTION" | "DANGER", - "risk_score": int, - "indicators": { - "KOSPI": {"price", "change", "high", "low", "prev_close", "volume"}, - "KOSDAQ": {"price", "change", ...}, - "KOSPI200":{"price", "change", ...}, - "MSI": float # Market Stress Index (0~100) - } -} -``` +## Phase 진행 상태 (Confidence Signal Pipeline V2) -- **SAFE** (risk_score < 1): 정상 맀맀 -- **CAUTION** (1 ≀ risk_score < 3): 맀수 규몚 축소 -- **DANGER** (risk_score ≥ 3): 맀수 쀑닚, 볎유분만 ꎀ늬 +`web-ui/docs/superpowers/specs/2026-05-15-confidence-signal-pipeline-v2-architecture.md` ì°žì¡°. -#### 3.2.4 앙상랔 (`analysis/ensemble.py`) - -`AdaptiveEnsemble` — 곌거 맀맀 결곌 êž°ë°˜ 가쀑치 자동 조정 + Kelly Criterion: - -**가쀑치 학습 흐멄**: -``` -BUY 첎결 → bot._buy_scores[ticker] = {tech, sentiment, lstm} 저장 -SELL 첎결 → ensemble.record_trade(ticker, ..., outcome_pct=yld) - → _update_weights() → EMA(alpha=0.10) 가쀑치 점진 조정 - → _save() → data/ensemble_history.json -워컀 프로섞슀 → reload_if_stale() → 파음 mtime 감지 시 재로드 -``` - -**죌요 메서드**: -- `get_weights(ticker, adx, macro_state, ai_confidence)` → `SignalWeights` - - 시장 컚텍슀튞 (strong_trend/sideways/danger/default) 별 Ʞ볞 가쀑치 - - 종목별 최귌 10거래 크Ʞ 가쀑 정확도 반영 - - ai_confidence >= 0.75 → LSTM 가쀑치 +25% (confidence 상한 0.80 반영) -- `get_kelly_fraction(ticker, half_kelly=True)` → 0.03~0.25 범위 투자 비쀑 - - f* = (p·b - q) / b (p=승률, b=손익비) - - 거래 데읎터 < 10걎 → 볎수적 Ʞ볞값 8% - - Half-Kelly 적용윌로 변동성 곌대추정 볎완 -- `compute_ensemble_score(tech, sentiment, lstm, investor, weights)` → 통합 점수 -- `reload_if_stale()` → 파음 mtime êž°ë°˜ cross-process 동Ʞ화 - -**`SignalWeights.normalize()` — Water-Filling 알고늬슘**: -- 겜계(0.10~0.65) 위반 시 핎당 값을 겜계에 고정, 나뚞지에 잔여 비쀑 비례 배분 -- 2ì°š 정규화(합=1 볎장)와 겜계 큎랚핑읎 상충하는 묞제 핎결 -- 영구 저장: `data/ensemble_history.json` (가쀑치 + 맀맀 히슀토늬 통합) - -#### 3.2.5 성곌 평가 (`analysis/evaluator.py`) - -`PerformanceEvaluator.generate_weekly_report()`: -- 핵심 지표: 쎝수익률, Sharpe Ratio, MDD, 승률, 평균손익비, KOSPI 상ꎀ도 -- S/A/B/C/D/F 등꞉ 산출 -- **5명 전묞가 LLM 팹널** (Ollama): 각각 닀륞 ꎀ점윌로 평가 -- HTML 포맷 텔레귞랚 죌간 볎고서 자동 생성 - ---- - -## 4. 왞부 서비슀 연동 - -### 4.1 한국투자슝권 KIS API (`services/kis.py`) - -#### 읞슝 - -```python -KISClient.ensure_token() -# OAuth 2.0 → access_token 발꞉ → data/kis_token.json에 캐시 -# 토큰 만료 시 자동 갱신 (_request_api에서 처늬) -``` - -| 섀정 | 몚의투자 | 싀전투자 | -|------|---------|---------| -| Base URL | `openapivts.koreainvestment.com:29443` | `openapi.koreainvestment.com:9443` | -| 환겜변수 | `KIS_VIRTUAL_APP_KEY/SECRET/ACCOUNT` | `KIS_REAL_APP_KEY/SECRET/ACCOUNT` | -| 전환 | `.env` → `KIS_ENV_TYPE=virtual` | `.env` → `KIS_ENV_TYPE=real` | - -#### API 슀로틀링 - -- 쎈당 2회 제한 (`_throttle()` — 0.5쎈 딜레읎) -- 토큰 만료 시 자동 갱신 (403 → retry with new token) - -#### 죌요 API 엔드포읞튞 맀핑 - -| Ʞ능 | KISClient 메서드 | KIS TR_ID | -|------|-----------------|-----------| -| 잔고 조회 | `get_balance()` → `{holdings, total_eval, deposit, today_buy_amt}` | `VTTC8434R` (몚의) / `TTTC8434R` (싀전) | -| 죌묞 (맀수/맀도) | `order()` | `VTTC0802U` / `VTTC0801U` (몚의) | -| 현재가 조회 | `get_current_price()` | `FHKST01010100` | -| 음뎉 OHLCV | `get_daily_ohlcv()` → `_get_daily_ohlcv_by_range()` | `FHKST03010100` | -| 음뎉 종가 | `get_daily_price()` → `_get_daily_price_by_range()` | `FHKST03010100` | -| 거래량 순위 | `get_volume_rank()` | `FHPST01710000` | -| 지수 현재가 | `get_current_index()` | `FHPUP02100000` | -| 지수 음뎉 | `get_daily_index_price()` | `FHKUP03500100` | -| 투자자 동향 | `get_investor_trend()` | `FHKST01010900` | -| Hash Key | `get_hash_key()` | - | - -#### 비동Ʞ 큎띌읎얞튞 (`KISAsyncClient`) - -`aiohttp` êž°ë°˜ — 닀쀑 종목 동시 수집용: -- `get_daily_price_batch()` — 여러 종목 음뎉 병렬 수집 -- `get_daily_ohlcv_batch()` — 여러 종목 OHLCV 병렬 수집 -- `get_investor_trends_batch()` — 여러 종목 투자자 동향 병렬 수집 - ---- - -### 4.2 Ollama LLM (`services/ollama.py`) - -| 섀정 | 값 | -|------|-----| -| **몚덞** | `qwen2.5:7b-instruct-q4_K_M` (VRAM ~4GB) | -| **API URL** | `http://localhost:11434` | -| **Context Window** | 4096 토큰 | -| **Max Output** | 200 토큰 | -| **Temperature** | 0.1 (결정론적, JSON 안정성) | -| **Keep Alive** | 5분 (비활성 시 자동 얞로드) | -| **Timeout** | 90쎈 | -| **CPU Threads** | 8 (9800X3D 최적화) | -| **응답 포맷** | JSON (format: "json") | - -**GPU 충돌 방지**: -- LSTM 학습 쀑 → Ollama 추론 최대 60쎈 대Ʞ -- VRAM > 12GB → 몚덞 슉시 얞로드 (`keep_alive=0`) -- LSTM 학습 전 → Ollama 자동 얞로드, 학습 후 → 자동 늬로드 - ---- - -### 4.3 뉎슀 수집 (`services/news.py`) - -- **소슀**: Google News RSS (`news.google.com/rss/search`) -- **동Ʞ**: `NewsCollector.get_market_news()` — 시장 음반 뉎슀 5걎 -- **비동Ʞ**: `AsyncNewsCollector` - - `get_market_news_async()` — 시장 뉎슀 (5분 캐시) - - `get_stock_news_async()` — 종목별 뉎슀 (5분 캐시) - ---- - -## 5. 웹 백엔드 서버 API (FastAPI) - -### 5.1 서버 정볎 - -| 항목 | 값 | -|------|-----| -| **프레임워크** | FastAPI + Uvicorn | -| **혞슀튞** | `0.0.0.0:8000` | -| **NAS 백엔드** | `http://192.168.45.54:18500` (웹 프론튞엔드 서버) | - -### 5.2 API 엔드포읞튞 - -#### `GET /` — 서버 상태 - -```json -{ - "status": "online", - "gpu_vram": 4.2, - "service": "Windows AI Server (Refactored)" -} -``` - -#### `GET /trade/balance` | `GET /api/trade/balance` — 잔고 조회 - -KIS API륌 통핎 현재 계좌 잔고(예수ꞈ, 볎유종목, 평가ꞈ액) 조회. - -```json -{ - "total_eval": 10500000, - "deposit": 5000000, - "holdings": [ - { - "ticker": "005930", - "name": "삌성전자", - "qty": 10, - "avg_price": 72000, - "current_price": 73500, - "profit_rate": 2.08 - } - ] -} -``` - -#### `POST /trade/order` | `POST /api/trade/order` — 수동 죌묞 - -```json -// Request Body -{ - "ticker": "005930", - "action": "BUY", // "BUY" | "SELL" - "quantity": 10 -} - -// Response -{ - "status": "executed", - "kis_result": { ... } -} -``` - -#### `POST /analyze/portfolio` | `POST /api/analyze/portfolio` — AI 포튞폎늬였 분석 - -현재 잔고 + 최신 뉎슀륌 종합하여 Ollama LLM윌로 포튞폎늬였 분석. - -```json -{ - "analysis": "... AI 분석 결곌 (한국얎) ..." -} -``` - -### 5.3 NAS 서버와의 통신 흐멄 - -``` -┌──────────────┐ HTTP Request ┌────────────────────┐ -│ NAS Backend │ ─────────────────────► │ Windows AI Server │ -│ (웹 프론튞) │ │ (FastAPI:8000) │ -│ :18500 │ ◄──────────────────── │ │ -│ │ JSON Response │ │ -└──────────────┘ └────────────────────┘ - -[통신 시나늬였] -1. 웹 → /api/trade/balance → 잔고 데읎터 표시 -2. 웹 → /api/trade/order → 수동 맀수/맀도 싀행 -3. 웹 → /api/analyze/portfolio → AI 분석 결곌 표시 -4. 웹 → / → 서버 상태 및 GPU 정볎 -``` - -- **NAS 서버** (`192.168.45.54:18500`): 웹 프론튞엔드 혞슀팅, 사용자 읞터페읎슀 제공 -- **Windows AI 서버** (`0.0.0.0:8000`): GPU 연산, KIS API 통신, AI 분석 처늬 -- 낎부 넀튞워크 (LAN) 통신, 왞부 ë…žì¶œ 없음 - ---- - -## 6. 텔레귞랚 뮇 섀정 & 명령얎 - -### 6.1 환겜변수 - -```env -TELEGRAM_BOT_TOKEN=8546032918:AAF5GJcP92DrtpSoQdaimMIZe7bz_xtGGPo -TELEGRAM_CHAT_ID=7388056964 -``` - -### 6.2 뮇 프로섞슀 아킀텍처 - -``` -runner.py - └── run_telegram_bot_standalone() - ├── SharedIPC 쎈Ʞ화 (lock, queue, shutdown_event) - ├── TelegramBotServer 생성 - ├── IPC에서 쎈Ʞ 데읎터 로드 - ├── bot_server.run() (python-telegram-bot polling) - └── Conflict 감지 시 백였프 재시도 (최대 10회) -``` - -- **띌읎람러늬**: `python-telegram-bot` (Application, CommandHandler) -- **메시지 포맷**: HTML (`parse_mode="HTML"`) -- **동시 업데읎튞**: `concurrent_updates=True` -- **로깅**: `telegram_bot.log` (파음 + 윘솔) - -### 6.3 명령얎 목록 - -| 명령얎 | 섀명 | 데읎터 소슀 | -|--------|------|------------| -| `/start` | 뮇 시작 & 전첎 명령얎 안낎 | - | -| `/status` | 뮇 상태, 시장 지수, AI 몚덞 상태 | IPC (SharedMemory) | -| `/portfolio` | 볎유 종목 & 수익률 조회 | IPC → FakeKIS.get_balance() | -| `/watchlist` | 현재 감시 종목 늬슀튞 | IPC → watchlist 데읎터 | -| `/update_watchlist` | Watchlist 슉시 업데읎튞 요청 | Command Queue → 메읞 뮇 | -| `/macro` | 거시겜제 분석 (KOSPI/KOSDAQ/MSI) | IPC → macro_indices | -| `/system` | CPU/GPU/RAM 시슀템 상태 | IPC → gpu_status + psutil | -| `/ai` | AI 몚덞 상태 (VRAM, 학습 여부) | IPC → gpu_status | -| `/restart` | 메읞 뮇 재시작 명령 | Command Queue | -| `/stop` | 뮇 종료 | shutdown_event.set() | -| `/exec ` | 서버 쉘 명령얎 직접 싀행 | subprocess (10쎈 타임아웃) | -| `/evaluate` | 슉시 성곌 평가 볎고서 생성 | PerformanceEvaluator | - -### 6.4 TelegramMessenger (`services/telegram.py`) - -닚방향 알늌 전용 (메읞 뮇 → 사용자): -- **비동Ʞ 전송**: `threading.Thread(daemon=True)` — Fire-and-forget -- **HTML 파싱**: 마크닀욎 에러 방지 -- 맀맀 싀행, 서버 시작/종료, 에러 알늌 등에 사용 - -### 6.5 Conflict 처늬 - -텔레귞랚 뮇 API는 동시에 하나의 polling 읞슀턎슀만 허용: -- `Conflict` 에러 감지 시 지수 백였프 (5s → 10s → ... → 30s) -- 최대 10회 재시도 후 프로섞슀 종료 -- Watchdog가 감지하여 자동 재시작 - ---- - -## 7. 환겜 섀정 (`modules/config.py`) - -### 7.1 죌요 섀정 상수 - -| 귞룹 | í‚€ | 값 | 섀명 | -|------|-----|-----|------| -| **맀맀** | `MAX_INVESTMENT_PER_STOCK` | 3,000,000원 | 종목당 최대 투자ꞈ | -| **맀맀** | `MAX_BUY_PER_CYCLE` | 2 | 사읎큎당 최대 맀수 종목 수 (env: `MAX_BUY_PER_CYCLE`) | -| **맀맀** | `MAX_DAILY_BUY_RATIO` | 0.80 | 예수ꞈ 대비 음음 최대 맀수 비윚 (env: `MAX_DAILY_BUY_RATIO`) | -| **IPC** | `SHM_NAME` | `web_ai_bot_ipc` | SharedMemory 읎늄 | -| **IPC** | `SHM_SIZE` | 131,072 (128KB) | SharedMemory 크Ʞ | -| **IPC** | `IPC_STALENESS` | 600쎈 | 데읎터 유횚 êž°ê°„ | -| **GPU** | `VRAM_WARNING_THRESHOLD` | 12.0 GB | VRAM 겜고 임계값 | -| **프로섞슀** | `WATCHDOG_INTERVAL` | 30쎈 | 헬슀첎크 간격 | -| **프로섞슀** | `MAX_RESTART_COUNT` | 3 | 최대 자동 재시작 횟수 | -| **LSTM** | `LSTM_COOLDOWN` | 1,200쎈 | 동음 종목 재학습 방지 | -| **LSTM** | `LSTM_FAST_EPOCHS` | 30 | 빠륞 재학습 에포크 | -| **CPU** | `CPU_CIRCUIT_BREAKER_THRESHOLD` | 92% | 서킷 람레읎컀 임계값 | -| **CPU** | `CPU_CIRCUIT_BREAKER_CONSECUTIVE` | 2회 | 연속 쎈곌 시 발동 | -| **Ollama** | `OLLAMA_NUM_CTX` | 4,096 | 컚텍슀튞 윈도우 | -| **Ollama** | `OLLAMA_NUM_PREDICT` | 200 | 최대 출력 토큰 | -| **Ollama** | `OLLAMA_NUM_THREAD` | 8 | CPU 슀레드 수 | -| **Network** | `HTTP_TIMEOUT` | 10쎈 | Ʞ볞 HTTP 요청 타임아웃 | - -### 7.2 .env 파음 구조 - -```env -# NAS Backend (웹 프론튞엔드 서버) -NAS_API_URL=http://192.168.45.54:18500 - -# Ollama LLM -OLLAMA_API_URL=http://localhost:11434 -OLLAMA_MODEL=qwen2.5:7b-instruct-q4_K_M - -# KIS API (virtual/real 전환) -KIS_ENV_TYPE=virtual -KIS_REAL_APP_KEY=... -KIS_REAL_APP_SECRET=... -KIS_REAL_ACCOUNT=XXXXXXXX-XX -KIS_VIRTUAL_APP_KEY=... -KIS_VIRTUAL_APP_SECRET=... -KIS_VIRTUAL_ACCOUNT=XXXXXXXX-XX - -# Telegram Bot -TELEGRAM_BOT_TOKEN=... -TELEGRAM_CHAT_ID=... -``` - ---- - -## 8. 욎영 가읎드 - -### 8.1 시작 방법 - -```bash -# 음반 시작 -python main_server.py - -# LSTM 사전학습 후 자동 시작 -python warmup_and_restart.py - -# 텔레귞랚 뮇만 당독 싀행 (디버깅용) -python -m modules.services.telegram_bot.runner -``` - -### 8.2 좀비 프로섞슀 ꎀ늬 - -- `main_server.py` 싀행 시 자동윌로 읎전 좀비 프로섞슀 정늬 -- `pids.txt` êž°ë°˜ → 메몚늬 êž°ë°˜ PID 추적윌로 전환 완료 -- 수동 확읞: `Get-Process python` (PowerShell) - -### 8.3 로귞 파음 - -| 파음 | 용도 | -|------|------| -| `server.log` | Uvicorn 서버 로귞 | -| `telegram_bot.log` | 텔레귞랚 뮇 로귞 | -| `warmup.log` | LSTM 사전학습 진행 로귞 | -| `bot_output.log` | 튞레읎딩 뮇 출력 로귞 | - -### 8.4 튞러랔슈팅 - -| 슝상 | 원읞 | 핎결 | -|------|------|------| -| KIS 403 Forbidden | 토큰 만료 또는 Rate Limit | `data/kis_token.json` 삭제 후 재시작 | -| Telegram Conflict | 읎전 뮇 프로섞슀 믞종료 | `main_server.py` 재시작 (자동 정늬) | -| GPU OOM | LSTM + Ollama 동시 적재 | `VRAM_WARNING_THRESHOLD` 낮추Ʞ | -| CPU 100% 고정 | 좀비 워컀 프로섞슀 | `main_server.py` 재시작 | -| IPC 데읎터 였래됚 | 메읞 뮇 크래시 | Watchdog 자동 재시작 확읞, 수동 재시작 | -| 예수ꞈ 쎈곌 맀수 | KIS 몚의투자 T+2 믞찚감 | `MAX_DAILY_BUY_RATIO` / `MAX_BUY_PER_CYCLE` 조정 | -| Kelly 비쀑읎 너묎 낮음 | 거래 Ʞ록 부족 (< 10걎) | 쎈Ʞ에는 Ʞ볞값 8% 사용, 거래 누적 후 자동 조정 | -| 앙상랔 가쀑치 갱신 안 됚 | 맀도 첎결 없음 또는 `_buy_scores` 누띜 | 뮇 재시작 전 맀도 완료 확읞; `data/ensemble_history.json` 확읞 | - ---- - -## 9. 데읎터 흐멄 요앜 - -``` -[시장 개장 전] - WatchlistManager → 뉎슀 분석 → Watchlist 갱신 - -[장쀑 사읎큎 (≈5분 간격)] - 1. SystemMonitor.check_health() → CPU/GPU 확읞 - 2. MacroAnalyzer.get_macro_status() → 시장 상태 판당 - 3. KIS → get_balance() → raw_deposit - today_buy_total = 가용 예수ꞈ - 4. KIS → get_daily_ohlcv_batch() → OHLCV 수집 - 5. ProcessPool → analyze_stock_process() × N종목 - ├── ensemble.reload_if_stale() → 파음 mtime 감지 시 가쀑치 재로드 - ├── TechnicalAnalyzer → Ʞ술적 점수 - ├── PricePredictor → LSTM 예잡 - ├── OllamaManager → LLM 감성 분석 - ├── AdaptiveEnsemble.get_weights() → 학습된 동적 가쀑치 - └── calculate_position_size() → Kelly Criterion 수량 산출 - 6. 맀수 판당 → 예수ꞈ 확읞 → KIS 죌묞 - ├── _buy_scores[ticker] 저장 (앙상랔 학습용) - ├── _today_buy_total += 맀수ꞈ액 - └── buys_this_cycle++ (MAX_BUY_PER_CYCLE 제한) - 7. 맀도 판당 → KIS 죌묞 - └── ensemble.record_trade() → 가쀑치 학습 + ensemble_history.json 저장 - 8. SharedIPC.write_status() → 텔레귞랚 뎇에 공유 - 9. TelegramMessenger → 결곌 알늌 - -[장 마감 후] - PerformanceDB.save_daily_snapshot() → 음별 자산 Ʞ록 - Evaluator → 죌간 볎고서 (월요음) -``` - ---- - -## 10. 버전 변겜 읎력 - -### v3.1 (2026-03-19) — 잔고 ꎀ늬 & 앙상랔 학습 완성 - -**버귞 수정**: -- `tracking_deposit` 사읎큎 간 쎈Ʞ화 묞제 → `_today_buy_total` 읞슀턎슀 변수로 누적 추적 -- KIS 몚의투자 T+2 믞찚감윌로 읞한 예수ꞈ 쎈곌 맀수 방지 -- `ai_confidence >= 0.85` 임계값 버귞 (LSTM confidence 상한 0.80 믞반영) → 0.75로 수정 -- OHLCV 플처 누띜 시 silent fallback → 겜고 로귞 출력 - -**신규 Ʞ능**: -- `MAX_BUY_PER_CYCLE`: 사읎큎당 최대 맀수 종목 수 제한 (Ʞ볞 2) -- `MAX_DAILY_BUY_RATIO`: 예수ꞈ 대비 음음 최대 맀수 비윚 (Ʞ볞 80%) -- `kis.get_balance()` → `today_buy_amt` 필드 추가 (`thdt_buy_amt`) - -**앙상랔 (`analysis/ensemble.py`)**: -- `AdaptiveEnsemble`을 `process.py`에 싀제 연동 (하드윔딩 가쀑치 제거) -- `get_kelly_fraction()`: Half-Kelly Criterion 포지션 비쀑 계산 추가 -- `SignalWeights.normalize()`: Water-Filling 알고늬슘윌로 겜계 위반 묞제 핎결 -- `_accuracy()` 읎진 지표 제거 → `_accuracy_weighted()` (크Ʞ 가쀑) 통음 -- `reload_if_stale()`: 파음 mtime êž°ë°˜ cross-process 동Ʞ화 - -**포지션 사읎징 (`strategy/process.py`)**: -- `calculate_position_size()`: 하드윔딩 10% → Kelly Criterion (곌거 승률·손익비 êž°ë°˜) -- `bot.py` 쀑복 계산 제거 → 워컀의 `suggested_qty` 직접 사용 - -**앙상랔 학습 룚프 (`bot.py`)**: -- BUY 첎결 시 `_buy_scores[ticker]` 신혞 점수 저장 -- SELL 첎결 시 `ensemble.record_trade()` → `ensemble_history.json` 갱신 -- 워컀 프로섞슀는 `reload_if_stale()`로 자동 반영 +자섞한 V1 가읎드는 `signal_v1/CLAUDE.md` ì°žì¡°. diff --git a/signal_v1/CLAUDE.md b/signal_v1/CLAUDE.md new file mode 100644 index 0000000..b8fd00a --- /dev/null +++ b/signal_v1/CLAUDE.md @@ -0,0 +1,696 @@ +# 🀖 AI Trading Bot — 프로젝튞 섀계 묞서 (CLAUDE.md) + +> **최종 갱신**: 2026-03-19 +> **런타임**: Windows (Python 3.x, PyTorch CUDA, FastAPI, Ollama) +> **하드웚얎**: AMD 9800X3D + RTX 5070 Ti (16 GB VRAM) + +--- + +## 1. 시슀템 아킀텍처 개요 + +``` +┌──────────────────────────────────────────────────────────────────┐ +│ main_server.py │ +│ FastAPI (uvicorn, port 8000) — 프로섞슀 맀니저 & REST API 서버 │ +│ ┌──────────────┐ ┌─────────────────┐ ┌──────────────────────┐ │ +│ │ Trading Bot │ │ Telegram Bot │ │ ProcessWatchdog │ │ +│ │ (Process #1) │ │ (Process #2) │ │ (Daemon Thread) │ │ +│ └──────┬───────┘ └────────┬────────┘ └──────────┬───────────┘ │ +│ │ │ │ │ +│ └─── Shared Memory (IPC) ───┘ Health Check / Restart │ +│ + Command Queue │ +└──────────────────────────────────────────────────────────────────┘ +``` + +### 1.1 멀티 프로섞슀 구성 + +| 프로섞슀 | 역할 | 진입점 | +|---------|------|--------| +| **Main Server (Uvicorn)** | FastAPI REST API 서버, 프로섞슀 였쌀슀튞레읎터 | `main_server.py` | +| **Trading Bot** | 자동맀맀 메읞 룚프 (슀쌀쀄러, 분석, 죌묞) | `modules/bot.py` → `AutoTradingBot.loop()` | +| **Telegram Bot** | 사용자 읞터랙션 (명령얎 처늬, 알늌) | `modules/services/telegram_bot/runner.py` | +| **ProcessWatchdog** | 자식 프로섞슀 헬슀첎크 & 자동 재시작 (30쎈 간격) | `modules/utils/process_tracker.py` | + +### 1.2 프로섞슀 간 통신 (IPC) + +``` +┌─────────────┐ SharedMemory (128KB) ┌──────────────┐ +│ Trading Bot │ ─── write_status() ───────► │ Telegram Bot │ +│ │ ◄── read_status() ──────── │ │ +│ │ │ │ +│ │ multiprocessing.Queue │ │ +│ │ ◄── send_command() ──────── │ │ +│ │ (텔레귞랚 → 뮇 명령) │ │ +└─────────────┘ └──────────────┘ +``` + +- **SharedMemory** (`web_ai_bot_ipc`, 128KB): 메읞 뎇읎 상태 데읎터(잔고, GPU, 맀크로 지표 등)륌 JSON윌로 Ʞ록, 텔레귞랚 뎇읎 읜Ʞ +- **Command Queue** (`multiprocessing.Queue`): 텔레귞랚 → 메읞 뮇 양방향 명령 채널 (`restart`, `evaluate` 등) +- **Lock** (`multiprocessing.Lock`): SharedMemory 동시 ì ‘ê·Œ 볎혞 +- **IPC Staleness**: 600쎈 (10분 읎상 였래된 데읎터는 묎시) + +### 1.3 서버 생명죌Ʞ (Lifespan) + +```python +# main_server.py > lifespan() +1. Config.validate() # 환겜변수 검슝 +2. ProcessTracker.check_and_kill_zombies() # 좀비 프로섞슀 정늬 +3. 전역 객첎 쎈Ʞ화 (OllamaManager, KISClient, NewsCollector) +4. Shared Resources 생성 (Lock, Queue, Event) +5. Trading Bot 프로섞슀 생성 & 시작 +6. Telegram Bot 프로섞슀 생성 & 시작 +7. ProcessWatchdog 시작 (30쎈 간격 헬슀첎크) +8. → yield (서버 정상 욎영) +9. [종료] shutdown_event 섀정 → 자식 종료 → SharedMemory 핎제 +``` + +--- + +## 2. 디렉토늬 구조 + +``` +web-ai/ +├── main_server.py # [Entry Point] FastAPI + 프로섞슀 맀니저 +├── warmup_and_restart.py # LSTM 사전학습 + 뮇 자동 시작 슀크늜튞 +├── watchlist_manager.py # 뉎슀 êž°ë°˜ 음음 Watchlist 자동 업데읎튞 +├── backtester.py # 전략 백테슀팅 CLI +├── theme_manager.py # 종목별 테마/섹터 ꎀ늬 +├── .env # 환겜변수 (KIS, Telegram, Ollama 등) +│ +├── modules/ +│ ├── __init__.py +│ ├── config.py # [Config] 환겜변수 & 상수 정의 +│ ├── bot.py # [Core] AutoTradingBot (상태 ëšžì‹  & 슀쌀쀄러) +│ │ +│ ├── analysis/ # [AI Brain] 분석 엔진 +│ │ ├── deep_learning.py # Attention-LSTM (7D 플처, PyTorch GPU) +│ │ ├── technical.py # Ʞ술적 지표 (RSI, MACD, BB, ADX, OBV...) +│ │ ├── macro.py # 거시겜제 분석 (KOSPI/KOSDAQ/MSI) +│ │ ├── ensemble.py # 적응형 앙상랔 (3신혞 가쀑치 자동조정) +│ │ ├── evaluator.py # 죌간 성곌 평가 + LLM 전묞가 팹널 +│ │ └── backtest.py # 백테슀팅 프레임워크 (Sharpe, MDD 등) +│ │ +│ ├── strategy/ # [Decision] 맀맀 의사결정 +│ │ └── process.py # 워컀 프로섞슀용 분석 핚수 (병렬 처늬) +│ │ +│ ├── services/ # [I/O] 왞부 서비슀 연동 +│ │ ├── kis.py # 한국투자슝권 REST API (동Ʞ + 비동Ʞ) +│ │ ├── ollama.py # Ollama LLM 읞터페읎슀 (GPU 충돌 방지) +│ │ ├── news.py # Google News RSS 크례링 (동Ʞ + 비동Ʞ) +│ │ ├── telegram.py # 텔레귞랚 메시지 발송 (Fire-and-forget) +│ │ └── telegram_bot/ +│ │ ├── server.py # 텔레귞랚 뮇 서버 (명령얎 핞듀러) +│ │ └── runner.py # 텔레귞랚 뮇 독늜 프로섞슀 싀행Ʞ +│ │ +│ └── utils/ # [Util] 유틞늬티 +│ ├── ipc.py # SharedMemory + Command Queue IPC +│ ├── process_tracker.py # PID 추적 & 좀비 정늬 & Watchdog +│ ├── monitor.py # CPU/GPU/RAM 서킷 람레읎컀 +│ └── performance_db.py # 음별 슀냅샷 & 맀맀 Ʞ록 영구 저장 +│ +├── data/ # [Runtime Data] +│ ├── watchlist.json # 현재 감시 종목 늬슀튞 +│ ├── daily_trade_history.json # 음음 맀맀 Ʞ록 +│ ├── kis_token.json # KIS OAuth 토큰 캐시 +│ ├── peak_prices.json # 튞레음링 슀탑용 최고가 +│ ├── ensemble_history.json # AdaptiveEnsemble 가쀑치 + 맀맀 히슀토늬 (종목별) +│ ├── models/ # LSTM 첎크포읞튞 (종목별 .pt 파음) +│ └── performance/ # 성곌 데읎터 (daily_snapshots, trade_records) +│ +└── tests/ # 테슀튞 +``` + +--- + +## 3. 핵심 몚듈 상섞 + +### 3.1 AutoTradingBot (`modules/bot.py`) + +**메읞 튞레읎딩 룚프** — 장 시작(09:00) ~ 장 마감(15:30) 사읎에 자동 싀행 + +``` +[v3.1 죌요 Ʞ능] +├── ATR êž°ë°˜ 동적 손절/익절 + 튞레음링 슀탑 +├── Kelly Criterion 포지션 사읎징 (싀전 승률·손익비 êž°ë°˜, Half-Kelly) +├── AdaptiveEnsemble 연동 (맀도 후 가쀑치 자동 학습) +├── 당음 누적 맀수 추적 (_today_buy_total) - KIS T+2 믞찚감 볎완 +├── 사읎큎당 최대 맀수 종목 수 제한 (MAX_BUY_PER_CYCLE) +├── ProcessPoolExecutor 병렬 분석 (워컀 1개, OOM 대응 자동 재시작) +├── 음별 자산 슀냅샷 (09:05~09:15) +├── 죌간 성곌 평가 (월요음 아칚) +├── CPU 서킷 람레읎컀 연동 +└── IPC Command Queue 폎링 (텔레귞랚 명령 처늬) +``` + +**잔고 추적 로직 (v3.1 — 곌맀수 방지)**: +``` +KIS get_balance() → raw_deposit (dnca_tot_amt) + ↓ +max_daily_buy = raw_deposit × MAX_DAILY_BUY_RATIO (80%) +tracking_deposit = max_daily_buy - effective_today_buy + ↑ + max(kis_today_buy, self._today_buy_total) + (KIS thdt_buy_amt vs 로컬 누적 쀑 큰 값) +``` +- `_today_buy_total`: 읞슀턎슀 변수, 사읎큎 간 유지 (09:00 늬셋) +- `_buy_scores`: BUY 시 신혞 점수 저장 → SELL 시 `record_trade()` 전달 + +**run_cycle() 흐멄**: +1. 시슀템 헬슀 첎크 (CPU/GPU/RAM) +2. 거시겜제 분석 (KOSPI/KOSDAQ/MSI) +3. 위험 상태별 ë¶„êž° (SAFE/CAUTION/DANGER) +4. Watchlist 종목 OHLCV 수집 (KIS 비동Ʞ 배치) +5. 잔고 조회 + 당음 누적 맀수 찚감 → 싀제 가용 예수ꞈ 계산 +6. `ProcessPoolExecutor`로 종목 병렬 분석 (Kelly Criterion + Ensemble 가쀑치) +7. 앙상랔 점수 êž°ë°˜ 맀수/맀도 판당 (사읎큎당 MAX_BUY_PER_CYCLE 제한) +8. 죌묞 싀행 & 결곌 텔레귞랚 알늌 +9. 맀도 시 `record_trade()` → Ensemble 가쀑치 학습 +10. IPC 상태 갱신 + +### 3.2 AI 분석 파읎프띌읞 + +``` + ┌─────────────────────┐ + │ analyze_stock_ │ + │ process() │ + │ (strategy/process)│ + └─────────┬───────────┘ + │ + ┌─────────────────────┌────────────────────┐ + â–Œ â–Œ â–Œ +┌───────────────┐ ┌────────────────┐ ┌─────────────────┐ +│ Technical │ │ Deep Learning │ │ LLM (Ollama) │ +│ Analyzer │ │ LSTM │ │ Sentiment │ +│ (Ʞ술적 지표) │ │ (죌가 예잡) │ │ (뉎슀 감성분석) │ +├──────────────── ├───────────────── ├────────────────── +│ RSI 25% │ │ Attention-LSTM │ │ qwen2.5:7b │ +│ 읎격도 15% │ │ 4L×512H │ │ JSON 포맷 요청 │ +│ MACD 15% │ │ 7찚원 플처 │ │ 뉎슀+지표 통합 │ +│ Stochastic 5% │ │ 60음 시퀀슀 │ │ 감성+신뢰도 │ +│ BB 15% │ │ GPU 가속 │ │ │ +│ ADX 15% │ │ 종목별 몚덞 │ │ │ +│ MTF 10% │ │ (ModelRegistry)│ │ │ +│ OBV ±볎너슀 │ │ │ │ │ +└───────┬───────┘ └───────┬────────┘ └───────┬─────────┘ + │ │ │ + └──────────┬────────┘ │ + â–Œ │ + ┌─────────────────┐ │ + │ AdaptiveEnsemble│ ◄───────────────────┘ + │ (학습형 가쀑치) │ + ├────────────────── + │ get_weights() │ ← 곌거 맀맀 결곌 반영 + │ (ADX+macro+conf)│ 크Ʞ 가쀑 정확도 Ʞ쀀 + │ 겜계: 0.10~0.65 │ Water-Filling 정규화 + │ Kelly Fraction │ ← 승률·손익비 êž°ë°˜ + └────────┬────────┘ + â–Œ + ┌────────────────┐ + │ 맀수/맀도/홀드 │ + │ 최종 판당 │ + └────────────────┘ +``` + +#### 3.2.1 Deep Learning — Attention-LSTM (`analysis/deep_learning.py`) + +| 항목 | 값 | +|------|-----| +| **아킀텍처** | 4-Layer Stacked LSTM + Attention + FC | +| **Hidden Size** | 512 | +| **Input Features** | 7 (close, open, high, low, volume_norm, rsi_14, macd_hist) | +| **시퀀슀 Ꞟ읎** | 60음 | +| **학습 에포크** | 최대 200 (Early Stopping patience=15) | +| **빠륞 재학습** | 30 에포크 (첎크포읞튞 졎재 시) | +| **쿚닀욎** | 1200쎈 (20분, 동음 종목 재학습 방지) | +| **ModelRegistry** | LRU 방식, 최대 5개 몚덞 동시 적재 | +| **첎크포읞튞** | `data/models/{ticker}_v3.pt` | +| **GPU ꎀ늬** | LSTM 학습 시 Ollama 자동 얞로드/늬로드 | + +#### 3.2.2 Ʞ술적 분석 (`analysis/technical.py`) + +`TechnicalAnalyzer.get_technical_score()` → 0.0 ~ 1.0 통합 점수 + +| 지표 | 비쀑 | 섀명 | +|------|------|------| +| RSI (14음) | 25% | Wilder 방식, 30 읎하 곌맀도/70 읎상 곌맀수 | +| 읎동평균 읎격도 | 15% | 20음 MA 대비 현재가 위치 | +| MACD | 15% | 12/26/9, 히슀토귞랚 방향 | +| Stochastic | 5% | Fast %K/%D (14/3/3) | +| Bollinger Bands | 15% | 20음/2σ, %B 위치 + 밮드폭 | +| ADX | 15% | 추섞 강도 (>25 강한 추섞) | +| Multi-Timeframe | 10% | 5음/20음/60음 추섞 음ꎀ성 | +| OBV | ±0.1 볎너슀 | 거래량 êž°ë°˜ 맀집/분산 감지 | + +추가 Ʞ능: +- `calculate_atr()` → ATR êž°ë°˜ 동적 손절/익절 +- `calculate_dynamic_sl_tp()` → 변동성 적응형 SL/TP +- `calculate_obv()` → 슀마튞 빾니 닀읎버전슀 감지 + +#### 3.2.3 거시겜제 분석 (`analysis/macro.py`) + +```python +MacroAnalyzer.get_macro_status(kis_client) → { + "status": "SAFE" | "CAUTION" | "DANGER", + "risk_score": int, + "indicators": { + "KOSPI": {"price", "change", "high", "low", "prev_close", "volume"}, + "KOSDAQ": {"price", "change", ...}, + "KOSPI200":{"price", "change", ...}, + "MSI": float # Market Stress Index (0~100) + } +} +``` + +- **SAFE** (risk_score < 1): 정상 맀맀 +- **CAUTION** (1 ≀ risk_score < 3): 맀수 규몚 축소 +- **DANGER** (risk_score ≥ 3): 맀수 쀑닚, 볎유분만 ꎀ늬 + +#### 3.2.4 앙상랔 (`analysis/ensemble.py`) + +`AdaptiveEnsemble` — 곌거 맀맀 결곌 êž°ë°˜ 가쀑치 자동 조정 + Kelly Criterion: + +**가쀑치 학습 흐멄**: +``` +BUY 첎결 → bot._buy_scores[ticker] = {tech, sentiment, lstm} 저장 +SELL 첎결 → ensemble.record_trade(ticker, ..., outcome_pct=yld) + → _update_weights() → EMA(alpha=0.10) 가쀑치 점진 조정 + → _save() → data/ensemble_history.json +워컀 프로섞슀 → reload_if_stale() → 파음 mtime 감지 시 재로드 +``` + +**죌요 메서드**: +- `get_weights(ticker, adx, macro_state, ai_confidence)` → `SignalWeights` + - 시장 컚텍슀튞 (strong_trend/sideways/danger/default) 별 Ʞ볞 가쀑치 + - 종목별 최귌 10거래 크Ʞ 가쀑 정확도 반영 + - ai_confidence >= 0.75 → LSTM 가쀑치 +25% (confidence 상한 0.80 반영) +- `get_kelly_fraction(ticker, half_kelly=True)` → 0.03~0.25 범위 투자 비쀑 + - f* = (p·b - q) / b (p=승률, b=손익비) + - 거래 데읎터 < 10걎 → 볎수적 Ʞ볞값 8% + - Half-Kelly 적용윌로 변동성 곌대추정 볎완 +- `compute_ensemble_score(tech, sentiment, lstm, investor, weights)` → 통합 점수 +- `reload_if_stale()` → 파음 mtime êž°ë°˜ cross-process 동Ʞ화 + +**`SignalWeights.normalize()` — Water-Filling 알고늬슘**: +- 겜계(0.10~0.65) 위반 시 핎당 값을 겜계에 고정, 나뚞지에 잔여 비쀑 비례 배분 +- 2ì°š 정규화(합=1 볎장)와 겜계 큎랚핑읎 상충하는 묞제 핎결 +- 영구 저장: `data/ensemble_history.json` (가쀑치 + 맀맀 히슀토늬 통합) + +#### 3.2.5 성곌 평가 (`analysis/evaluator.py`) + +`PerformanceEvaluator.generate_weekly_report()`: +- 핵심 지표: 쎝수익률, Sharpe Ratio, MDD, 승률, 평균손익비, KOSPI 상ꎀ도 +- S/A/B/C/D/F 등꞉ 산출 +- **5명 전묞가 LLM 팹널** (Ollama): 각각 닀륞 ꎀ점윌로 평가 +- HTML 포맷 텔레귞랚 죌간 볎고서 자동 생성 + +--- + +## 4. 왞부 서비슀 연동 + +### 4.1 한국투자슝권 KIS API (`services/kis.py`) + +#### 읞슝 + +```python +KISClient.ensure_token() +# OAuth 2.0 → access_token 발꞉ → data/kis_token.json에 캐시 +# 토큰 만료 시 자동 갱신 (_request_api에서 처늬) +``` + +| 섀정 | 몚의투자 | 싀전투자 | +|------|---------|---------| +| Base URL | `openapivts.koreainvestment.com:29443` | `openapi.koreainvestment.com:9443` | +| 환겜변수 | `KIS_VIRTUAL_APP_KEY/SECRET/ACCOUNT` | `KIS_REAL_APP_KEY/SECRET/ACCOUNT` | +| 전환 | `.env` → `KIS_ENV_TYPE=virtual` | `.env` → `KIS_ENV_TYPE=real` | + +#### API 슀로틀링 + +- 쎈당 2회 제한 (`_throttle()` — 0.5쎈 딜레읎) +- 토큰 만료 시 자동 갱신 (403 → retry with new token) + +#### 죌요 API 엔드포읞튞 맀핑 + +| Ʞ능 | KISClient 메서드 | KIS TR_ID | +|------|-----------------|-----------| +| 잔고 조회 | `get_balance()` → `{holdings, total_eval, deposit, today_buy_amt}` | `VTTC8434R` (몚의) / `TTTC8434R` (싀전) | +| 죌묞 (맀수/맀도) | `order()` | `VTTC0802U` / `VTTC0801U` (몚의) | +| 현재가 조회 | `get_current_price()` | `FHKST01010100` | +| 음뎉 OHLCV | `get_daily_ohlcv()` → `_get_daily_ohlcv_by_range()` | `FHKST03010100` | +| 음뎉 종가 | `get_daily_price()` → `_get_daily_price_by_range()` | `FHKST03010100` | +| 거래량 순위 | `get_volume_rank()` | `FHPST01710000` | +| 지수 현재가 | `get_current_index()` | `FHPUP02100000` | +| 지수 음뎉 | `get_daily_index_price()` | `FHKUP03500100` | +| 투자자 동향 | `get_investor_trend()` | `FHKST01010900` | +| Hash Key | `get_hash_key()` | - | + +#### 비동Ʞ 큎띌읎얞튞 (`KISAsyncClient`) + +`aiohttp` êž°ë°˜ — 닀쀑 종목 동시 수집용: +- `get_daily_price_batch()` — 여러 종목 음뎉 병렬 수집 +- `get_daily_ohlcv_batch()` — 여러 종목 OHLCV 병렬 수집 +- `get_investor_trends_batch()` — 여러 종목 투자자 동향 병렬 수집 + +--- + +### 4.2 Ollama LLM (`services/ollama.py`) + +| 섀정 | 값 | +|------|-----| +| **몚덞** | `qwen2.5:7b-instruct-q4_K_M` (VRAM ~4GB) | +| **API URL** | `http://localhost:11434` | +| **Context Window** | 4096 토큰 | +| **Max Output** | 200 토큰 | +| **Temperature** | 0.1 (결정론적, JSON 안정성) | +| **Keep Alive** | 5분 (비활성 시 자동 얞로드) | +| **Timeout** | 90쎈 | +| **CPU Threads** | 8 (9800X3D 최적화) | +| **응답 포맷** | JSON (format: "json") | + +**GPU 충돌 방지**: +- LSTM 학습 쀑 → Ollama 추론 최대 60쎈 대Ʞ +- VRAM > 12GB → 몚덞 슉시 얞로드 (`keep_alive=0`) +- LSTM 학습 전 → Ollama 자동 얞로드, 학습 후 → 자동 늬로드 + +--- + +### 4.3 뉎슀 수집 (`services/news.py`) + +- **소슀**: Google News RSS (`news.google.com/rss/search`) +- **동Ʞ**: `NewsCollector.get_market_news()` — 시장 음반 뉎슀 5걎 +- **비동Ʞ**: `AsyncNewsCollector` + - `get_market_news_async()` — 시장 뉎슀 (5분 캐시) + - `get_stock_news_async()` — 종목별 뉎슀 (5분 캐시) + +--- + +## 5. 웹 백엔드 서버 API (FastAPI) + +### 5.1 서버 정볎 + +| 항목 | 값 | +|------|-----| +| **프레임워크** | FastAPI + Uvicorn | +| **혞슀튞** | `0.0.0.0:8000` | +| **NAS 백엔드** | `http://192.168.45.54:18500` (웹 프론튞엔드 서버) | + +### 5.2 API 엔드포읞튞 + +#### `GET /` — 서버 상태 + +```json +{ + "status": "online", + "gpu_vram": 4.2, + "service": "Windows AI Server (Refactored)" +} +``` + +#### `GET /trade/balance` | `GET /api/trade/balance` — 잔고 조회 + +KIS API륌 통핎 현재 계좌 잔고(예수ꞈ, 볎유종목, 평가ꞈ액) 조회. + +```json +{ + "total_eval": 10500000, + "deposit": 5000000, + "holdings": [ + { + "ticker": "005930", + "name": "삌성전자", + "qty": 10, + "avg_price": 72000, + "current_price": 73500, + "profit_rate": 2.08 + } + ] +} +``` + +#### `POST /trade/order` | `POST /api/trade/order` — 수동 죌묞 + +```json +// Request Body +{ + "ticker": "005930", + "action": "BUY", // "BUY" | "SELL" + "quantity": 10 +} + +// Response +{ + "status": "executed", + "kis_result": { ... } +} +``` + +#### `POST /analyze/portfolio` | `POST /api/analyze/portfolio` — AI 포튞폎늬였 분석 + +현재 잔고 + 최신 뉎슀륌 종합하여 Ollama LLM윌로 포튞폎늬였 분석. + +```json +{ + "analysis": "... AI 분석 결곌 (한국얎) ..." +} +``` + +### 5.3 NAS 서버와의 통신 흐멄 + +``` +┌──────────────┐ HTTP Request ┌────────────────────┐ +│ NAS Backend │ ─────────────────────► │ Windows AI Server │ +│ (웹 프론튞) │ │ (FastAPI:8000) │ +│ :18500 │ ◄──────────────────── │ │ +│ │ JSON Response │ │ +└──────────────┘ └────────────────────┘ + +[통신 시나늬였] +1. 웹 → /api/trade/balance → 잔고 데읎터 표시 +2. 웹 → /api/trade/order → 수동 맀수/맀도 싀행 +3. 웹 → /api/analyze/portfolio → AI 분석 결곌 표시 +4. 웹 → / → 서버 상태 및 GPU 정볎 +``` + +- **NAS 서버** (`192.168.45.54:18500`): 웹 프론튞엔드 혞슀팅, 사용자 읞터페읎슀 제공 +- **Windows AI 서버** (`0.0.0.0:8000`): GPU 연산, KIS API 통신, AI 분석 처늬 +- 낎부 넀튞워크 (LAN) 통신, 왞부 ë…žì¶œ 없음 + +--- + +## 6. 텔레귞랚 뮇 섀정 & 명령얎 + +### 6.1 환겜변수 + +```env +TELEGRAM_BOT_TOKEN=8546032918:AAF5GJcP92DrtpSoQdaimMIZe7bz_xtGGPo +TELEGRAM_CHAT_ID=7388056964 +``` + +### 6.2 뮇 프로섞슀 아킀텍처 + +``` +runner.py + └── run_telegram_bot_standalone() + ├── SharedIPC 쎈Ʞ화 (lock, queue, shutdown_event) + ├── TelegramBotServer 생성 + ├── IPC에서 쎈Ʞ 데읎터 로드 + ├── bot_server.run() (python-telegram-bot polling) + └── Conflict 감지 시 백였프 재시도 (최대 10회) +``` + +- **띌읎람러늬**: `python-telegram-bot` (Application, CommandHandler) +- **메시지 포맷**: HTML (`parse_mode="HTML"`) +- **동시 업데읎튞**: `concurrent_updates=True` +- **로깅**: `telegram_bot.log` (파음 + 윘솔) + +### 6.3 명령얎 목록 + +| 명령얎 | 섀명 | 데읎터 소슀 | +|--------|------|------------| +| `/start` | 뮇 시작 & 전첎 명령얎 안낎 | - | +| `/status` | 뮇 상태, 시장 지수, AI 몚덞 상태 | IPC (SharedMemory) | +| `/portfolio` | 볎유 종목 & 수익률 조회 | IPC → FakeKIS.get_balance() | +| `/watchlist` | 현재 감시 종목 늬슀튞 | IPC → watchlist 데읎터 | +| `/update_watchlist` | Watchlist 슉시 업데읎튞 요청 | Command Queue → 메읞 뮇 | +| `/macro` | 거시겜제 분석 (KOSPI/KOSDAQ/MSI) | IPC → macro_indices | +| `/system` | CPU/GPU/RAM 시슀템 상태 | IPC → gpu_status + psutil | +| `/ai` | AI 몚덞 상태 (VRAM, 학습 여부) | IPC → gpu_status | +| `/restart` | 메읞 뮇 재시작 명령 | Command Queue | +| `/stop` | 뮇 종료 | shutdown_event.set() | +| `/exec ` | 서버 쉘 명령얎 직접 싀행 | subprocess (10쎈 타임아웃) | +| `/evaluate` | 슉시 성곌 평가 볎고서 생성 | PerformanceEvaluator | + +### 6.4 TelegramMessenger (`services/telegram.py`) + +닚방향 알늌 전용 (메읞 뮇 → 사용자): +- **비동Ʞ 전송**: `threading.Thread(daemon=True)` — Fire-and-forget +- **HTML 파싱**: 마크닀욎 에러 방지 +- 맀맀 싀행, 서버 시작/종료, 에러 알늌 등에 사용 + +### 6.5 Conflict 처늬 + +텔레귞랚 뮇 API는 동시에 하나의 polling 읞슀턎슀만 허용: +- `Conflict` 에러 감지 시 지수 백였프 (5s → 10s → ... → 30s) +- 최대 10회 재시도 후 프로섞슀 종료 +- Watchdog가 감지하여 자동 재시작 + +--- + +## 7. 환겜 섀정 (`modules/config.py`) + +### 7.1 죌요 섀정 상수 + +| 귞룹 | í‚€ | 값 | 섀명 | +|------|-----|-----|------| +| **맀맀** | `MAX_INVESTMENT_PER_STOCK` | 3,000,000원 | 종목당 최대 투자ꞈ | +| **맀맀** | `MAX_BUY_PER_CYCLE` | 2 | 사읎큎당 최대 맀수 종목 수 (env: `MAX_BUY_PER_CYCLE`) | +| **맀맀** | `MAX_DAILY_BUY_RATIO` | 0.80 | 예수ꞈ 대비 음음 최대 맀수 비윚 (env: `MAX_DAILY_BUY_RATIO`) | +| **IPC** | `SHM_NAME` | `web_ai_bot_ipc` | SharedMemory 읎늄 | +| **IPC** | `SHM_SIZE` | 131,072 (128KB) | SharedMemory 크Ʞ | +| **IPC** | `IPC_STALENESS` | 600쎈 | 데읎터 유횚 êž°ê°„ | +| **GPU** | `VRAM_WARNING_THRESHOLD` | 12.0 GB | VRAM 겜고 임계값 | +| **프로섞슀** | `WATCHDOG_INTERVAL` | 30쎈 | 헬슀첎크 간격 | +| **프로섞슀** | `MAX_RESTART_COUNT` | 3 | 최대 자동 재시작 횟수 | +| **LSTM** | `LSTM_COOLDOWN` | 1,200쎈 | 동음 종목 재학습 방지 | +| **LSTM** | `LSTM_FAST_EPOCHS` | 30 | 빠륞 재학습 에포크 | +| **CPU** | `CPU_CIRCUIT_BREAKER_THRESHOLD` | 92% | 서킷 람레읎컀 임계값 | +| **CPU** | `CPU_CIRCUIT_BREAKER_CONSECUTIVE` | 2회 | 연속 쎈곌 시 발동 | +| **Ollama** | `OLLAMA_NUM_CTX` | 4,096 | 컚텍슀튞 윈도우 | +| **Ollama** | `OLLAMA_NUM_PREDICT` | 200 | 최대 출력 토큰 | +| **Ollama** | `OLLAMA_NUM_THREAD` | 8 | CPU 슀레드 수 | +| **Network** | `HTTP_TIMEOUT` | 10쎈 | Ʞ볞 HTTP 요청 타임아웃 | + +### 7.2 .env 파음 구조 + +```env +# NAS Backend (웹 프론튞엔드 서버) +NAS_API_URL=http://192.168.45.54:18500 + +# Ollama LLM +OLLAMA_API_URL=http://localhost:11434 +OLLAMA_MODEL=qwen2.5:7b-instruct-q4_K_M + +# KIS API (virtual/real 전환) +KIS_ENV_TYPE=virtual +KIS_REAL_APP_KEY=... +KIS_REAL_APP_SECRET=... +KIS_REAL_ACCOUNT=XXXXXXXX-XX +KIS_VIRTUAL_APP_KEY=... +KIS_VIRTUAL_APP_SECRET=... +KIS_VIRTUAL_ACCOUNT=XXXXXXXX-XX + +# Telegram Bot +TELEGRAM_BOT_TOKEN=... +TELEGRAM_CHAT_ID=... +``` + +--- + +## 8. 욎영 가읎드 + +### 8.1 시작 방법 + +```bash +# 음반 시작 +python main_server.py + +# LSTM 사전학습 후 자동 시작 +python warmup_and_restart.py + +# 텔레귞랚 뮇만 당독 싀행 (디버깅용) +python -m modules.services.telegram_bot.runner +``` + +### 8.2 좀비 프로섞슀 ꎀ늬 + +- `main_server.py` 싀행 시 자동윌로 읎전 좀비 프로섞슀 정늬 +- `pids.txt` êž°ë°˜ → 메몚늬 êž°ë°˜ PID 추적윌로 전환 완료 +- 수동 확읞: `Get-Process python` (PowerShell) + +### 8.3 로귞 파음 + +| 파음 | 용도 | +|------|------| +| `server.log` | Uvicorn 서버 로귞 | +| `telegram_bot.log` | 텔레귞랚 뮇 로귞 | +| `warmup.log` | LSTM 사전학습 진행 로귞 | +| `bot_output.log` | 튞레읎딩 뮇 출력 로귞 | + +### 8.4 튞러랔슈팅 + +| 슝상 | 원읞 | 핎결 | +|------|------|------| +| KIS 403 Forbidden | 토큰 만료 또는 Rate Limit | `data/kis_token.json` 삭제 후 재시작 | +| Telegram Conflict | 읎전 뮇 프로섞슀 믞종료 | `main_server.py` 재시작 (자동 정늬) | +| GPU OOM | LSTM + Ollama 동시 적재 | `VRAM_WARNING_THRESHOLD` 낮추Ʞ | +| CPU 100% 고정 | 좀비 워컀 프로섞슀 | `main_server.py` 재시작 | +| IPC 데읎터 였래됚 | 메읞 뮇 크래시 | Watchdog 자동 재시작 확읞, 수동 재시작 | +| 예수ꞈ 쎈곌 맀수 | KIS 몚의투자 T+2 믞찚감 | `MAX_DAILY_BUY_RATIO` / `MAX_BUY_PER_CYCLE` 조정 | +| Kelly 비쀑읎 너묎 낮음 | 거래 Ʞ록 부족 (< 10걎) | 쎈Ʞ에는 Ʞ볞값 8% 사용, 거래 누적 후 자동 조정 | +| 앙상랔 가쀑치 갱신 안 됚 | 맀도 첎결 없음 또는 `_buy_scores` 누띜 | 뮇 재시작 전 맀도 완료 확읞; `data/ensemble_history.json` 확읞 | + +--- + +## 9. 데읎터 흐멄 요앜 + +``` +[시장 개장 전] + WatchlistManager → 뉎슀 분석 → Watchlist 갱신 + +[장쀑 사읎큎 (≈5분 간격)] + 1. SystemMonitor.check_health() → CPU/GPU 확읞 + 2. MacroAnalyzer.get_macro_status() → 시장 상태 판당 + 3. KIS → get_balance() → raw_deposit - today_buy_total = 가용 예수ꞈ + 4. KIS → get_daily_ohlcv_batch() → OHLCV 수집 + 5. ProcessPool → analyze_stock_process() × N종목 + ├── ensemble.reload_if_stale() → 파음 mtime 감지 시 가쀑치 재로드 + ├── TechnicalAnalyzer → Ʞ술적 점수 + ├── PricePredictor → LSTM 예잡 + ├── OllamaManager → LLM 감성 분석 + ├── AdaptiveEnsemble.get_weights() → 학습된 동적 가쀑치 + └── calculate_position_size() → Kelly Criterion 수량 산출 + 6. 맀수 판당 → 예수ꞈ 확읞 → KIS 죌묞 + ├── _buy_scores[ticker] 저장 (앙상랔 학습용) + ├── _today_buy_total += 맀수ꞈ액 + └── buys_this_cycle++ (MAX_BUY_PER_CYCLE 제한) + 7. 맀도 판당 → KIS 죌묞 + └── ensemble.record_trade() → 가쀑치 학습 + ensemble_history.json 저장 + 8. SharedIPC.write_status() → 텔레귞랚 뎇에 공유 + 9. TelegramMessenger → 결곌 알늌 + +[장 마감 후] + PerformanceDB.save_daily_snapshot() → 음별 자산 Ʞ록 + Evaluator → 죌간 볎고서 (월요음) +``` + +--- + +## 10. 버전 변겜 읎력 + +### v3.1 (2026-03-19) — 잔고 ꎀ늬 & 앙상랔 학습 완성 + +**버귞 수정**: +- `tracking_deposit` 사읎큎 간 쎈Ʞ화 묞제 → `_today_buy_total` 읞슀턎슀 변수로 누적 추적 +- KIS 몚의투자 T+2 믞찚감윌로 읞한 예수ꞈ 쎈곌 맀수 방지 +- `ai_confidence >= 0.85` 임계값 버귞 (LSTM confidence 상한 0.80 믞반영) → 0.75로 수정 +- OHLCV 플처 누띜 시 silent fallback → 겜고 로귞 출력 + +**신규 Ʞ능**: +- `MAX_BUY_PER_CYCLE`: 사읎큎당 최대 맀수 종목 수 제한 (Ʞ볞 2) +- `MAX_DAILY_BUY_RATIO`: 예수ꞈ 대비 음음 최대 맀수 비윚 (Ʞ볞 80%) +- `kis.get_balance()` → `today_buy_amt` 필드 추가 (`thdt_buy_amt`) + +**앙상랔 (`analysis/ensemble.py`)**: +- `AdaptiveEnsemble`을 `process.py`에 싀제 연동 (하드윔딩 가쀑치 제거) +- `get_kelly_fraction()`: Half-Kelly Criterion 포지션 비쀑 계산 추가 +- `SignalWeights.normalize()`: Water-Filling 알고늬슘윌로 겜계 위반 묞제 핎결 +- `_accuracy()` 읎진 지표 제거 → `_accuracy_weighted()` (크Ʞ 가쀑) 통음 +- `reload_if_stale()`: 파음 mtime êž°ë°˜ cross-process 동Ʞ화 + +**포지션 사읎징 (`strategy/process.py`)**: +- `calculate_position_size()`: 하드윔딩 10% → Kelly Criterion (곌거 승률·손익비 êž°ë°˜) +- `bot.py` 쀑복 계산 제거 → 워컀의 `suggested_qty` 직접 사용 + +**앙상랔 학습 룚프 (`bot.py`)**: +- BUY 첎결 시 `_buy_scores[ticker]` 신혞 점수 저장 +- SELL 첎결 시 `ensemble.record_trade()` → `ensemble_history.json` 갱신 +- 워컀 프로섞슀는 `reload_if_stale()`로 자동 반영 diff --git a/README.md b/signal_v1/README.md similarity index 100% rename from README.md rename to signal_v1/README.md diff --git a/backtest_runner.py b/signal_v1/backtest_runner.py similarity index 100% rename from backtest_runner.py rename to signal_v1/backtest_runner.py diff --git a/backtester.py b/signal_v1/backtester.py similarity index 100% rename from backtester.py rename to signal_v1/backtester.py diff --git a/main_server.py b/signal_v1/main_server.py similarity index 100% rename from main_server.py rename to signal_v1/main_server.py diff --git a/modules/__init__.py b/signal_v1/modules/__init__.py similarity index 100% rename from modules/__init__.py rename to signal_v1/modules/__init__.py diff --git a/modules/analysis/ai_council.py b/signal_v1/modules/analysis/ai_council.py similarity index 100% rename from modules/analysis/ai_council.py rename to signal_v1/modules/analysis/ai_council.py diff --git a/modules/analysis/backtest.py b/signal_v1/modules/analysis/backtest.py similarity index 100% rename from modules/analysis/backtest.py rename to signal_v1/modules/analysis/backtest.py diff --git a/modules/analysis/deep_learning.py b/signal_v1/modules/analysis/deep_learning.py similarity index 100% rename from modules/analysis/deep_learning.py rename to signal_v1/modules/analysis/deep_learning.py diff --git a/modules/analysis/ensemble.py b/signal_v1/modules/analysis/ensemble.py similarity index 100% rename from modules/analysis/ensemble.py rename to signal_v1/modules/analysis/ensemble.py diff --git a/modules/analysis/evaluator.py b/signal_v1/modules/analysis/evaluator.py similarity index 100% rename from modules/analysis/evaluator.py rename to signal_v1/modules/analysis/evaluator.py diff --git a/modules/analysis/macro.py b/signal_v1/modules/analysis/macro.py similarity index 98% rename from modules/analysis/macro.py rename to signal_v1/modules/analysis/macro.py index c373b6c..fcf0e11 100644 --- a/modules/analysis/macro.py +++ b/signal_v1/modules/analysis/macro.py @@ -1,6 +1,7 @@ from datetime import datetime import time import os +from pathlib import Path from dotenv import load_dotenv from modules.services.kis import KISClient @@ -130,7 +131,7 @@ class MacroAnalyzer: if __name__ == "__main__": # 테슀튞륌 위한 윔드 - load_dotenv() + load_dotenv(Path(__file__).parent.parent.parent / ".env") # 환겜변수 로딩 및 큎띌읎얞튞 쎈Ʞ화 if os.getenv("KIS_ENV_TYPE") == "real": diff --git a/modules/analysis/market_regime.py b/signal_v1/modules/analysis/market_regime.py similarity index 100% rename from modules/analysis/market_regime.py rename to signal_v1/modules/analysis/market_regime.py diff --git a/modules/analysis/model_validator.py b/signal_v1/modules/analysis/model_validator.py similarity index 100% rename from modules/analysis/model_validator.py rename to signal_v1/modules/analysis/model_validator.py diff --git a/modules/analysis/technical.py b/signal_v1/modules/analysis/technical.py similarity index 100% rename from modules/analysis/technical.py rename to signal_v1/modules/analysis/technical.py diff --git a/modules/bot.py b/signal_v1/modules/bot.py similarity index 100% rename from modules/bot.py rename to signal_v1/modules/bot.py diff --git a/modules/config.py b/signal_v1/modules/config.py similarity index 98% rename from modules/config.py rename to signal_v1/modules/config.py index e03c035..3b3dce6 100644 --- a/modules/config.py +++ b/signal_v1/modules/config.py @@ -1,9 +1,10 @@ import os import sys +from pathlib import Path from dotenv import load_dotenv # .env 파음 로드 -load_dotenv() +load_dotenv(Path(__file__).parent.parent / ".env") class Config: # 1. Ʞ볞 섀정 diff --git a/modules/services/kis.py b/signal_v1/modules/services/kis.py similarity index 100% rename from modules/services/kis.py rename to signal_v1/modules/services/kis.py diff --git a/modules/services/llm_client.py b/signal_v1/modules/services/llm_client.py similarity index 100% rename from modules/services/llm_client.py rename to signal_v1/modules/services/llm_client.py diff --git a/modules/services/news.py b/signal_v1/modules/services/news.py similarity index 100% rename from modules/services/news.py rename to signal_v1/modules/services/news.py diff --git a/modules/services/news_snapshot.py b/signal_v1/modules/services/news_snapshot.py similarity index 100% rename from modules/services/news_snapshot.py rename to signal_v1/modules/services/news_snapshot.py diff --git a/modules/services/ollama.py b/signal_v1/modules/services/ollama.py similarity index 100% rename from modules/services/ollama.py rename to signal_v1/modules/services/ollama.py diff --git a/modules/services/telegram.py b/signal_v1/modules/services/telegram.py similarity index 100% rename from modules/services/telegram.py rename to signal_v1/modules/services/telegram.py diff --git a/modules/services/telegram_bot/runner.py b/signal_v1/modules/services/telegram_bot/runner.py similarity index 97% rename from modules/services/telegram_bot/runner.py rename to signal_v1/modules/services/telegram_bot/runner.py index ddd8ab3..7d6664f 100644 --- a/modules/services/telegram_bot/runner.py +++ b/signal_v1/modules/services/telegram_bot/runner.py @@ -6,9 +6,10 @@ import os import sys import time import multiprocessing +from pathlib import Path from dotenv import load_dotenv -load_dotenv() +load_dotenv(Path(__file__).parent.parent.parent.parent / ".env") def run_telegram_bot_standalone(ipc_lock=None, command_queue=None, shutdown_event=None): diff --git a/modules/services/telegram_bot/server.py b/signal_v1/modules/services/telegram_bot/server.py similarity index 100% rename from modules/services/telegram_bot/server.py rename to signal_v1/modules/services/telegram_bot/server.py diff --git a/modules/services/telegram_bot/skill_runner.py b/signal_v1/modules/services/telegram_bot/skill_runner.py similarity index 100% rename from modules/services/telegram_bot/skill_runner.py rename to signal_v1/modules/services/telegram_bot/skill_runner.py diff --git a/modules/strategy/daily_ledger.py b/signal_v1/modules/strategy/daily_ledger.py similarity index 100% rename from modules/strategy/daily_ledger.py rename to signal_v1/modules/strategy/daily_ledger.py diff --git a/modules/strategy/process.py b/signal_v1/modules/strategy/process.py similarity index 100% rename from modules/strategy/process.py rename to signal_v1/modules/strategy/process.py diff --git a/modules/strategy/risk_gate.py b/signal_v1/modules/strategy/risk_gate.py similarity index 100% rename from modules/strategy/risk_gate.py rename to signal_v1/modules/strategy/risk_gate.py diff --git a/modules/utils/ipc.py b/signal_v1/modules/utils/ipc.py similarity index 100% rename from modules/utils/ipc.py rename to signal_v1/modules/utils/ipc.py diff --git a/modules/utils/market_calendar.py b/signal_v1/modules/utils/market_calendar.py similarity index 100% rename from modules/utils/market_calendar.py rename to signal_v1/modules/utils/market_calendar.py diff --git a/modules/utils/monitor.py b/signal_v1/modules/utils/monitor.py similarity index 100% rename from modules/utils/monitor.py rename to signal_v1/modules/utils/monitor.py diff --git a/modules/utils/performance_db.py b/signal_v1/modules/utils/performance_db.py similarity index 100% rename from modules/utils/performance_db.py rename to signal_v1/modules/utils/performance_db.py diff --git a/modules/utils/process_tracker.py b/signal_v1/modules/utils/process_tracker.py similarity index 100% rename from modules/utils/process_tracker.py rename to signal_v1/modules/utils/process_tracker.py diff --git a/theme_manager.py b/signal_v1/theme_manager.py similarity index 100% rename from theme_manager.py rename to signal_v1/theme_manager.py diff --git a/warmup_and_restart.py b/signal_v1/warmup_and_restart.py similarity index 100% rename from warmup_and_restart.py rename to signal_v1/warmup_and_restart.py diff --git a/watchlist_manager.py b/signal_v1/watchlist_manager.py similarity index 99% rename from watchlist_manager.py rename to signal_v1/watchlist_manager.py index 2b2e558..74b11c3 100644 --- a/watchlist_manager.py +++ b/signal_v1/watchlist_manager.py @@ -1,12 +1,13 @@ import json import os from datetime import datetime +from pathlib import Path from dotenv import load_dotenv from modules.services.kis import KISClient from modules.services.ollama import OllamaManager from modules.services.news import NewsCollector -load_dotenv() +load_dotenv(Path(__file__).parent.parent / ".env") class WatchlistManager: """ diff --git a/start.bat b/start.bat new file mode 100644 index 0000000..929e26d --- /dev/null +++ b/start.bat @@ -0,0 +1,3 @@ +@echo off +cd /d "%~dp0\signal_v1" +python main_server.py