feat: 프로젝트 기본 구조 구축

This commit is contained in:
2025-10-04 22:11:32 +09:00
parent 01403c7df4
commit ab99abad8a
36 changed files with 32356 additions and 199 deletions

412
STRATEGY_MODULES_README.md Normal file
View File

@@ -0,0 +1,412 @@
# 전략 모듈 구조
## 📁 디렉토리 구조
```
strategies/
├── __init__.py
├── base.py # 기본 클래스 및 레지스트리
├── implementations.py # 통합 임포트 모듈
├── models.py # Django 모델
├── views.py # Django 뷰
├── urls.py # URL 라우팅
└── impls/ # 전략 구현체 모듈
├── __init__.py # 모듈 통합
├── trend_following.py # 추세 추종 전략
├── mean_reversion.py # 평균 회귀 전략
├── volatility_breakout.py # 변동성 돌파 전략
└── asset_allocation.py # 자산 배분 전략
```
---
## 📊 전략 분류
### 1. 추세 추종(Trend Following) 전략
**파일**: `strategies/impls/trend_following.py`
이동평균선, 모멘텀 등 추세를 따라가는 전략들
#### 포함된 전략:
- **MovingAverageCrossover** (v1.0.0)
- 단기/장기 이동평균선 교차 전략
- 골든크로스/데드크로스 기반
- 파라미터: `short_window`, `long_window`
**사용 예시:**
```python
from strategies.impls.trend_following import MovingAverageCrossover
strategy = MovingAverageCrossover()
result = strategy.execute({
"short_window": 20,
"long_window": 50,
"initial_capital": 100000
})
```
---
### 2. 평균 회귀(Mean Reversion) 전략
**파일**: `strategies/impls/mean_reversion.py`
RSI, 볼린저밴드 등 과매수/과매도 구간에서 반대 방향으로 거래
#### 포함된 전략:
- **RSIMeanReversion** (v1.0.0)
- RSI 지표 기반 평균회귀
- 과매수(70)/과매도(30) 구간 역방향 거래
- 파라미터: `rsi_period`, `oversold_threshold`, `overbought_threshold`
**사용 예시:**
```python
from strategies.impls.mean_reversion import RSIMeanReversion
strategy = RSIMeanReversion()
result = strategy.execute({
"rsi_period": 14,
"oversold_threshold": 30,
"overbought_threshold": 70,
"initial_capital": 100000
})
```
---
### 3. 변동성 돌파(Volatility Breakout) 전략
**파일**: `strategies/impls/volatility_breakout.py`
볼린저 밴드, ATR 등 변동성 기반 돌파 전략들
#### 포함된 전략:
- **BollingerBandBreakout** (v2.0.0)
- 볼린저 밴드 상한/하한 돌파 전략
- 변동성 확장 구간 포착
- 파라미터: `period`, `std_dev`, `stop_loss`
**사용 예시:**
```python
from strategies.impls.volatility_breakout import BollingerBandBreakout
strategy = BollingerBandBreakout()
result = strategy.execute({
"period": 20,
"std_dev": 2.0,
"initial_capital": 100000
})
```
---
### 4. 자산 배분(Asset Allocation) 전략
**파일**: `strategies/impls/asset_allocation.py`
전술적 자산배분, 리스크 패리티 등 다양한 자산에 배분하는 전략들
#### 포함된 전략:
- **BoldAssetAllocation** (v1.0.0)
- 상대/절대 모멘텀 결합 전략
- 카나리아 유니버스 기반 크래시 보호
- 5가지 변형: BAA-G12, BAA-G4, BAA-G12/T3, BAA-G4/T2, BAA-SPY
- 실제 데이터 기반 포트폴리오 제안 기능
**사용 예시:**
```python
from strategies.impls.asset_allocation import BoldAssetAllocation
# 시뮬레이션 모드
strategy = BoldAssetAllocation()
result = strategy.execute({
"variant": "BAA-G12",
"initial_capital": 100000,
"use_real_data": False
})
# 실제 데이터 모드
result = strategy.execute({
"variant": "BAA-G4",
"initial_capital": 50000,
"use_real_data": True,
"as_of_date": "2024-01-31"
})
```
---
## 🔧 모듈 사용 방법
### 통합 임포트 (권장)
```python
# 모든 전략을 한 번에 임포트
from strategies import implementations
# 또는 특정 전략만
from strategies.implementations import (
MovingAverageCrossover,
BoldAssetAllocation
)
```
### 개별 모듈 임포트
```python
# 특정 카테고리의 전략만 필요한 경우
from strategies.impls.trend_following import MovingAverageCrossover
from strategies.impls.asset_allocation import BoldAssetAllocation
```
### 레지스트리 사용
```python
from strategies.base import StrategyRegistry
# 등록된 전략 조회
available = StrategyRegistry.list_strategies()
# 전략 인스턴스 생성
strategy = StrategyRegistry.get_strategy(
name="BoldAssetAllocation",
version="1.0.0"
)
```
---
## 새 전략 추가하기
### 1. 적절한 카테고리 선택
전략 유형에 따라 해당 파일 선택:
- 추세 추종 → `trend_following.py`
- 평균 회귀 → `mean_reversion.py`
- 변동성 돌파 → `volatility_breakout.py`
- 자산 배분 → `asset_allocation.py`
새 카테고리가 필요하면 새 파일 생성 (예: `arbitrage.py`)
### 2. 전략 클래스 작성
```python
# strategies/impls/your_category.py
from typing import Dict, Any
from ..base import BaseQuantStrategy, strategy
@strategy
class YourStrategy(BaseQuantStrategy):
"""전략 설명"""
@property
def name(self) -> str:
return "YourStrategy"
@property
def description(self) -> str:
return "전략에 대한 상세 설명"
@property
def version(self) -> str:
return "1.0.0"
@property
def default_parameters(self) -> Dict[str, Any]:
return {
"param1": "value1",
"param2": "value2"
}
def validate_parameters(self, parameters: Dict[str, Any]) -> bool:
# 파라미터 검증 로직
return True
def execute(self, parameters: Dict[str, Any] = None) -> Dict[str, Any]:
# 전략 실행 로직
return {
"strategy": self.name,
"result": "..."
}
```
### 3. 임포트 경로 추가
#### `strategies/impls/__init__.py`에 추가:
```python
from .your_category import YourStrategy
__all__ = [
# ... 기존 전략들
'YourStrategy',
]
```
#### `strategies/implementations.py`에 추가:
```python
from .impls.your_category import YourStrategy
__all__ = [
# ... 기존 전략들
'YourStrategy',
]
```
### 4. 자동 등록 확인
`@strategy` 데코레이터를 사용하면 자동으로 레지스트리에 등록됩니다.
```python
# 확인
python manage.py shell
>>> from strategies.base import StrategyRegistry
>>> StrategyRegistry.list_strategies()
# YourStrategy가 포함되어 있는지 확인
```
---
## 📝 모범 사례
### 1. 파일 조직
- 한 파일에 너무 많은 전략을 넣지 마세요 (최대 5개 권장)
- 유사한 특성의 전략끼리 그룹화
### 2. 명명 규칙
- 클래스명: PascalCase (예: `MovingAverageCrossover`)
- 파일명: snake_case (예: `trend_following.py`)
- 전략 이름(name): 클래스명과 동일
### 3. 문서화
- 각 파일 상단에 독스트링으로 카테고리 설명
- 각 전략 클래스에 독스트링으로 전략 설명
- 파라미터 의미를 주석으로 명시
### 4. 의존성 관리
- 공통 의존성: 파일 상단에 import
- 선택적 의존성: 함수/메서드 내부에서 import
```python
# 좋은 예
import time
import random
from typing import Dict, Any
from ..base import BaseQuantStrategy, strategy
@strategy
class MyStrategy(BaseQuantStrategy):
def execute(self, parameters):
# 여기서만 필요한 라이브러리
import some_optional_lib
...
```
---
## 🔄 마이그레이션 가이드
### 기존 `implementations.py`에서 분리된 코드 사용하기
#### Before (기존):
```python
from strategies.implementations import BoldAssetAllocation
```
#### After (현재):
```python
# 방법 1: 기존과 동일하게 사용 (권장)
from strategies.implementations import BoldAssetAllocation
# 방법 2: 직접 모듈에서 임포트
from strategies.impls.asset_allocation import BoldAssetAllocation
```
**👍 호환성**: 기존 코드 수정 불필요!
---
## 🧪 테스트
### 개별 모듈 테스트
```python
# test_trend_following.py
from strategies.impls.trend_following import MovingAverageCrossover
def test_moving_average():
strategy = MovingAverageCrossover()
result = strategy.execute()
assert result["strategy"] == "MovingAverageCrossover"
```
### 통합 테스트
```python
# test_all_strategies.py
from strategies.implementations import (
MovingAverageCrossover,
RSIMeanReversion,
BollingerBandBreakout,
BoldAssetAllocation
)
strategies = [
MovingAverageCrossover(),
RSIMeanReversion(),
BollingerBandBreakout(),
BoldAssetAllocation()
]
for strategy in strategies:
result = strategy.execute()
assert "strategy" in result
```
---
## 🎯 장점
### 1. 코드 구조화
- 관련 전략끼리 그룹화
- 파일 크기 감소 (가독성 향상)
- 명확한 책임 분리
### 2. 유지보수성
- 특정 카테고리만 수정 가능
- 머지 충돌 감소
- 버그 추적 용이
### 3. 확장성
- 새 카테고리 쉽게 추가
- 독립적인 개발 가능
- 팀 협업 용이
### 4. 성능
- 필요한 모듈만 로드
- 메모리 사용 최적화
- 빠른 개발 서버 재시작
---
## 📚 참고
- **기본 클래스**: `strategies/base.py`
- **레지스트리**: `strategies/base.py - StrategyRegistry`
- **API 가이드**: `API_USAGE_GUIDE.md`
- **BAA 전략**: `BAA_STRATEGY_README.md`
---
## ❓ FAQ
### Q: 기존 코드가 작동하지 않나요?
**A:** 아니요! `implementations.py`가 자동으로 모든 모듈을 임포트하므로 기존 코드는 그대로 작동합니다.
### Q: 새 카테고리를 추가하려면?
**A:**
1. `strategies/impls/new_category.py` 생성
2. `strategies/impls/__init__.py`에 임포트 추가
3. `strategies/implementations.py`에 임포트 추가
### Q: 전략을 다른 카테고리로 옮기려면?
**A:**
1. 전략 클래스를 새 파일로 복사
2.`__init__.py` 파일의 임포트 경로 수정
3. 기존 파일에서 전략 삭제
### Q: 한 전략이 여러 카테고리에 속한다면?
**A:** 가장 주요한 특성에 맞는 카테고리에 배치하세요. 또는 `hybrid.py` 같은 새 카테고리를 만드세요.