diff --git a/.env.example b/.env.example index 2bb1ead..119b721 100644 --- a/.env.example +++ b/.env.example @@ -179,8 +179,8 @@ SHORT_TERM_VOLUME_MULTIPLIER=1.5 # 거래량 필터 배수 (1.5배) # ═══════════════════════════════════════════════════════════════════════════════ # 감시 목록 관리 (watchlist.py) # ═══════════════════════════════════════════════════════════════════════════════ -WATCHLIST_INIT_SIZE=50 # 아침 배치 초기화 종목 수 -WATCHLIST_MAX_SIZE=100 # 최대 관리 종목 수 +WATCHLIST_INIT_SIZE=150 # 아침 배치 초기화 종목 수 +WATCHLIST_MAX_SIZE=150 # 최대 관리 종목 수 WATCHLIST_ENTRY_SCORE=60 # 장중 신규 진입 기준 점수 WATCHLIST_EXIT_SCORE=20 # 장중 제거 기준 점수 diff --git a/README.md b/README.md index e946ad6..5c1579d 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,11 @@ auto-stock/ # 환경 변수 설정 cp .env.example .env +# 기본값 +# - `DATABASE_URL`은 `.env.example`에 이미 도커 컨테이너(127.0.0.1:5432)를 +# 가리키도록 설정되어 있습니다. 로컬 개발 시 별도 수정이 필요 없습니다. +# 원격 DB를 사용하려면 여기에 URL을 덮어쓰십시오. + # Docker로 전체 시스템 시작 ./scripts/deploy.sh @@ -51,7 +56,7 @@ cp .env.example .env - `KOREA_INVESTMENT_APP_KEY`: 한국투자증권 앱키 - `KOREA_INVESTMENT_APP_SECRET`: 한국투자증권 시크릿 - `ANTHROPIC_API_KEY`: Claude API 키 -- `DATABASE_URL`: PostgreSQL 연결 URL +- `DATABASE_URL`: PostgreSQL 연결 URL (기본값은 도커 컨테이너) - `REDIS_URL`: Redis 연결 URL ## 라이센스 diff --git a/backend/app/api/endpoints/recommendations.py b/backend/app/api/endpoints/recommendations.py index 57c7f85..4ac998a 100644 --- a/backend/app/api/endpoints/recommendations.py +++ b/backend/app/api/endpoints/recommendations.py @@ -13,7 +13,8 @@ from sqlalchemy import select from app.core.config import settings from app.services.market_analyzer import ( - check_market_regime, get_all_tradable_stocks, analyze_stock, + check_market_regime, get_all_tradable_stocks, analyze_stock, + analyze_stock_for_batch, RecommendationCriteria, StockRecommendation, KST ) from app.services.trade_executor import execute_auto_trade_background, execute_auto_trade diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 07a7fda..fb70872 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -73,6 +73,23 @@ class Settings(BaseSettings): def __init__(self, **kwargs): super().__init__(**kwargs) self._apply_kis_mode() + self._apply_docker_db_override() + + def _apply_docker_db_override(self): + """If running inside Docker, convert localhost in DATABASE_URL to the + postgres service hostname. + + Users often copy `.env.example` which defaults to + `postgresql://...@localhost:5432/...`. That works on the host machine, + but inside the backend container `localhost` refers to the container + itself, not the Postgres server. When `/.dockerenv` exists we assume the + code is running in Docker and automatically patch the URL. + """ + if os.path.exists("/.dockerenv"): + # simple string replacement; pydantic does not throw if format + # changes after initialization + if "localhost" in self.DATABASE_URL: + self.DATABASE_URL = self.DATABASE_URL.replace("localhost", "postgres") def _apply_kis_mode(self): """KIS_MODE에 따라 모의/실전 API 설정을 자동 선택""" @@ -254,8 +271,8 @@ class Settings(BaseSettings): # ═════════════════════════════════════════════════════════════════════════════ # 감시 목록 (watchlist.py) # ═════════════════════════════════════════════════════════════════════════════ - WATCHLIST_INIT_SIZE: int = 50 # 아침 배치 초기화 종목 수 - WATCHLIST_MAX_SIZE: int = 100 # 최대 관리 종목 수 + WATCHLIST_INIT_SIZE: int = 150 # 아침 배치 초기화 종목 수 + WATCHLIST_MAX_SIZE: int = 150 # 최대 관리 종목 수 WATCHLIST_ENTRY_SCORE: int = 60 # 장중 신규 진입 기준 점수 WATCHLIST_EXIT_SCORE: int = 20 # 장중 제거 기준 점수 diff --git a/backend/app/services/watchlist.py b/backend/app/services/watchlist.py index 28c8b29..b5e454a 100644 --- a/backend/app/services/watchlist.py +++ b/backend/app/services/watchlist.py @@ -24,7 +24,7 @@ from app.models.models import WatchlistStock, StockAnalysis logger = logging.getLogger(__name__) # 스캐너 신호 종목에 배정하는 최대 슬롯 수 (settings.WATCHLIST_INIT_SIZE 중 이 수만큼 우선) -SCANNER_PRIORITY_SLOTS: int = 20 +SCANNER_PRIORITY_SLOTS: int = 50 async def initialize_watchlist( diff --git a/init_db.py b/init_db.py index dad31b0..c2032f1 100644 --- a/init_db.py +++ b/init_db.py @@ -10,13 +10,20 @@ async def init_database(): with open('docker/init-db.sql', 'r') as f: sql = f.read() - # Connect to database + # Connect to database using settings or environment variable + # (fall back to defaults in .env.example which point at the local docker container) + from app.core.config import Settings + settings = Settings() + # parse DATABASE_URL to asyncpg components + from sqlalchemy.engine.url import make_url + url = make_url(settings.DATABASE_URL) + conn = await asyncpg.connect( - host='shium.net', - port=55432, - user='stock', - password='Tjduddn!!12', - database='stock' + host=url.host or 'localhost', + port=url.port or 5432, + user=url.username or 'autostock', + password=url.password or 'autostock_password', + database=url.database or 'autostock_db' ) try: