|
1 | 1 | from concurrent.futures import ThreadPoolExecutor, as_completed |
2 | | -from sqlalchemy.orm import Session |
| 2 | +from sqlalchemy.orm import Session, aliased |
| 3 | +from sqlalchemy import func |
3 | 4 | from app.db.session import SessionLocal |
4 | 5 | from app.models.stock import Stock |
| 6 | +from app.models.stock_detail import StockDetail |
| 7 | +from app.models.prediction import Prediction |
5 | 8 | import time |
| 9 | +import datetime |
6 | 10 | from app.crud.prediction import create_prediction_objects, save_predictions |
7 | 11 | from app.services.prediction_service import PredictionService |
8 | 12 | import logging |
@@ -122,3 +126,126 @@ def batch_predict_and_save(start_id: int, end_id: int, max_workers: int = 2): |
122 | 126 | logger.exception(f"[{stock_id}] 처리 중 예외 발생: {str(e)}") |
123 | 127 |
|
124 | 128 | logger.info("전체 배치 완료") |
| 129 | + |
| 130 | + @staticmethod |
| 131 | + def update_ai_avg_increase_and_rank(base_date: datetime.date | None = None): |
| 132 | + """ |
| 133 | + 종목별 예측값 기반 실제 존재하는 예측일 기준 15일 평균 상승률 계산 후 stock_detail 업데이트 |
| 134 | + :param base_date: 기준일 (None이면 오늘 날짜 사용) |
| 135 | + :return: None |
| 136 | + """ |
| 137 | + db = SessionLocal() |
| 138 | + try: |
| 139 | + today = base_date or datetime.date.today() |
| 140 | + logger.info(f"[BatchService] 평균 상승률 계산 시작 (기준일: {today})") |
| 141 | + |
| 142 | + # --- 예측 데이터 존재 여부 확인 --- |
| 143 | + total_preds = db.query(Prediction).count() |
| 144 | + future_preds = db.query(Prediction).filter(Prediction.target_date > today).count() |
| 145 | + logger.info(f"[BatchService] Prediction 전체: {total_preds}건 / 기준일 이후: {future_preds}건") |
| 146 | + |
| 147 | + if future_preds == 0: |
| 148 | + logger.warning(f"[BatchService] 기준일({today}) 이후 예측 데이터가 없습니다.") |
| 149 | + return |
| 150 | + |
| 151 | + # --- 첫 번째 예측일 구하기 --- |
| 152 | + first_date_subq = ( |
| 153 | + db.query( |
| 154 | + Prediction.stock_id, |
| 155 | + func.min(Prediction.target_date).label("first_target_date") |
| 156 | + ) |
| 157 | + .filter(Prediction.target_date > today) |
| 158 | + .group_by(Prediction.stock_id) |
| 159 | + .subquery() |
| 160 | + ) |
| 161 | + logger.debug(f"[BatchService] first_date_subq 생성 완료") |
| 162 | + |
| 163 | + # --- 첫 예측일의 예측 종가 구하기 --- |
| 164 | + subquery_first_price = ( |
| 165 | + db.query( |
| 166 | + Prediction.stock_id, |
| 167 | + Prediction.predicted_close.label("first_predicted_close") |
| 168 | + ) |
| 169 | + .join( |
| 170 | + first_date_subq, |
| 171 | + (Prediction.stock_id == first_date_subq.c.stock_id) |
| 172 | + & (Prediction.target_date == first_date_subq.c.first_target_date) |
| 173 | + ) |
| 174 | + .subquery() |
| 175 | + ) |
| 176 | + first_price_count = db.query(subquery_first_price).count() |
| 177 | + logger.info(f"[BatchService] 첫 예측일 종가 매핑 완료 ({first_price_count}건)") |
| 178 | + |
| 179 | + # --- 평균 상승률 계산 --- |
| 180 | + results = ( |
| 181 | + db.query( |
| 182 | + Prediction.stock_id, |
| 183 | + func.avg( |
| 184 | + (Prediction.predicted_close - subquery_first_price.c.first_predicted_close) |
| 185 | + / func.nullif(subquery_first_price.c.first_predicted_close, 0.0) |
| 186 | + ).label("avg_increase") |
| 187 | + ) |
| 188 | + .join(subquery_first_price, Prediction.stock_id == subquery_first_price.c.stock_id) |
| 189 | + .filter(Prediction.target_date > today) |
| 190 | + .group_by(Prediction.stock_id) |
| 191 | + .all() |
| 192 | + ) |
| 193 | + |
| 194 | + logger.info(f"[BatchService] 평균 상승률 계산 결과: {len(results)}건") |
| 195 | + |
| 196 | + if not results: |
| 197 | + logger.warning("[BatchService] 평균 상승률 계산 결과 없음 (JOIN 또는 데이터 매칭 문제 가능)") |
| 198 | + return |
| 199 | + |
| 200 | + # --- 상위 3개 샘플 출력 --- |
| 201 | + sample_logs = [ |
| 202 | + f"stock_id={r.stock_id}, avg_increase={round((r.avg_increase or 0) * 100, 2)}%" |
| 203 | + for r in results[:3] |
| 204 | + ] |
| 205 | + logger.debug(f"[BatchService] 계산 결과 샘플: {sample_logs}") |
| 206 | + |
| 207 | + # --- 평균 상승률 내림차순 정렬 및 랭킹 부여 --- |
| 208 | + sorted_results = sorted(results, key=lambda r: r.avg_increase or 0, reverse=True) |
| 209 | + |
| 210 | + for rank, row in enumerate(sorted_results, start=1): |
| 211 | + db.query(StockDetail).filter(StockDetail.stock_id == row.stock_id).update( |
| 212 | + { |
| 213 | + StockDetail.ai_avg_increase: row.avg_increase, |
| 214 | + StockDetail.ai_rank: rank, |
| 215 | + StockDetail.updated_at: datetime.datetime.utcnow(), |
| 216 | + } |
| 217 | + ) |
| 218 | + if rank <= 3: # 상위 3개만 출력 |
| 219 | + logger.debug( |
| 220 | + f"[BatchService] UPDATE → stock_id={row.stock_id}, " |
| 221 | + f"avg_increase={row.avg_increase}, rank={rank}" |
| 222 | + ) |
| 223 | + |
| 224 | + db.commit() |
| 225 | + logger.info(f"[BatchService] 평균 상승률 및 랭킹 갱신 완료 ({len(sorted_results)}개 종목)") |
| 226 | + |
| 227 | + # 상위 3개 종목 조회 |
| 228 | + top3 = ( |
| 229 | + db.query(Stock.name, StockDetail.ai_avg_increase) |
| 230 | + .join(StockDetail, Stock.id == StockDetail.stock_id) |
| 231 | + .order_by(StockDetail.ai_rank.asc()) |
| 232 | + .limit(3) |
| 233 | + .all() |
| 234 | + ) |
| 235 | + |
| 236 | + # 디스코드 알림용 리스트 반환 |
| 237 | + top3_info = [ |
| 238 | + {"name": name, "increase": round((increase or 0) * 100, 2)} |
| 239 | + for name, increase in top3 |
| 240 | + ] |
| 241 | + |
| 242 | + return top3_info |
| 243 | + |
| 244 | + except Exception as e: |
| 245 | + db.rollback() |
| 246 | + logger.exception(f"[BatchService] 평균 상승률 계산 중 오류 발생: {e}") |
| 247 | + raise |
| 248 | + |
| 249 | + finally: |
| 250 | + db.close() |
| 251 | + logger.debug("[BatchService] 세션 종료 완료") |
0 commit comments