보유종목 1분마다 호출하는부분 수정

This commit is contained in:
2026-02-27 12:19:48 +09:00
parent a47591e40d
commit 6f23b06816
10 changed files with 729 additions and 353 deletions

86
backend/alembic/env.py Normal file
View File

@@ -0,0 +1,86 @@
"""Alembic 환경 설정 (async / asyncpg)
- settings.DATABASE_URL 에서 연결 문자열을 읽어 동기 드라이버(psycopg2) URL 로 변환
- 모델 메타데이터를 임포트해 autogenerate 지원
"""
import asyncio
from logging.config import fileConfig
from sqlalchemy import pool
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import async_engine_from_config
from alembic import context
# ── 프로젝트 루트를 sys.path 에 추가 (alembic.ini prepend_sys_path = .) ───────
import sys
import os
# backend/ 가 작업 디렉토리이므로 app 패키지를 바로 임포트 가능
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from app.core.config import settings
from app.core.database import Base
# 모든 모델 임포트 — autogenerate 가 테이블을 인식하도록
import app.models.models # noqa: F401
# ── alembic.ini 로거 설정 ─────────────────────────────────────────────────────
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# ── DB URL: asyncpg → psycopg2 (Alembic 동기 드라이버용) ────────────────────
_db_url = settings.DATABASE_URL
if "+asyncpg" in _db_url:
_db_url = _db_url.replace("+asyncpg", "")
elif _db_url.startswith("postgresql://"):
pass # already sync-compatible
config.set_main_option("sqlalchemy.url", _db_url)
target_metadata = Base.metadata
# ── 오프라인 마이그레이션 ─────────────────────────────────────────────────────
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
# ── 온라인 마이그레이션 (async) ───────────────────────────────────────────────
def do_run_migrations(connection: Connection) -> None:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
async def run_async_migrations() -> None:
_async_url = settings.DATABASE_URL
if not "+asyncpg" in _async_url:
_async_url = _async_url.replace("postgresql://", "postgresql+asyncpg://")
connectable = async_engine_from_config(
{"sqlalchemy.url": _async_url},
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)
await connectable.dispose()
def run_migrations_online() -> None:
asyncio.run(run_async_migrations())
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

View File

@@ -0,0 +1,26 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@@ -0,0 +1,122 @@
"""initial schema columns
lifespan 에서 관리하던 ADD COLUMN / CREATE TABLE DDL 을 Alembic 으로 이전.
이 revision 이 적용된 후에는 main.py lifespan 의 raw SQL DDL 블록은 제거됨.
Revision ID: 0001
Revises:
Create Date: 2026-02-27
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
revision: str = "0001"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ── trade_history 컬럼 추가 ─────────────────────────────────────────────
with op.batch_alter_table("trade_history", schema=None) as batch_op:
for col_name, col_type in [
("total_amount", sa.Numeric(15, 2)),
("entry_reason", sa.Text()),
("exit_reason", sa.Text()),
("signals", postgresql.JSONB()),
("entry_trade_id", sa.Integer()),
("slippage", sa.Numeric(10, 2)),
("commission", sa.Numeric(10, 2)),
("net_profit_loss", sa.Numeric(15, 2)),
("profit_loss_rate", sa.Numeric(10, 4)),
]:
try:
batch_op.add_column(sa.Column(col_name, col_type, nullable=True))
except Exception:
pass # 이미 존재하는 컬럼은 무시
# total_amount 백필
op.execute("""
UPDATE trade_history
SET total_amount = executed_price * executed_quantity
WHERE total_amount IS NULL
AND executed_price IS NOT NULL
AND executed_quantity IS NOT NULL
""")
# ── stock_analysis 컬럼 추가 ────────────────────────────────────────────
with op.batch_alter_table("stock_analysis", schema=None) as batch_op:
for col_name, col_type in [
("atr_14", sa.Numeric(15, 2)),
("adx_14", sa.Numeric(10, 2)),
("ml_score", sa.Integer()),
("ml_confidence", sa.Numeric(5, 4)),
("ml_signal", sa.String(10)),
]:
try:
batch_op.add_column(sa.Column(col_name, col_type, nullable=True))
except Exception:
pass
# stock_analysis 유니크 제약 추가 (idempotent)
op.execute("""
DO $$ BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint
WHERE conname = 'uq_stock_analysis_code_date'
AND conrelid = 'stock_analysis'::regclass
) THEN
ALTER TABLE stock_analysis
ADD CONSTRAINT uq_stock_analysis_code_date
UNIQUE (stock_code, analysis_date);
END IF;
END $$;
""")
# ── active_trades 컬럼 추가 ─────────────────────────────────────────────
with op.batch_alter_table("active_trades", schema=None) as batch_op:
for col_name, col_type, default in [
("remaining_pct", sa.Numeric(5, 2), "1.0"),
("highest_since_entry", sa.Numeric(15, 2), None),
("strategy_name", sa.String(100), None),
]:
try:
col = sa.Column(col_name, col_type, nullable=True,
server_default=default if default else sa.null())
batch_op.add_column(col)
except Exception:
pass
# ── trading_sessions 테이블 ─────────────────────────────────────────────
op.execute("""
CREATE TABLE IF NOT EXISTS trading_sessions (
id SERIAL PRIMARY KEY,
session_date DATE UNIQUE NOT NULL,
consecutive_losses INTEGER DEFAULT 0,
daily_profit_loss NUMERIC(15, 2) DEFAULT 0,
is_paused BOOLEAN DEFAULT FALSE,
pause_reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# ── stock_bans 테이블 ───────────────────────────────────────────────────
op.execute("""
CREATE TABLE IF NOT EXISTS stock_bans (
stock_code VARCHAR(20) PRIMARY KEY,
consecutive_losses INTEGER DEFAULT 0 NOT NULL,
ban_until TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
def downgrade() -> None:
# downgrade 는 데이터 손실 위험이 있으므로 명시적으로 구현하지 않음
# 필요 시 ALTER TABLE DROP COLUMN 을 수동으로 실행
pass