Files
auto-stock/backend/fix_trade_history.py
2026-02-22 17:23:20 +09:00

63 lines
2.4 KiB
Python

import asyncio
from app.core.database import AsyncSessionLocal
from app.models.models import TradeHistory, Portfolio
from sqlalchemy import select, and_
async def fix_trade_history():
"""잘못된 거래 내역 수정"""
async with AsyncSessionLocal() as db:
# 현대ADM 포트폴리오 확인
result = await db.execute(
select(Portfolio).where(Portfolio.stock_code == "187660")
)
portfolio = result.scalar_one_or_none()
if portfolio:
actual_qty = portfolio.quantity
print(f"✅ 실제 보유 수량: {actual_qty}주")
else:
print("❌ 포트폴리오에 현대ADM 없음")
return
# 현대ADM 거래 내역 조회
result = await db.execute(
select(TradeHistory)
.where(
and_(
TradeHistory.stock_code == "187660",
TradeHistory.order_type == "BUY",
TradeHistory.status.in_(["COMPLETED", "EXECUTED"])
)
)
.order_by(TradeHistory.created_at)
)
trades = result.scalars().all()
print(f"\n📋 DB 거래 내역: {len(trades)}건")
total_db_qty = sum(t.executed_quantity or t.order_quantity for t in trades)
print(f"📊 DB 총 매수량: {total_db_qty}주")
print(f"📊 실제 보유량: {actual_qty}주")
print(f"⚠️ 차이: {total_db_qty - actual_qty}주")
# 가장 최근 거래만 남기고 나머지 삭제
if len(trades) > 1:
print(f"\n🗑️ 중복 거래 내역 삭제:")
for trade in trades[:-1]: # 마지막 거래 제외하고 삭제
print(f" - ID {trade.id}: {trade.order_quantity}주 (생성: {trade.created_at})")
await db.delete(trade)
# 마지막 거래의 수량을 실제 보유량으로 수정
last_trade = trades[-1]
print(f"\n✏️ 마지막 거래 수량 수정:")
print(f" - ID {last_trade.id}: {last_trade.order_quantity}주 → {actual_qty}주")
last_trade.executed_quantity = actual_qty
last_trade.order_quantity = actual_qty
await db.commit()
print(f"\n✅ 수정 완료!")
else:
print("\n✅ 중복 없음")
if __name__ == "__main__":
asyncio.run(fix_trade_history())