diff --git "a/src/app.py" "b/src/app.py" new file mode 100644--- /dev/null +++ "b/src/app.py" @@ -0,0 +1,4782 @@ +import streamlit as st +import streamlit.components.v1 as components +import yfinance as yf +import google.generativeai as genai +import pandas as pd +import plotly.express as px +import plotly.graph_objects as go +import os +import json +import re +import ast +import random +import time +import hashlib +import concurrent.futures +import threading +from datetime import datetime, timedelta +from huggingface_hub import HfApi, hf_hub_download +import shutil +from streamlit.runtime.scriptrunner import add_script_run_ctx, get_script_run_ctx + +today_str = datetime.now().strftime("%Y-%m-%d") + +st.set_page_config(page_title="Invest Pro Alpha", layout="wide", initial_sidebar_state="collapsed") + +NAV_CSS = """ +/* ── 하단 네비게이션 바 ── */ +div.element-container:has(.nav-marker) + div { + position: fixed !important; bottom: 0 !important; left: 0 !important; + width: 100vw !important; + background: rgba(12,12,12,0.97) !important; + backdrop-filter: blur(20px) !important; + -webkit-backdrop-filter: blur(20px) !important; + z-index: 999999 !important; + border-top: 1px solid rgba(255,255,255,0.07) !important; + padding-bottom: env(safe-area-inset-bottom) !important; +} +div.element-container:has(.nav-marker) + div [data-testid="stColumns"], +div.element-container:has(.nav-marker) + div [data-testid="stHorizontalBlock"] { + display: grid !important; grid-template-columns: 1fr 1fr 1fr !important; + width: 100% !important; gap: 0 !important; +} +div.element-container:has(.nav-marker) + div [data-testid="column"], +div.element-container:has(.nav-marker) + div [data-testid="stColumn"] { + width: 100% !important; min-width: 100% !important; padding: 0 !important; margin: 0 !important; +} +div.element-container:has(.nav-marker) + div button { + background: transparent !important; border: none !important; box-shadow: none !important; + color: #444444 !important; width: 100% !important; height: 58px !important; + padding: 0 !important; display: block !important; transition: color 0.2s; +} +div.element-container:has(.nav-marker) + div button p { + white-space: pre-wrap !important; text-align: center !important; + font-size: 10px !important; font-weight: 700 !important; line-height: 1.2 !important; + margin: 0 !important; color: #444444 !important; letter-spacing: 0.5px !important; +} +div.element-container:has(.nav-marker) + div button em { + font-style: normal !important; font-size: 20px !important; display: block !important; + margin-bottom: 3px !important; color: #444444 !important; +} +div.element-container:has(.nav-marker) + div button:hover p, +div.element-container:has(.nav-marker) + div button:active p { color: #D8D8D8 !important; } +div.element-container:has(.nav-marker) + div button:hover em, +div.element-container:has(.nav-marker) + div button:active em { color: #D8D8D8 !important; } +/* ── 메뉴 드로어 ── */ +div.element-container:has(.menu-drawer-marker) + div { + position: fixed !important; bottom: 58px !important; left: 0 !important; + width: 100vw !important; z-index: 999998 !important; + background: rgba(14,14,14,0.98) !important; + backdrop-filter: blur(24px) !important; + border-top: 1px solid rgba(255,255,255,0.08) !important; + padding: 12px 0 8px !important; +} +div.element-container:has(.menu-drawer-marker) + div [data-testid="stColumns"], +div.element-container:has(.menu-drawer-marker) + div [data-testid="stHorizontalBlock"] { + display: flex !important; flex-direction: column !important; + width: 100% !important; gap: 0 !important; padding: 0 !important; +} +div.element-container:has(.menu-drawer-marker) + div [data-testid="column"], +div.element-container:has(.menu-drawer-marker) + div [data-testid="stColumn"] { + width: 100% !important; min-width: 100% !important; padding: 0 !important; +} +div.element-container:has(.menu-drawer-marker) + div button { + background: transparent !important; border: none !important; box-shadow: none !important; + color: #888 !important; width: 100% !important; height: 48px !important; + padding: 0 24px !important; text-align: left !important; transition: all 0.15s; + border-bottom: 1px solid rgba(255,255,255,0.04) !important; +} +div.element-container:has(.menu-drawer-marker) + div button p { + font-size: 14px !important; font-weight: 600 !important; color: #888 !important; + text-align: left !important; margin: 0 !important; +} +div.element-container:has(.menu-drawer-marker) + div button:hover { background: rgba(255,255,255,0.04) !important; } +div.element-container:has(.menu-drawer-marker) + div button:hover p { color: #EBEBEB !important; } +""" + +CARD_CSS = """ +div.element-container:has(.scan-marker) + div.element-container button { + background: #161616 !important; + border: 1px solid rgba(255,255,255,0.07) !important; + border-radius: 10px !important; + padding: 18px 10px !important; display: flex !important; flex-direction: column !important; + align-items: center !important; justify-content: center !important; width: 100% !important; + box-shadow: none !important; + transition: all 0.2s ease !important; + height: auto !important; min-height: 115px !important; margin-bottom: 10px !important; +} +div.element-container:has(.scan-marker) + div.element-container button:hover { + border-color: rgba(255,255,255,0.22) !important; + background: #202020 !important; + transform: translateY(-2px) !important; + box-shadow: 0 8px 20px rgba(0,0,0,0.3) !important; +} +div.element-container:has(.scan-marker) + div.element-container button p { + white-space: pre-wrap !important; text-align: center !important; + margin: 0 !important; width: 100% !important; line-height: 1.6 !important; +} +div.element-container:has(.scan-marker) + div.element-container button em { + font-style: normal !important; font-size: 10px !important; color: #D8D8D8 !important; + background: rgba(255,255,255,0.08) !important; padding: 2px 8px !important; + border-radius: 4px !important; font-weight: 800 !important; display: inline-block !important; + margin-bottom: 8px !important; letter-spacing: 0.5px !important; + border: 1px solid rgba(201,168,76,0.2) !important; +} +div.element-container:has(.scan-marker) + div.element-container button strong { + font-size: 14px !important; font-weight: 700 !important; color: #EBEBEB !important; + display: block !important; margin-bottom: 5px !important; +} +div.element-container:has(.scan-marker) + div.element-container button del { + text-decoration: none !important; font-size: 13px !important; font-weight: 500 !important; + color: #888888 !important; display: block !important; font-family: 'IBM Plex Mono', monospace !important; +} +div.element-container:has(.port-marker) + div.element-container button { + background: linear-gradient(135deg, #161616 0%, #131313 100%) !important; + border: 1px solid rgba(255,255,255,0.14) !important; + border-radius: 16px !important; + padding: 26px 20px !important; text-align: center !important; + box-shadow: none !important; height: auto !important; + margin-bottom: 16px !important; width: 100% !important; + position: relative !important; overflow: hidden !important; + transition: border-color 0.2s !important; +} +div.element-container:has(.port-marker) + div.element-container button:hover { + border-color: rgba(201,168,76,0.5) !important; +} +div.element-container:has(.port-marker) + div.element-container button p { + white-space: pre-wrap !important; font-size: 11px !important; font-weight: 700 !important; + color: #444444 !important; line-height: 1.8 !important; letter-spacing: 1px !important; + text-transform: uppercase !important; +} +div.element-container:has(.port-marker) + div.element-container button del { + text-decoration: none !important; font-size: 28px !important; font-weight: 500 !important; + color: #EBEBEB !important; display: block !important; margin: 6px 0 !important; + font-family: 'IBM Plex Mono', monospace !important; letter-spacing: -1px !important; +} +div.element-container:has(.port-marker) + div.element-container button strong { + color: #E0E0E0 !important; font-size: 14px !important; + font-family: 'IBM Plex Mono', monospace !important; font-weight: 700 !important; +} +""" + +COMPONENT_CSS = """ +.menu-overlay-btn > button { + background: #161616 !important; + border: 1px solid rgba(255,255,255,0.07) !important; + border-radius: 12px !important; + padding: 18px 20px !important; font-size: 16px !important; font-weight: 700 !important; + color: #EBEBEB !important; box-shadow: none !important; margin-bottom: 10px !important; + transition: all 0.15s !important; +} +.menu-overlay-btn > button:hover { + border-color: rgba(255,255,255,0.20) !important; + background: #202020 !important; +} +.menu-overlay-btn > button p { + font-size: 16px !important; font-weight: 400 !important; margin: 0 !important; color: #EBEBEB !important; +} +div.stButton > button:not([title]) { + border-radius: 8px; font-weight: 600; padding: 10px 20px; transition: all 0.2s ease; + border: 1px solid rgba(255,255,255,0.08); width: 100%; word-break: keep-all; + color: #888888; background: linear-gradient(135deg, #161616 0%, #111111 100%); font-size: 13px; + box-shadow: 0 1px 4px rgba(0,0,0,0.3); +} +div.stButton > button:not([title]):hover { + border-color: rgba(255,255,255,0.22); + color: #D8D8D8; + background: linear-gradient(135deg, #202020 0%, #161616 100%); + box-shadow: 0 2px 12px rgba(255,255,255,0.05); + transform: translateY(-1px); +} +/* 카드 아이콘 버튼 (✎ ↑ ✕) - 투명하게, 카드에 동화 */ +div.stButton button[title="편집"], +div.stButton button[title="매도 일지"], +div.stButton button[title="삭제"] { + background: transparent !important; + border: none !important; + color: #444444 !important; + padding: 0 !important; + box-shadow: none !important; + transform: none !important; + min-height: 36px !important; + font-size: 14px !important; + width: 100% !important; +} +div.stButton button[title="편집"]:hover, +div.stButton button[title="매도 일지"]:hover, +div.stButton button[title="삭제"]:hover { + background: transparent !important; + border: none !important; + color: #AAAAAA !important; + transform: none !important; + box-shadow: none !important; +} +/* 모바일에서 columns 세로 쌓임 방지 */ +[data-testid="stHorizontalBlock"]:has(button[title="편집"]) { + flex-wrap: nowrap !important; + gap: 4px !important; +} +[data-testid="stHorizontalBlock"]:has(button[title="편집"]) > [data-testid="stColumn"] { + min-width: 0 !important; + flex-shrink: 1 !important; +} +/* 카드 종목명 클릭 버튼 */ +div.stButton button[title="카드이동"] { + background: #161616 !important; + border: none !important; + box-shadow: none !important; + padding: 4px 2px !important; + text-align: left !important; + transform: none !important; + width: 100% !important; + min-height: unset !important; +} +div.stButton button[title="카드이동"] p { + color: #EBEBEB !important; + font-size: 15px !important; + font-weight: 800 !important; + text-align: left !important; + line-height: 1.4 !important; + margin: 0 !important; +} +div.stButton button[title="카드이동"]:hover { background: #1A1A1A !important; } +div.stButton button[title="카드이동"]:hover p { color: #FFFFFF !important; } +/* 카드 본문 클릭 버튼 */ +div.stButton button[title="카드본문"] { + background: #161616 !important; + border: none !important; + box-shadow: none !important; + padding: 0 2px !important; + text-align: left !important; + transform: none !important; + width: 100% !important; + min-height: unset !important; + height: auto !important; +} +div.stButton button[title="카드본문"] p { + color: #888888 !important; + font-size: 13px !important; + font-weight: 400 !important; + text-align: left !important; + line-height: 1.7 !important; + margin: 0 !important; + white-space: pre-wrap !important; +} +div.stButton button[title="카드본문"]:hover { background: #181818 !important; } +div.stButton button[title="카드본문"]:hover p { color: #AAAAAA !important; } +button[kind="primary"]:not([title]) { + background: linear-gradient(135deg, rgba(255,255,255,0.11) 0%, rgba(255,255,255,0.07) 100%) !important; + border-color: rgba(255,255,255,0.20) !important; + color: #D8D8D8 !important; + box-shadow: 0 1px 8px rgba(201,168,76,0.1) !important; +} +button[kind="primary"]:not([title]):hover { + background: linear-gradient(135deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0.11) 100%) !important; + box-shadow: 0 2px 16px rgba(255,255,255,0.09) !important; +} +@keyframes skeleton-pulse { + 0% { background-color: #161616; } + 50% { background-color: #202020; } + 100% { background-color: #161616; } +} +.skeleton-box { border-radius: 10px; animation: skeleton-pulse 1.5s ease-in-out infinite; } +.stock-header-card { + background: linear-gradient(160deg, #1C1C1C 0%, #111111 60%, #0C0C0C 100%); + border: 1px solid rgba(255,255,255,0.11); + border-radius: 16px; padding: 20px; + margin-bottom: 14px; position: relative; overflow: hidden; + box-shadow: 0 4px 32px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.08); +} +.stock-header-card::before { + content: ''; + position: absolute; top: 0; left: 0; right: 0; height: 1px; + background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), rgba(255,255,255,0.55), rgba(255,255,255,0.3), transparent); +} +.stock-title { + font-size: 10px; color: #444444; font-weight: 700; + text-transform: uppercase; letter-spacing: 2px; margin-bottom: 10px; + display: flex; align-items: center; justify-content: space-between; +} +.stock-name-row { display: flex; align-items: baseline; gap: 10px; margin-bottom: 12px; flex-wrap: wrap; } +.stock-name { font-size: 24px; font-weight: 900; color: #EBEBEB; } +.stock-ticker { + font-size: 13px; color: #D8D8D8; + background: rgba(201,168,76,0.1); padding: 2px 8px; + border-radius: 4px; border: 1px solid rgba(201,168,76,0.2); +} +.price-star-row { + display: flex; align-items: center; justify-content: space-between; + border-top: 1px solid rgba(255,255,255,0.05); padding-top: 12px; +} +.stock-price { + font-size: 30px; font-weight: 500; color: #D8D8D8; + letter-spacing: -1px; font-family: 'IBM Plex Mono', monospace; +} +.star-rating { + color: #D8D8D8; font-size: 16px; letter-spacing: 2px; + background: rgba(201,168,76,0.1); padding: 4px 12px; + border-radius: 6px; border: 1px solid rgba(201,168,76,0.2); +} +.header-badges-row { + display: flex; flex-wrap: wrap; gap: 6px; + margin-top: 12px; padding-top: 10px; + border-top: 1px solid rgba(255,255,255,0.04); +} +.conclusion-box { + background: linear-gradient(135deg, #1C1C1C 0%, #111111 100%); + color: #888888; + border-radius: 10px; padding: 16px; + margin-bottom: 16px; + border: 1px solid rgba(255,255,255,0.09); + border-left: 3px solid #D8D8D8; + font-size: 14px; line-height: 1.8; + box-shadow: 0 2px 16px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.05); +} +.conclusion-box strong { color: #EBEBEB; } +.report-section { + margin-bottom: 16px; + padding-bottom: 16px; + border-bottom: 1px solid rgba(255,255,255,0.04); +} +.report-section:last-child { border-bottom: none; } +.analysis-header { + background: linear-gradient(90deg, rgba(255,255,255,0.08), rgba(255,255,255,0.04)); + color: #D8D8D8; padding: 7px 14px; border-radius: 6px; + font-weight: 700; font-size: 11px; width: fit-content; margin-bottom: 12px; + border: 1px solid rgba(201,168,76,0.2); + border-left: 2px solid rgba(201,168,76,0.7); + letter-spacing: 1px; text-transform: uppercase; + box-shadow: 0 1px 8px rgba(255,255,255,0.04); +} +.analysis-content { line-height: 1.9; font-size: 14px; color: #888888; } +.analysis-content strong { color: #EBEBEB; font-weight: 700; } +.strategy-badge { + padding: 3px 10px; border-radius: 4px; font-size: 11px; + font-weight: 700; display: inline-block; letter-spacing: 0.3px; +} +.badge-buy { background: rgba(229,62,62,0.1); color: #E0E0E0; border: 1px solid rgba(200,60,60,0.18); } +.badge-hold { background: rgba(255,255,255,0.035); color: #888888; border: 1px solid rgba(255,255,255,0.08); } +.badge-profit { background: rgba(126,170,212,0.1); color: #9ABBE0; border: 1px solid rgba(126,170,212,0.2); } +.badge-loss { background: rgba(255,255,255,0.03); color: #444444; border: 1px solid rgba(255,255,255,0.05); } +.badge-none { background: transparent; color: #444444; border: 1px dashed rgba(255,255,255,0.08); } +.strat-summary-card { + background: linear-gradient(135deg, #1C1C1C 0%, #111111 100%); + padding: 16px; border-radius: 10px; + border: 1px solid rgba(255,255,255,0.11); + box-shadow: inset 0 1px 0 rgba(255,255,255,0.05); +} +.inline-edit-box { + background: rgba(255,255,255,0.025); padding: 16px; border-radius: 10px; + border: 1px dashed rgba(255,255,255,0.14); margin-bottom: 12px; + box-shadow: inset 0 0 20px rgba(201,168,76,0.02); +} +.onboarding-step { + background: linear-gradient(90deg, rgba(255,255,255,0.035) 0%, #161616 40%); + border-radius: 10px; padding: 14px 16px; margin-bottom: 10px; + border: 1px solid rgba(255,255,255,0.08); + border-left: 3px solid #D8D8D8; + color: #888888; font-size: 14px; +} +.analytics-metric { + background: linear-gradient(160deg, #1C1C1C 0%, #0C0C0C 100%); + border: 1px solid rgba(255,255,255,0.09); + border-radius: 10px; padding: 18px; text-align: center; + box-shadow: inset 0 1px 0 rgba(201,168,76,0.1), 0 2px 12px rgba(0,0,0,0.3); +} +.analytics-metric .metric-label { + font-size: 10px; font-weight: 700; color: #444444; + margin-bottom: 6px; letter-spacing: 1.5px; text-transform: uppercase; +} +.analytics-metric .metric-value { font-size: 24px; font-weight: 700; color: #EBEBEB; font-family: 'IBM Plex Mono', monospace; } +.data-badge-ok { + display: inline-flex; align-items: center; + background: rgba(255,255,255,0.05); color: #BBBBBB; + font-size: 10px; font-weight: 700; padding: 2px 8px; border-radius: 4px; + border: 1px solid rgba(255,255,255,0.12); letter-spacing: 0.3px; +} +.data-badge-warn { + display: inline-flex; align-items: center; + background: rgba(255,255,255,0.05); color: #D8D8D8; + font-size: 10px; font-weight: 700; padding: 2px 8px; border-radius: 4px; + border: 1px solid rgba(201,168,76,0.2); +} +@keyframes alertPulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.65; } +} +.risk-gauge-bar { + height: 8px; border-radius: 4px; background: rgba(255,255,255,0.04); + margin: 6px 0 10px; +} +.news-card { + background: linear-gradient(135deg,#1C1C1C 0%,#111111 100%); + border: 1px solid rgba(255,255,255,0.07); + border-radius: 10px; padding: 14px 16px; margin-bottom: 8px; +} +.news-card:hover { border-color: rgba(255,255,255,0.16); } +.div-badge { + display: inline-flex; align-items: center; gap: 4px; + background: rgba(255,255,255,0.06); color: #AAAAAA; + font-size: 11px; font-weight: 700; padding: 3px 9px; border-radius: 4px; + border: 1px solid rgba(255,255,255,0.12); +} +/* ── 포트폴리오 카드: container(border=True) */ +div[data-testid="stVerticalBlockBorderWrapper"] { + background: linear-gradient(135deg, #1C1C1C 0%, #111111 100%) !important; + border: 1px solid rgba(255,255,255,0.09) !important; + border-radius: 14px !important; + margin-bottom: 12px !important; + box-shadow: 0 2px 16px rgba(0,0,0,0.3) !important; + overflow: hidden !important; +} +/* 종목명 행 grid 레이아웃 */ +div.element-container:has(.portfolio-item-row-marker) + div [data-testid="stColumns"], +div.element-container:has(.portfolio-item-row-marker) + div [data-testid="stHorizontalBlock"] { + display: grid !important; grid-template-columns: 1fr 40px 40px 40px !important; + align-items: center !important; width: 100% !important; gap: 4px !important; +} +div.element-container:has(.portfolio-item-row-marker) + div [data-testid="column"], +div.element-container:has(.portfolio-item-row-marker) + div [data-testid="stColumn"] { + width: 100% !important; min-width: 0 !important; padding: 0 !important; margin: 0 !important; +} +/* ↑ ✎ ✕ 아이콘 버튼 */ +div.element-container:has(.action-marker) + div button { + background-color: transparent !important; border: none !important; box-shadow: none !important; + color: #444444 !important; padding: 0 !important; width: 40px !important; height: 40px !important; + font-size: 16px !important; display: flex !important; justify-content: center !important; + align-items: center !important; transition: all 0.2s !important; +} +div.element-container:has(.action-marker.delete) + div button:hover { color: #CC5555 !important; transform: scale(1.15) !important; } +div.element-container:has(.action-marker.edit) + div button:hover { color: #AAAAAA !important; transform: scale(1.15) !important; } +div.element-container:has(.action-marker.log) + div button:hover { color: #AAAAAA !important; transform: scale(1.15) !important; } +/* ── 시안 A 카드 ── */ +.pca-card { + background: linear-gradient(135deg, #1C1C1C 0%, #111111 100%); + border: 1px solid rgba(255,255,255,0.09); + border-radius: 14px; + padding: 16px 18px; + margin-bottom: 8px; + display: flex; + align-items: flex-start; + justify-content: space-between; + transition: border-color 0.2s; +} +.pca-card:hover { border-color: rgba(255,255,255,0.09); cursor: default; } +.pca-body { flex: 1; min-width: 0; } +.pca-name { + font-size: 17px; font-weight: 900; color: #EBEBEB; + letter-spacing: -0.3px; margin-bottom: 6px; +} +.pca-ticker { + font-size: 10px; font-weight: 700; color: #C9A84C; + background: rgba(201,168,76,0.1); + border: 1px solid rgba(201,168,76,0.2); + padding: 1px 7px; border-radius: 4px; + margin-left: 8px; letter-spacing: 0.5px; + vertical-align: middle; +} +.pca-verdict { + font-size: 10px; color: #AAAAAA; + background: rgba(255,255,255,0.06); + border: 1px solid rgba(255,255,255,0.1); + padding: 1px 6px; border-radius: 3px; + margin-left: 6px; vertical-align: middle; +} +.pca-returns { + font-size: 13px; color: #666; margin-bottom: 5px; + font-family: 'IBM Plex Mono', monospace; +} +.pca-avg { color: #888; } +.pca-cur { color: #EBEBEB; font-weight: 500; } +.pca-pct-pos { color: #E0E0E0; font-weight: 700; } +.pca-pct-neg { color: #7AABDA; font-weight: 700; } +.pca-goal { color: #C9A84C; } +.pca-strategy { font-size: 11px; color: #555; letter-spacing: 0.3px; } +.pca-strategy span { + color: #888; background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.08); + padding: 1px 8px; border-radius: 4px; margin-left: 4px; +} +.pca-icons { + display: flex; gap: 6px; flex-shrink: 0; + margin-left: 12px; align-items: center; +} +.pca-icon { + width: 32px; height: 32px; border-radius: 8px; + background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.08); + color: #444; display: flex; align-items: center; + justify-content: center; font-size: 14px; + cursor: pointer; transition: color 0.2s, background 0.2s; +} +.pca-icon:hover { color: #AAAAAA; background: rgba(255,255,255,0.09); } +.pca-icon-del:hover { color: #CC5555 !important; background: rgba(180,60,60,0.12) !important; } +/* PCATRIGGER 숨긴 버튼 - JS로 처리 */ +/* ── 포트폴리오 카드 버튼행: 카드 HTML 바로 아래 붙이기 */ +.port-card-btn-row { + background: linear-gradient(135deg, #161616 0%, #0E0E0E 100%); + border: 1px solid rgba(255,255,255,0.09); + border-top: none; + border-radius: 0 0 16px 16px; + padding: 8px 10px 10px 10px; + margin-bottom: 16px; + display: flex; + gap: 6px; + align-items: center; +} +/* ── 카드 버튼행 마커: 바로 다음 stHorizontalBlock을 카드 하단처럼 */ +div.element-container:has(.card-btn-marker) + div [data-testid="stHorizontalBlock"], +div.element-container:has(.card-btn-marker) + div [data-testid="stColumns"] { + background: linear-gradient(135deg, #1C1C1C 0%, #111111 100%) !important; + border: 1px solid rgba(255,255,255,0.08) !important; + border-top: none !important; + border-radius: 0 0 16px 16px !important; + padding: 6px 8px 10px 8px !important; + margin-top: -2px !important; + margin-bottom: 16px !important; + flex-wrap: nowrap !important; + gap: 4px !important; +} +div.element-container:has(.card-btn-marker) + div [data-testid="stColumn"], +div.element-container:has(.card-btn-marker) + div [data-testid="column"] { + min-width: 0 !important; + flex-shrink: 1 !important; + padding: 0 2px !important; +} +""" + +def load_css(): + st.markdown(f""" + + """, unsafe_allow_html=True) + +load_css() +components.html(""" + + + +""", height=1) +# ============================================================ +# 투자자 프로필 상수 (세션 초기화보다 먼저 정의) +# ============================================================ +_PROFILE_STYLE_MAP = { + "중장기 성장주": { + "desc": "중장기 성장주 투자자 (6개월 이상 보유 원칙)", + "preferred": "성장형 주식, 턴어라운드 주식, 기술주", + "risk_hint": "성장과 턴어라운드를 위한 리스크는 수용", + "moat_hint": "기술적 해자 훼손이 없는 단기 변동성은 노이즈로 취급, 중장기 성장 스토리가 핵심 (해자가 훼손일 경우에는 반드시 말해줄 것)", + }, + "단기 트레이딩": { + "desc": "단기 트레이더 (1개월 이내 매매 원칙)", + "preferred": "모멘텀 주식, 변동성 높은 종목", + "risk_hint": "단기 손절 기준을 엄격히 적용, 손실 최소화 우선", + "moat_hint": "기술적 차트 패턴과 거래량 신호를 우선 분석. 장기 펀더멘털보다 단기 촉매에 집중", + }, + "배당 / 방어형": { + "desc": "배당·방어형 투자자 (안정적 현금흐름 우선)", + "preferred": "배당주, 리츠(REITs), 필수소비재, 유틸리티", + "risk_hint": "원금 보전 우선, 고변동성 종목 지양", + "moat_hint": "배당 지속 가능성(페이아웃 비율·FCF)과 방어적 해자(브랜드·규제 보호)를 핵심 지표로 평가", + }, + "가치 투자": { + "desc": "가치 투자자 (저평가 종목 장기 보유)", + "preferred": "PBR·PER 저평가 종목, 턴어라운드 기업", + "risk_hint": "중간 리스크 허용, 안전 마진 확보 필수", + "moat_hint": "내재가치 대비 할인율(안전마진)과 경쟁 해자의 지속성 중심 분석. 단기 주가 변동은 노이즈로 취급", + }, +} +_RISK_LEVEL_LABELS = ["낮음", "중간", "중간~높음", "높음"] +DEFAULT_INVESTOR_PROFILE = { + "style": "중장기 성장주", + "risk_level": "중간~높음", + "extra_notes": "", +} + +# ============================================================ +if 'api_key' not in st.session_state: st.session_state.api_key = os.getenv("GEMINI_API_KEY", "") +if 'show_menu' not in st.session_state: st.session_state.show_menu = False +if 'main_menu' not in st.session_state: st.session_state.main_menu = "⌂ 홈 & 스캔" +if 'alert_panel_minimized' not in st.session_state: st.session_state.alert_panel_minimized = False +if 'alert_panel_start_time' not in st.session_state: st.session_state.alert_panel_start_time = time.time() +if 'alert_active_tab' not in st.session_state: st.session_state.alert_active_tab = None +if 'fee_rate' not in st.session_state: st.session_state.fee_rate = 0.00015 +if 'target_return_pct' not in st.session_state: st.session_state.target_return_pct = 20.0 +if 'show_usd' not in st.session_state: st.session_state.show_usd = False +# investor_profile 은 HF 로드 후 병합하므로 여기선 dict 기본값만 설정 +if 'investor_profile' not in st.session_state: st.session_state.investor_profile = dict(DEFAULT_INVESTOR_PROFILE) + +def _key_hash(): + return hashlib.sha256(st.session_state.api_key.encode()).hexdigest()[:16] + +def toggle_menu(): st.session_state.show_menu = not st.session_state.show_menu +def go_home(): + st.session_state.main_menu = "⌂ 홈 & 스캔" + st.session_state.p_diag_mode = False + st.session_state.show_menu = False + for k in ['active_ticker', 'detail_ticker']: + st.session_state.pop(k, None) + +def go_back(): + st.session_state.show_menu = False + if 'active_ticker' in st.session_state: del st.session_state['active_ticker'] + elif 'detail_ticker' in st.session_state: del st.session_state['detail_ticker'] + elif st.session_state.get('p_diag_mode'): st.session_state.p_diag_mode = False + else: st.session_state.main_menu = "⌂ 홈 & 스캔" + +def select_menu(name): + st.session_state.main_menu = name + st.session_state.show_menu = False + st.session_state.p_diag_mode = False + for k in ['active_ticker', 'detail_ticker']: + st.session_state.pop(k, None) + +st.button("⬢ INVEST PRO ALPHA", key="header_logo_btn", help="header_logo", on_click=go_home) +# pca_trigger 숨긴 버튼 - JS가 innerText="PCATRIGGER"로 찾아서 클릭 +st.button("PCATRIGGER", key="pca_trigger_btn") + +# ── pca_action query param 처리 (카드 아이콘 버튼 -> JS -> query param -> 여기서 처리) +_pca = st.query_params.get("pca_action", "") +if _pca: + from urllib.parse import unquote + _pca = unquote(_pca) + st.query_params.clear() + parts = _pca.split(":") # 형식: "action:idx" 또는 "action:idx:ticker" + if len(parts) >= 2: + _act, _idx = parts[0], parts[1] + _ticker = parts[2] if len(parts) > 2 else "" + _idx_int = int(_idx) if _idx.isdigit() else None + if _act == "detail" and _ticker: + st.session_state.detail_ticker = _ticker + st.session_state.p_diag_mode = False + st.session_state.main_menu = "▤ 자산 상세 진단" + st.rerun() + elif _act == "log" and _idx_int is not None: + st.session_state[f"log_mode_{_idx_int}"] = not st.session_state.get(f"log_mode_{_idx_int}", False) + st.session_state[f"edit_mode_{_idx_int}"] = False + st.rerun() + elif _act == "edit" and _idx_int is not None: + st.session_state[f"edit_mode_{_idx_int}"] = not st.session_state.get(f"edit_mode_{_idx_int}", False) + st.session_state[f"log_mode_{_idx_int}"] = False + st.rerun() + elif _act == "del" and _idx_int is not None: + st.session_state["_pca_del_idx"] = _idx_int + st.rerun() + +if not st.session_state.api_key: + st.markdown(""" +
+
+ SYSTEM ACCESS +
+
+ Invest Pro Alpha +
+

+ 본인의 Gemini API KEY로 접속합니다.
+ 데이터는 키별로 완전히 분리 저장됩니다. +

+
+
+
+ GEMINI API KEY +
+ """, unsafe_allow_html=True) + input_key = st.text_input("API KEY", type="password", + placeholder="AIzaSy...", + label_visibility="collapsed") + st.markdown(""" +
+ 🔑   + Google AI Studio에서 무료 발급 가능 +
+
+ """, unsafe_allow_html=True) + if st.button("시스템 접속", use_container_width=True, type="primary"): + if input_key.startswith("AIza"): + st.session_state.api_key = input_key + st.success("인증 성공! 데이터를 불러옵니다...") + time.sleep(1); st.rerun() + else: + st.error("올바른 API 키 형식이 아닙니다. (AIzaSy... 로 시작)") + st.stop() + +genai.configure(api_key=st.session_state.api_key) + +@st.cache_data +def get_valid_models(key_hash): + try: + return [m.name.replace('models/', '') for m in genai.list_models() + if 'generateContent' in m.supported_generation_methods] + except: + return ["gemini-1.5-flash", "gemini-1.5-pro", "gemini-2.5-flash", "gemini-2.5-pro"] + +AVAILABLE_MODELS = get_valid_models(_key_hash()) +if 'selected_model' not in st.session_state: + st.session_state.selected_model = AVAILABLE_MODELS[0] + +# ============================================================ +# AI 응답 유틸 +# ============================================================ +MODEL_PRIORITY = [ + "gemini-2.0-flash", + "gemini-2.0-flash-lite", + "gemini-1.5-flash", + "gemini-1.5-flash-8b", + "gemini-1.5-pro", + "gemini-2.5-flash-preview-04-17", + "gemini-2.5-pro-preview-03-25", +] + +def _classify_error(e): + msg = str(e).lower() + if "429" in msg or "quota" in msg or "rate" in msg or "resource" in msg: return "quota" + if "500" in msg or "503" in msg or "unavailable" in msg: return "server" + if "invalid" in msg or "not found" in msg or "404" in msg: return "invalid" + return "other" + +def _get_model_order(): + seen = set(); result = [] + candidates = ( + [st.session_state.get("last_success_model", "")] + + [st.session_state.selected_model] + + MODEL_PRIORITY + AVAILABLE_MODELS + ) + for m in candidates: + if m and m not in seen: + seen.add(m); result.append(m) + return result + +@st.cache_data(ttl=3600, show_spinner=False) +def _fetch_ai_json_cached(prompt, model_name, key_hash, is_list): + temp = 0.85 if is_list else 0.2 + model = genai.GenerativeModel( + model_name, + generation_config={"response_mime_type": "application/json", "temperature": temp} + ) + return model.generate_content(prompt).text + +def _parse_ai(text, is_list): + clean = re.sub(r'```(?:json)?', '', text).replace('```', '').strip() + m = re.search(r'\[.*\]' if is_list else r'\{.*\}', clean, re.DOTALL) + if m: clean = m.group(0) + try: return json.loads(clean) + except: return ast.literal_eval(clean.replace('true','True').replace('false','False').replace('null','None')) + +def get_ai_json_response(prompt, bypass_cache=False): + if not st.session_state.api_key: return None + is_list = "1차원 JSON 배열" in prompt + key_hash = _key_hash() + errors = [] + + for mn in _get_model_order(): + try: + if bypass_cache: + temp = 0.85 if is_list else 0.2 + model = genai.GenerativeModel( + mn, + generation_config={"response_mime_type": "application/json", "temperature": temp} + ) + raw = model.generate_content(prompt).text + else: + raw = _fetch_ai_json_cached(prompt, mn, key_hash, is_list) + + data = _parse_ai(raw, is_list) + if not is_list: + data.setdefault("recommendation_stars", "★★★★☆") + data.setdefault("confidence_score", 50) + data.setdefault("confidence_reason", "자동 분석 완료") + st.session_state["last_success_model"] = mn + return data + + except Exception as e: + err_type = _classify_error(e) + errors.append((mn, err_type, str(e)[:80])) + if err_type == "server": time.sleep(0.5) + if err_type == "invalid" and mn in AVAILABLE_MODELS: + AVAILABLE_MODELS.remove(mn) + continue + + err_summary = " | ".join([f"{m}({t})" for m, t, _ in errors[:3]]) + return ( + ["MSFT", "CRWD", "PLTR"] if is_list + else { + "action_type": "분석 실패", + "summary": f"모든 모델 응답 실패. 잠시 후 재시도해 주세요. ({err_summary})", + "recommendation_stars": "분석불가", + "confidence_score": 0, + "confidence_reason": f"API 오류로 분석 불가 - {err_summary}", + } + ) + +# ============================================================ +# 데이터 조회 +# ============================================================ +def resolve_ticker(query): + if query.isalpha() and query.isupper() and len(query) <= 5: return query + res = get_ai_json_response(f"회사명 '{query}'의 미국 주식 공식 티커 1개만. 반드시 [\"AAPL\"] 형태의 1차원 JSON 배열 형식으로만 출력.") + if isinstance(res, list) and res and isinstance(res[0], str): return res[0].strip().upper() + return query.strip().upper() + +def _safe_price(ticker): + try: + h = yf.Ticker(ticker).history(period="1mo") + if not h.empty: return float(h['Close'].dropna().iloc[-1]) + except: pass + try: return float(yf.Ticker(ticker).fast_info['last_price']) + except: pass + try: + info = yf.Ticker(ticker).info + return float(info.get('currentPrice', info.get('previousClose', 0.0))) + except: return 0.0 + +@st.cache_data(ttl=60, show_spinner=False) +def get_prices_bulk(tickers_tuple): + return {t: _safe_price(t) for t in tickers_tuple} + +@st.cache_data(ttl=300, show_spinner=False) +def get_daily_change_bulk(tickers_tuple): + result = {} + for t in tickers_tuple: + try: + hist = yf.Ticker(t).history(period="2d", interval="1d") + if len(hist) >= 2: + prev = float(hist['Close'].iloc[-2]) + today_p = float(hist['Close'].iloc[-1]) + result[t] = (today_p / prev - 1) * 100 + else: + result[t] = 0.0 + except: result[t] = 0.0 + return result + +@st.cache_data(ttl=3600) +def get_exchange_rate(): + try: return float(yf.Ticker("KRW=X").fast_info['last_price']) + except: return 1450.0 + +@st.cache_data(ttl=600) +def get_ticker_info(ticker_or_name): + try: + ct = resolve_ticker(ticker_or_name) + price = _safe_price(ct) + rate = get_exchange_rate() + try: + info = yf.Ticker(ct).info + name = info.get('shortName') or info.get('longName') + if not name: + name = ct if str(ticker_or_name).isalpha() and str(ticker_or_name).isupper() else str(ticker_or_name) + except: + name = ct if str(ticker_or_name).isalpha() and str(ticker_or_name).isupper() else str(ticker_or_name) + return str(name), int(price * rate), ct + except: return str(ticker_or_name), 0, str(ticker_or_name).upper() + +@st.cache_data(ttl=3600, show_spinner=False) +def get_ticker_metadata(ticker): + try: + info = yf.Ticker(ticker).info + return info.get('sector','Unknown'), info.get('beta', 1.0) + except: return 'Unknown', 1.0 + +@st.cache_data(ttl=3600, show_spinner=False) +def get_analyst_target(ticker): + try: + return int(yf.Ticker(ticker).info.get('targetMeanPrice', 0.0) * get_exchange_rate()) + except: return 0 + +@st.cache_data(ttl=1800, show_spinner=False) +def get_recent_news(ticker): + """ + yfinance .news 에서 헤드라인 + 기사 본문 앞부분을 함께 반환. + - 각 기사 URL을 병렬 fetch (timeout=6s) → HTML 태그 제거 후 앞 400자 추출 + - fetch 실패 시 헤드라인만 반환 (기존 동작 유지) + """ + import requests + + def _fetch_body(url: str) -> str: + try: + resp = requests.get( + url, timeout=6, + headers={"User-Agent": ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/124.0 Safari/537.36" + )}, + allow_redirects=True, + ) + if resp.status_code != 200: + return "" + text = resp.text + # script / style 블록 제거 + text = re.sub(r"]*>.*?", " ", text, flags=re.DOTALL | re.IGNORECASE) + text = re.sub(r"]*>.*?", " ", text, flags=re.DOTALL | re.IGNORECASE) + # HTML 태그 제거 + text = re.sub(r"<[^>]+>", " ", text) + text = re.sub(r"\s+", " ", text).strip() + # 의미 있는 본문 영역 앞 400자 + return text[:400] + except Exception: + return "" + + try: + raw_news = yf.Ticker(ticker).news or [] + items = raw_news[:5] + if not items: + return [] + + urls = [n.get("link") or n.get("url", "") for n in items] + titles = [n.get("title", "") for n in items] + + # 병렬 fetch (최대 5개 × 6s → 실질 ~6s 이내) + bodies: list[str] = [""] * len(items) + with concurrent.futures.ThreadPoolExecutor(max_workers=5) as ex: + futs = {ex.submit(_fetch_body, u): i for i, u in enumerate(urls) if u} + for fut in concurrent.futures.as_completed(futs, timeout=8): + idx = futs[fut] + try: + bodies[idx] = fut.result() + except Exception: + pass + + results = [] + for title, body in zip(titles, bodies): + if not title: + continue + if body: + # 본문이 있으면 헤드라인 + 요약 형태로 + snippet = body[:300].rstrip() + ("..." if len(body) >= 300 else "") + results.append(f"- [제목] {title}\n [본문 요약] {snippet}") + else: + results.append(f"- {title}") + return results + except Exception: + return [] + +@st.cache_data(ttl=3600, show_spinner=False) +def get_rich_financial_context(ticker): + try: + t = yf.Ticker(ticker) + info = t.info + hist = t.history(period="3mo") + + def pct(v): return f"{v*100:.1f}%" if isinstance(v, float) else 'N/A' + def num(v): return str(round(v, 2)) if isinstance(v, (int, float)) else 'N/A' + + cp = info.get('currentPrice') or info.get('previousClose', 0) + ma50 = info.get('fiftyDayAverage', 0) + ma200 = info.get('twoHundredDayAverage', 0) + wk52h = info.get('fiftyTwoWeekHigh', 0) + wk52l = info.get('fiftyTwoWeekLow', 0) + mcap = info.get('marketCap', 0) + mcap_s = f"${mcap/1e9:.1f}B" if mcap > 1e9 else f"${mcap/1e6:.0f}M" + + vol_s = trend_s = 'N/A' + if not hist.empty and len(hist) > 5: + vol_s = f"{hist['Close'].pct_change().std()*100:.2f}%" + trend_s = f"{((hist['Close'].iloc[-1]/hist['Close'].iloc[0])-1)*100:+.2f}%" + + tm = info.get('targetMeanPrice', 0) + th = info.get('targetHighPrice', 0) + tl = info.get('targetLowPrice', 0) + target_s = f"${tm:.2f}/${th:.2f}/${tl:.2f}" if tm > 0 else 'N/A' + + div_yield = info.get('dividendYield', 0) + div_s = f"{div_yield*100:.2f}%" if div_yield else 'N/A' + + # ── 피보나치 되돌림 레벨 (52주 고/저 기준) ── + fib_s = 'N/A' + if wk52h > wk52l > 0: + swing = wk52h - wk52l + f382 = wk52h - swing * 0.382 + f500 = wk52h - swing * 0.500 + f618 = wk52h - swing * 0.618 + fib_s = f"38.2%=${f382:.2f} / 50%=${f500:.2f} / 61.8%=${f618:.2f}" + + # ── 52주 구간 내 현재가 위치 ── + wk52_pos_s = 'N/A' + if wk52h > wk52l > 0 and cp > 0: + pos = (cp - wk52l) / (wk52h - wk52l) * 100 + wk52_pos_s = f"{pos:.1f}% (0%=52주저점, 100%=52주고점)" + + # ── MA 이격도 ── + ma_gap_s = 'N/A' + if ma50 > 0 and ma200 > 0 and cp > 0: + gap50 = (cp / ma50 - 1) * 100 + gap200 = (cp / ma200 - 1) * 100 + ma_gap_s = f"MA50 대비 {gap50:+.1f}% / MA200 대비 {gap200:+.1f}%" + + # ── ROIC 근사 (영업현금흐름 / 투하자본) ── + roic_s = 'N/A' + try: + op_cf = info.get('operatingCashflow') or 0 + total_assets = info.get('totalAssets') or 0 + curr_liab = info.get('totalCurrentLiabilities') or 0 + invested_cap = total_assets - curr_liab + if invested_cap > 0 and op_cf != 0: + roic_s = f"{op_cf / invested_cap * 100:.1f}% (영업현금흐름 기반 근사치)" + except: + pass + + # ── FCF Yield ── + fcf_s = 'N/A' + try: + fcf = info.get('freeCashflow') or 0 + if fcf != 0 and mcap > 0: + fcf_s = f"{fcf / mcap * 100:.2f}%" + except: + pass + + rows = { + "섹터/산업": f"{info.get('sector','N/A')} / {info.get('industry','N/A')}", + "시가총액": mcap_s, + "현재가/MA50/MA200": f"${cp:.2f} / ${ma50:.2f} / ${ma200:.2f}", + "MA 이격도": ma_gap_s, + "52주 고/저": f"${wk52h:.2f} / ${wk52l:.2f}", + "52주 구간내 현재 위치": wk52_pos_s, + "피보나치 되돌림 레벨": fib_s, + "3개월 주가 추이": trend_s, + "3개월 변동성": vol_s, + "PER(TTM/Forward)": f"{num(info.get('trailingPE'))} / {num(info.get('forwardPE'))}", + "PBR": num(info.get('priceToBook')), + "PSR": num(info.get('priceToSalesTrailing12Months')), + "EV/EBITDA": num(info.get('enterpriseToEbitda')), + "매출 성장률(YoY)": pct(info.get('revenueGrowth')), + "순이익 성장률(YoY)": pct(info.get('earningsGrowth')), + "매출총이익률": pct(info.get('grossMargins')), + "영업이익률": pct(info.get('operatingMargins')), + "순이익률": pct(info.get('profitMargins')), + "ROE": pct(info.get('returnOnEquity')), + "ROIC(근사)": roic_s, + "FCF Yield": fcf_s, + "부채비율(D/E)": num(info.get('debtToEquity')), + "유동비율": num(info.get('currentRatio')), + "배당수익률": div_s, + "애널리스트 의견": f"{info.get('recommendationKey','N/A')} ({info.get('numberOfAnalystOpinions',0)}명)", + "목표주가(평균/고/저)": target_s, + } + lines = [f" - {k}: {v}" for k, v in rows.items() if v not in ('N/A', 'N/A / N/A')] + return "\n".join(lines), len(lines) >= 8 + except Exception as e: + return f" - 재무 데이터 조회 실패: {str(e)[:60]}", False + +@st.cache_data(ttl=600, show_spinner=False) +def get_ai_alert(summary, key_hash, model_name): + try: + model = genai.GenerativeModel(model_name) + prompt = f"[냉철한 월스트리트 트레이더]\n포트폴리오: {summary}\n1~2문장의 날카로운 알림. 마크다운 기호 금지." + return model.generate_content(prompt, generation_config={"temperature":0.5}).text.strip() + except: + return "현재 포트폴리오 변동성을 모니터링 중입니다. 자산 상세 진단을 확인하세요." + +@st.cache_data(ttl=3600, show_spinner=False) +def get_dividend_info(ticker): + try: + info = yf.Ticker(ticker).info + div_yield = info.get('dividendYield', 0) or 0 + div_rate = info.get('dividendRate', 0) or 0 + ex_div = info.get('exDividendDate', None) + ex_div_str = datetime.fromtimestamp(ex_div).strftime("%Y-%m-%d") if ex_div else "-" + return { + "yield_pct": round(div_yield * 100, 2), + "annual_rate": div_rate, + "ex_date": ex_div_str, + } + except: + return {"yield_pct": 0, "annual_rate": 0, "ex_date": "-"} + +@st.cache_data(ttl=3600, show_spinner=False) +def get_earnings_calendar(tickers_tuple): + result = {} + for ticker in tickers_tuple: + try: + t = yf.Ticker(ticker) + info = t.info + ts = info.get("earningsTimestamp") or info.get("earningsDate") + if ts: + if isinstance(ts, (list, tuple)): ts = ts[0] + dt_earn = datetime.fromtimestamp(int(ts)) + days_left = (dt_earn - datetime.now()).days + eps_est = info.get("epsForward") or info.get("epsCurrentYear") or 0 + rev_raw = info.get("revenueEstimate", {}) + rev_est = "" + if isinstance(rev_raw, dict): + av = rev_raw.get("avg", {}) + if isinstance(av, dict): rev_val = av.get("raw", 0) + else: rev_val = float(av) if av else 0 + if rev_val > 1e9: rev_est = f"${rev_val/1e9:.1f}B" + elif rev_val > 1e6: rev_est = f"${rev_val/1e6:.0f}M" + result[ticker] = { + "date": dt_earn.strftime("%Y-%m-%d"), + "days_left": days_left, + "eps_est": round(float(eps_est), 2) if eps_est else 0, + "rev_est": rev_est, + } + else: + try: + cal = t.calendar + if cal is not None and not (hasattr(cal, 'empty') and cal.empty): + if isinstance(cal, dict): + ed = cal.get("Earnings Date") + if ed: + if isinstance(ed, (list, tuple)): ed = ed[0] + dt_earn2 = pd.to_datetime(ed) + days_left2 = (dt_earn2 - pd.Timestamp.now()).days + result[ticker] = { + "date": dt_earn2.strftime("%Y-%m-%d"), + "days_left": days_left2, + "eps_est": 0, "rev_est": "", + } + except: pass + except: pass + return result + +@st.cache_data(ttl=60, show_spinner=False) +def get_usd_price(ticker): + return _safe_price(ticker) + +def _build_portfolio_context(prices, rate): + if st.session_state.df.empty: + return "현재 보유 종목 없음." + lines = [] + total_cost = total_val = 0.0 + for _, row in st.session_state.df.iterrows(): + t = row['티커']; ap = float(row['평단가']); qty = float(row['수량']) + ck = prices.get(t, 0) * rate + if ck <= 0: ck = ap + pct = (ck / ap - 1) * 100 if ap > 0 else 0 + total_cost += ap * qty + total_val += ck * qty + rp = st.session_state.full_stock_reports.get(f"{t}_{ap}", {}).get("report", {}) + act = rp.get("action_type", "미분석") + lines.append( + f" · {row['종목명']}({t}): 평단 {int(ap):,}원 -> 현재 {int(ck):,}원 " + f"({pct:+.1f}%), 수량 {qty}주, 전략판정 [{act}]" + ) + port_pct = (total_val / total_cost - 1) * 100 if total_cost > 0 else 0 + header = ( + f"[내 포트폴리오 현황 - 분석 기준일: {datetime.now().strftime('%Y-%m-%d')}]\n" + f" 총 투자원금: {int(total_cost):,}원 / 총 평가액: {int(total_val):,}원 / " + f"전체 수익률: {port_pct:+.1f}%\n" + f" 보유 종목 ({len(lines)}개):\n" + ) + return header + "\n".join(lines) + +def calc_52w_position(ticker, current_price_usd): + try: + info = yf.Ticker(ticker).info + h52 = info.get('fiftyTwoWeekHigh', 0) + l52 = info.get('fiftyTwoWeekLow', 0) + if h52 > l52 > 0: + return round((current_price_usd - l52) / (h52 - l52) * 100, 1) + except: pass + return 50.0 + +PRICE_TTL = 300 + +def get_all_prices(): + now = time.time() + if now - st.session_state.get('price_cache_ts', 0) < PRICE_TTL: + return st.session_state.get('price_cache', {}) + tickers = list(set( + st.session_state.df['티커'].tolist() + + st.session_state.fav_df['티커'].tolist() + )) + if not tickers: return {} + prices = get_prices_bulk(tuple(sorted(tickers))) + st.session_state.price_cache = prices + st.session_state.price_cache_ts = now + return prices + +# ============================================================ +# 허깅페이스 DB +# ============================================================ +REPO_ID = "ditgun/my-invest-db" # ← 본인 HF 저장소로 변경 (private 권장) + +def _user_files(): + """API 키 해시를 폴더명으로 사용해 사용자별 데이터 분리.""" + h = _key_hash() # 이미 정의된 함수 — API 키 sha256 앞 16자 + return { + "db": f"users/{h}/assets.csv", + "cache": f"users/{h}/cache.json", + "fav": f"users/{h}/fav.csv", + "trades": f"users/{h}/trades.csv", + "history": f"users/{h}/history.json", + "settings": f"users/{h}/settings.json", + } + +# 로컬 임시 파일명 (충돌 방지용 해시 prefix) +def _local(key): + h = _key_hash() + names = { + "db": "assets.csv", "cache": "cache.json", + "fav": "fav.csv", "trades": "trades.csv", + "history": "history.json", "settings": "settings.json" + } + return f"_tmp_{h}_{names[key]}" + +_NEW_REPORT_FIELDS = {"thesis_validity", "action_analysis", "additional_buy_analysis", + "target_remaining", "portfolio_context_judgment", + "growth_moat_quantitative", "growth_moat_qualitative", + "catalyst", "entry_zones", "portfolio_fit"} + +def _is_new_structure(report: dict) -> bool: + if not isinstance(report, dict): return False + return bool(_NEW_REPORT_FIELDS & report.keys()) + +def _hf_dl(key): + tok = os.getenv("HF_TOKEN") + if not tok: return False + remote = _user_files()[key] + local = _local(key) + try: + p = hf_hub_download(repo_id=REPO_ID, filename=remote, repo_type="dataset", token=tok) + shutil.copy(p, local); return True + except: return False + +def _hf_ul(key): + tok = os.getenv("HF_TOKEN") + if not tok: return + remote = _user_files()[key] + local = _local(key) + try: + HfApi(token=tok).upload_file( + path_or_fileobj=local, path_in_repo=remote, + repo_id=REPO_ID, repo_type="dataset" + ) + except: pass + +# ── 여기부터 추가 ────────────────────────────── +_LEGACY_MAP = { + "db": "my_assets_v30.csv", + "cache": "analysis_cache_v31.json", + "fav": "my_fav_v30.csv", + "trades": "my_trades_v30.csv", + "history": "portfolio_history_v1.json", +} + +def _migrate_legacy_if_needed(key): + """새 경로에 파일 없으면 루트 레거시 파일을 복사해 업로드. 1회만 실행.""" + tok = os.getenv("HF_TOKEN") + if not tok: return + remote_new = _user_files()[key] + legacy_fn = _LEGACY_MAP[key] + local = _local(key) + # 새 경로에 이미 있으면 스킵 + try: + hf_hub_download(repo_id=REPO_ID, filename=remote_new, + repo_type="dataset", token=tok) + return + except: pass + # 루트 레거시 파일 → 새 경로로 복사 업로드 + try: + p = hf_hub_download(repo_id=REPO_ID, filename=legacy_fn, + repo_type="dataset", token=tok) + shutil.copy(p, local) + HfApi(token=tok).upload_file( + path_or_fileobj=local, path_in_repo=remote_new, + repo_id=REPO_ID, repo_type="dataset" + ) + except: pass +# ── 여기까지 추가 ────────────────────────────── + +if 'df' not in st.session_state: + _migrate_legacy_if_needed("db") # ← 각 로드 앞에 호출 + ok = _hf_dl("db") + ... + +if 'df' not in st.session_state: + ok = _hf_dl("db") + try: st.session_state.df = pd.read_csv(_local("db")) + except: + if ok: st.warning("⚠️ 자산 데이터 파싱 오류. 빈 포트폴리오로 시작합니다.") + st.session_state.df = pd.DataFrame(columns=["티커","종목명","평단가","수량","매수근거","매수일"]) + for col in ['매수근거','매수일']: + if col not in st.session_state.df.columns: + st.session_state.df[col] = "" + +if 'fav_df' not in st.session_state: + _hf_dl("fav") + try: st.session_state.fav_df = pd.read_csv(_local("fav")) + except: st.session_state.fav_df = pd.DataFrame(columns=["티커","종목명"]) + +if 'trade_df' not in st.session_state: + _hf_dl("trades") + try: st.session_state.trade_df = pd.read_csv(_local("trades")) + except: st.session_state.trade_df = pd.DataFrame( + columns=["일시","티커","종목명","구분","매매가","수량","실현손익","수수료","태그","메모","매수근거"]) + for col in ['매수근거','수수료']: + if col not in st.session_state.trade_df.columns: + st.session_state.trade_df[col] = 0 if col == '수수료' else "" + +if 'full_stock_reports' not in st.session_state: + _hf_dl("cache") + try: + with open(_local("cache"), "r", encoding="utf-8") as f: + d = json.load(f) + raw_individual = d.get("individual", {}) + raw_portfolio = d.get("portfolio", None) + cleaned = {}; purged = 0 + for key, val in raw_individual.items(): + rpt = val.get("report", {}) if isinstance(val, dict) else {} + if _is_new_structure(rpt): cleaned[key] = val + else: purged += 1 + st.session_state.full_stock_reports = cleaned + if raw_portfolio and _is_new_structure(raw_portfolio): + st.session_state.p_diag_res = raw_portfolio + else: + st.session_state.p_diag_res = None + if purged > 0: + st.toast(f"분석 구조 업데이트: {purged}개 종목을 재분석합니다.", icon="🔄") + except: + st.session_state.full_stock_reports = {} + st.session_state.p_diag_res = None + +for k, v in [('p_diag_mode', False), ('price_cache', {}), ('price_cache_ts', 0.0)]: + if k not in st.session_state: st.session_state[k] = v + +def save_assets(): + st.session_state.df.to_csv(_local("db"), index=False); _hf_ul("db") + +if "_pca_del_idx" in st.session_state and "df" in st.session_state: + _di = st.session_state.pop("_pca_del_idx") + if _di in st.session_state.df.index: + st.session_state.df = st.session_state.df.drop(_di).reset_index(drop=True) + save_assets() + st.session_state.price_cache_ts = 0 + st.rerun() + +def save_fav(): + st.session_state.fav_df.to_csv(_local("fav"), index=False); _hf_ul("fav") + +def save_trades(): + st.session_state.trade_df.to_csv(_local("trades"), index=False); _hf_ul("trades") + +def save_cache(): + def _s(o): + if hasattr(o, 'item'): return o.item() + raise TypeError + d = {"individual": st.session_state.get('full_stock_reports',{}), + "portfolio": st.session_state.get('p_diag_res', None)} + with open(_local("cache"), "w", encoding="utf-8") as f: + json.dump(d, f, ensure_ascii=False, indent=2, default=_s) + _hf_ul("cache") + +def save_settings(): + """투자자 프로필 + 앱 설정을 HF 저장소에 저장.""" + payload = { + "investor_profile": st.session_state.get("investor_profile", DEFAULT_INVESTOR_PROFILE), + "fee_rate": st.session_state.get("fee_rate", 0.00015), + "target_return_pct": st.session_state.get("target_return_pct", 20.0), + "selected_model": st.session_state.get("selected_model", ""), + } + with open(_local("settings"), "w", encoding="utf-8") as f: + json.dump(payload, f, ensure_ascii=False, indent=2) + _hf_ul("settings") + +# ── 설정 최초 로드 +if "investor_profile" not in st.session_state: + _hf_dl("settings") + try: + with open(_local("settings"), "r", encoding="utf-8") as _sf: + _sdata = json.load(_sf) + st.session_state.investor_profile = _sdata.get("investor_profile", DEFAULT_INVESTOR_PROFILE) + # fee_rate / target_return_pct 는 이미 위에서 초기화했을 수 있으므로 덮어쓰지 않고 병합 + if "fee_rate" not in st.session_state: + st.session_state.fee_rate = _sdata.get("fee_rate", 0.00015) + if "target_return_pct" not in st.session_state: + st.session_state.target_return_pct = _sdata.get("target_return_pct", 20.0) + except Exception: + st.session_state.investor_profile = dict(DEFAULT_INVESTOR_PROFILE) + +if "portfolio_history" not in st.session_state: + _hf_dl("history") + try: + with open(_local("history"), "r", encoding="utf-8") as _hf: + _hdata = json.load(_hf) + st.session_state.portfolio_history = _hdata.get("portfolio_snapshots", []) + st.session_state.report_history = _hdata.get("report_history", {}) + except: + st.session_state.portfolio_history = [] + st.session_state.report_history = {} + +def save_history(): + def _s(o): + if hasattr(o, "item"): return o.item() + raise TypeError + payload = { + "portfolio_snapshots": st.session_state.portfolio_history, + "report_history": st.session_state.report_history, + } + with open(_local("history"), "w", encoding="utf-8") as f: + json.dump(payload, f, ensure_ascii=False, indent=2, default=_s) + _hf_ul("history") + +# ============================================================ +# ★ 히스토리: 로드 / 저장 / 스냅샷 / 리포트 기록 +# ============================================================ +if "portfolio_history" not in st.session_state: + _hf_dl(HISTORY_FILE) + try: + with open(HISTORY_FILE, "r", encoding="utf-8") as _hf: + _hdata = json.load(_hf) + st.session_state.portfolio_history = _hdata.get("portfolio_snapshots", []) + st.session_state.report_history = _hdata.get("report_history", {}) + except: + st.session_state.portfolio_history = [] + st.session_state.report_history = {} + +def save_history(): + def _s(o): + if hasattr(o, "item"): return o.item() + raise TypeError + payload = { + "portfolio_snapshots": st.session_state.portfolio_history, + "report_history": st.session_state.report_history, + } + with open(_local("history"), "w", encoding="utf-8") as f: + json.dump(payload, f, ensure_ascii=False, indent=2, default=_s) + _hf_ul("history") + +def _take_portfolio_snapshot(prices, rate): + """오늘 날짜 스냅샷이 없으면 포트폴리오 수익률 기록 (하루 1회).""" + today = datetime.now().strftime("%Y-%m-%d") + history = st.session_state.portfolio_history + if history and history[-1].get("date") == today: + return + if st.session_state.df.empty: + return + total_cost = total_val = 0.0 + snapshots = [] + for _, row in st.session_state.df.iterrows(): + t = row["티커"]; ap = float(row["평단가"]); qty = float(row["수량"]) + ck = prices.get(t, 0) * rate + if ck <= 0: ck = ap + pct = (ck / ap - 1) * 100 if ap > 0 else 0 + total_cost += ap * qty; total_val += ck * qty + snapshots.append({"ticker": t, "pct": round(pct, 2)}) + port_pct = (total_val / total_cost - 1) * 100 if total_cost > 0 else 0 + history.append({ + "date": today, + "total_cost": round(total_cost), + "total_val": round(total_val), + "pct": round(port_pct, 2), + "snapshots": snapshots, + }) + st.session_state.portfolio_history = history[-180:] + save_history() + +def _record_report_history(key: str, report: dict): + """AI 리포트를 key별로 날짜 순으로 최대 10개 보관.""" + if not report or not isinstance(report, dict): return + rh = st.session_state.report_history + today = datetime.now().strftime("%Y-%m-%d") + if key not in rh: + rh[key] = [] + if rh[key] and rh[key][-1].get("date") == today: + rh[key][-1]["report"] = report + else: + rh[key].append({"date": today, "report": report}) + rh[key] = rh[key][-10:] + save_history() + +# ============================================================ +# ★ 히스토리 렌더링 함수 +# ============================================================ +def render_portfolio_history_chart(): + """포트폴리오 수익률 타임라인 차트.""" + history = st.session_state.get("portfolio_history", []) + if len(history) < 2: + st.markdown( + '
' + '📈 수익률 타임라인은 이틀 이상 기록이 쌓이면 표시됩니다.
', + unsafe_allow_html=True, + ) + return + df_h = pd.DataFrame(history) + df_h["date"] = pd.to_datetime(df_h["date"]) + latest = df_h.iloc[-1]; first = df_h.iloc[0] + delta = latest["pct"] - first["pct"] + delta_color = "#AAAAAA" if delta >= 0 else "#9ABBE0" + st.markdown( + f'
' + f'📈 포트폴리오 수익률 타임라인' + f'' + f'누적 변화 {delta:+.2f}%p
', + unsafe_allow_html=True, + ) + fill_color = "rgba(170,170,170,0.07)" if latest["pct"] >= 0 else "rgba(154,187,224,0.07)" + line_color = "#AAAAAA" if latest["pct"] >= 0 else "#9ABBE0" + fig = go.Figure() + fig.add_trace(go.Scatter( + x=df_h["date"], y=df_h["pct"], mode="lines+markers", + line=dict(color=line_color, width=2), marker=dict(size=5, color=line_color), + fill="tozeroy", fillcolor=fill_color, + hovertemplate="%{x|%Y-%m-%d}
수익률 %{y:.2f}%", + )) + fig.add_hline(y=0, line_dash="dot", line_color="rgba(255,255,255,0.12)", line_width=1) + fig.update_layout( + height=200, margin=dict(l=0, r=0, t=0, b=0), + paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", + xaxis=dict(showgrid=False, color="#444444", tickfont=dict(size=10)), + yaxis=dict(showgrid=True, gridcolor="rgba(255,255,255,0.04)", color="#444444", + tickfont=dict(size=10), ticksuffix="%"), + hovermode="x unified", + ) + st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False}) + # 최근 7일 테이블 + recent = df_h.tail(7).iloc[::-1] + rows_html = "" + for _, r in recent.iterrows(): + pc = "#AAAAAA" if r["pct"] >= 0 else "#9ABBE0" + rows_html += ( + f'
' + f'{r["date"].strftime("%m/%d")}' + f'{int(r["total_val"]):,}원' + f'{r["pct"]:+.2f}%' + f'
' + ) + st.markdown( + f'
' + f'
날짜평가액수익률
' + f'{rows_html}
', + unsafe_allow_html=True, + ) + with st.expander("📊 종목별 수익률 추이", expanded=False): + all_tickers = sorted(set(s["ticker"] for snap in history for s in snap.get("snapshots", []))) + if not all_tickers: return + fig2 = go.Figure() + palette = ["#D8D8D8","#9ABBE0","#AAAAAA","#888888","#C9A84C","#E0E0E0","#7AABDA"] + for i, tk in enumerate(all_tickers[:7]): + dates_tk = []; pcts_tk = [] + for snap in history: + for s in snap.get("snapshots", []): + if s["ticker"] == tk: + dates_tk.append(snap["date"]); pcts_tk.append(s["pct"]); break + if len(dates_tk) < 2: continue + fig2.add_trace(go.Scatter( + x=pd.to_datetime(dates_tk), y=pcts_tk, mode="lines+markers", name=tk, + line=dict(color=palette[i % len(palette)], width=1.5), marker=dict(size=4), + hovertemplate=f"{tk}: %{{y:.2f}}%", + )) + fig2.add_hline(y=0, line_dash="dot", line_color="rgba(255,255,255,0.10)", line_width=1) + fig2.update_layout( + height=220, margin=dict(l=0, r=0, t=10, b=0), + paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", + xaxis=dict(showgrid=False, color="#444444", tickfont=dict(size=10)), + yaxis=dict(showgrid=True, gridcolor="rgba(255,255,255,0.04)", color="#444444", + tickfont=dict(size=10), ticksuffix="%"), + legend=dict(font=dict(size=10, color="#888888"), bgcolor="rgba(0,0,0,0)"), + hovermode="x unified", + ) + st.plotly_chart(fig2, use_container_width=True, config={"displayModeBar": False}) + + +def render_report_history_diff(key: str, current_report: dict): + """AI 리포트 변화 비교 뷰 — render_owned_report / render_scan_report 직후에 호출.""" + rh = st.session_state.get("report_history", {}).get(key, []) + if len(rh) < 2: return + with st.expander("📋 이전 AI 분석과 비교", expanded=False): + sorted_rh = sorted(rh, key=lambda x: x["date"], reverse=True) + dates = [r["date"] for r in sorted_rh] + today_date = dates[0] + sel_date = st.selectbox("비교할 날짜 선택", dates[1:], key=f"rh_sel_{key}") + prev_report = next((r["report"] for r in sorted_rh if r["date"] == sel_date), None) + if not prev_report: return + COMPARE_FIELDS = [ + ("recommendation_stars", "별점"), + ("action_type", "판단"), + ("confidence_score", "신뢰도"), + ("summary", "한줄 요약"), + ] + changed = []; unchanged = [] + for field, label in COMPARE_FIELDS: + cur_val = current_report.get(field, "-"); prev_val = prev_report.get(field, "-") + if str(cur_val) != str(prev_val): changed.append((field, label, prev_val, cur_val)) + else: unchanged.append((label, cur_val)) + if changed: + st.markdown('
🔄 변경된 항목
', unsafe_allow_html=True) + for field, label, prev_val, cur_val in changed: + def _act_color(v): + v = str(v) + if "매수" in v or "추가" in v: return "#E0E0E0" + if "익절" in v: return "#9ABBE0" + if "손절" in v: return "#E05C5C" + return "#888888" + prev_c = _act_color(prev_val) if field == "action_type" else "#888888" + cur_c = _act_color(cur_val) if field == "action_type" else "#EBEBEB" + prev_str = str(prev_val)[:80] + ("…" if len(str(prev_val)) > 80 else "") + cur_str = str(cur_val)[:80] + ("…" if len(str(cur_val)) > 80 else "") + st.markdown( + f'
' + f'
{label}
' + f'
' + f'
{sel_date} (이전)
' + f'
{prev_str}
' + f'
' + f'
{today_date} (최신)
' + f'
{cur_str}
' + f'
', + unsafe_allow_html=True, + ) + else: + st.markdown('
' + '주요 항목 변경 없음 (판단·별점·신뢰도·요약 동일)
', unsafe_allow_html=True) + if unchanged: + with st.expander("변경 없는 항목", expanded=False): + for label, val in unchanged: + st.markdown( + f'
' + f'{label}' + f'{str(val)[:80]}
', + unsafe_allow_html=True, + ) + +# ============================================================ +# AI 프롬프트 +# ============================================================ +# ============================================================ +# 투자자 프로필 (동적 — 시스템 설정에서 사용자가 직접 지정) +# ============================================================ + +# ============================================================ +# AI 프롬프트 +# ============================================================ + +def get_investor_profile_str() -> str: + """session_state의 investor_profile 설정을 읽어 AI 프롬프트용 문자열 반환.""" + prof = st.session_state.get("investor_profile", DEFAULT_INVESTOR_PROFILE) + style = prof.get("style", "중장기 성장주") + risk = prof.get("risk_level", "중간~높음") + extra = prof.get("extra_notes", "").strip() + + sm = _PROFILE_STYLE_MAP.get(style, _PROFILE_STYLE_MAP["중장기 성장주"]) + + lines = [ + "[투자자 프로필 - 반드시 이 기준으로 분석]", + f"- 투자 성향: {sm['desc']}", + f"- 선호 종목: {sm['preferred']}", + f"- 리스크 허용도: {risk} — {sm['risk_hint']}", + f"- {sm['moat_hint']}", + ] + if extra: + lines.append(f"- 추가 지침: {extra}") + return "\n".join(lines) + +def get_scan_prompt(target, tid="", owned=None, news=None, portfolio_context=""): + owned_s = ", ".join(owned) if owned else "없음" + date_s = datetime.now().strftime("%Y년 %m월 %d일") + news_s = "" + if news: news_s = "\n[최근 뉴스 - 분석에 반드시 반영]\n" + "\n".join(news) + port_s = f"\n{portfolio_context}" if portfolio_context else "" + return f"""[중장기 성장주 분석 전문가 - {date_s} / ID:{tid}_{random.randint(100,999)}] +{get_investor_profile_str()} +[분석 목적] +이 투자자의 현재 포트폴리오 상황과 기보유 종목을 먼저 파악한 뒤, +신규 종목이 이 포트폴리오에 편입할 가치가 있는지를 '이 투자자의 입장'에서 판단한다. +{port_s} +[반드시 지킬 규칙] +1. 금액은 반드시 원화(원)만. 달러 기호 $ 절대 금지. +2. 제공된 실제 숫자만 사용. 없는 숫자 추측 금지. +3. 중학생도 이해할 수 있는 쉬운 말로 작성. +4. 각 항목마다 근거 데이터 1개 이상 명시. +5. 순수 JSON만 출력. 마크다운 기호 금지. +6. 정량(숫자) 근거와 정성(판단) 근거를 반드시 분리해서 제시. +7. 포트폴리오 맥락을 반드시 반영 - 기보유 종목과의 섹터 중복, 리스크 분산 효과 등 포트폴리오에 주는 영향 언급. +8. entry_zones 가격 산출 시 반드시 제공된 MA50/MA200/피보나치 레벨/ROIC/FCF Yield 실수치를 근거로 사용. 해자(기술적 경쟁 우위) 강도에 따라 가격 허용 범위를 조정할 것 - 해자 강=현재가 ±10% 이내 1차 매수 가능, 해자 보통=피보나치 50% 이하, 해자 약/훼손=피보나치 61.8% 이하 또는 MA200 근방. +{news_s} +[분석 대상 종목 데이터] +{target} +[이미 보유 중인 종목 - 중복 추천 금지] {owned_s} +[출력 JSON 형식] +{{ + "recommendation_stars": "★★★★☆", + "summary": "한 줄 요약 - 반드시 '내 포트폴리오에' 편입 여부로 결론", + "action_type": "매수/관망/제외 중 하나", + "confidence_score": 0, + "confidence_reason": "신뢰도 근거 - 포트폴리오 맥락 포함", + "portfolio_fit": {{ + "sector_overlap": "기보유 종목과의 섹터/테마 중복 여부", + "risk_diversification": "포트폴리오 리스크 분산에 기여하는가", + "current_portfolio_signal": "현재 포트폴리오 전체 수익/손실 상황 감안 시 신규 진입 적절한가" + }}, + "growth_moat_quantitative": "정량 근거 (2~3문장)", + "growth_moat_qualitative": "정성 근거 (2~3문장, 성장주/턴어라운드 구분 명시)", + "timing_entry_analysis": "중장기 진입 타이밍 분석 (2~3문장) - 현재 내 포트폴리오 상황 감안", + "entry_zones": {{ + "basis": "가격대 산출 근거 - 아래 4가지를 실데이터 기반 복합 판단: ① 기술적(MA50/MA200/피보나치 레벨) ② 펀더멘털(PSR·PER 역산) ③ 해자 강도(강할수록 현재가 근접 매수 허용) ④ ROIC/FCF Yield(높을수록 멀티플 할증 정당화)", + "first_buy": "1차 분할매수 가격대 (원화) - MA50 또는 피보나치 38.2~50% 레벨 기반. 해자 강도 반영. 제공된 실수치로 산출", + "second_buy": "2차 추가매수 가격대 (원화) - MA200 또는 피보나치 61.8% 레벨 기반. 해자 유효 확인 조건부. 제공된 실수치로 산출", + "stop_thesis": "성장 스토리 붕괴 조�� - 단순 주가 하락 아님. 해자 훼손 신호(매출성장 급감·경쟁 심화·경영진 변화) 또는 MA200 이탈 + 펀더멘털 악화 동시 발생" + }}, + "valuation_growth_fit": "성장률 대비 밸류에이션 판단 (2~3문장)", + "tech_risk_hedge": "기술주 집중 리스크 및 헤지 조언 - 내 기존 포트폴리오 대비 (2~3문장)", + "catalyst": "지금 투자해야 할 구체적 촉매", + "rebalancing_recommendations": [ + {{"ticker": "티커", "name": "기업명", "reason": "내 포트폴리오 리스크 상쇄 효과"}} + ], + "portfolio_outlook": {{ + "pct_basis": "수익률 산출 근거 - 반드시 제공된 베타·애널리스트 업사이드·PER·매출성장률 실수치를 기반으로 계산. 임의 숫자 절대 금지", + "optimistic_pct": "낙관 수익률% - 베타×시장 상승폭 + 애널리스트 고목표가 업사이드 기반으로 산출", + "optimistic_desc": "이 종목 고유의 낙관 시나리오 - 구체적 촉매·실적·이벤트 기반 2문장", + "base_pct": "기본 수익률% - 애널리스트 컨센서스 평균 목표가 업사이드 기반으로 산출", + "base_desc": "이 종목 고유의 기본 시나리오 - 현재 컨센서스 기반 2문장", + "pessimistic_pct": "비관 수익률% - 베타×시장 하락폭 또는 저목표가 기반으로 산출 (반드시 음수)", + "pessimistic_desc": "이 종목 고유의 비관 시나리오 - 구체적 리스크 실현 조건 2문장", + "beta_note": "이 종목 베타 기반 변동폭 해석 1문장", + "upside_note": "이 종목 애널리스트 컨센서스 업사이드 해석 1문장", + "valuation_note": "이 종목 현재 밸류에이션(PER·성장률) 수준 평가 1문장", + "key_risk": "이 종목 수익률 실현을 막을 핵심 리스크 1가지" + }} +}}""" + +def get_owned_prompt(target, tid="", news=None, portfolio_context=""): + date_s = datetime.now().strftime("%Y년 %m월 %d일") + news_s = "" + if news: news_s = "\n[최근 뉴스 - 해자 유효성 판단에 반영]\n" + "\n".join(news) + port_s = f"\n{portfolio_context}" if portfolio_context else "" + return f"""[중장기 성장주 보유 진단 전문가 - {date_s} / ID:{tid}_{random.randint(100,999)}] +{get_investor_profile_str()} +[분석 목적] +이미 보유 중인 종목에 대해 '이 투자자의 전체 포트폴리오 상황'을 먼저 파악한 뒤, +지금 이 종목을 계속 들고 가야 하는지, 추가로 사야 하는지, 팔아야 하는지를 +투자자의 현실 수익/손실과 포트폴리오 맥락 위에서 판단한다. +{port_s} +[반드시 지킬 규칙] +1. 금액은 반드시 원화(원)만. 달러 기호 $ 절대 금지. +2. 단순 주가 하락은 손절 이유가 아님. 성장 스토리 붕괴 여부로 위주로 판단. (다른 리스크 또는 하락의 근거가 있을 경우는 제외) +3. 추가매수/손절 판단 시 포트폴리오 전체 손익과 리스크 집중도를 반드시 반영. +4. 순수 JSON만 출력. 마크다운 기호 금지. +5. additional_buy_analysis의 suggested_price 산출 시 제공된 MA50/MA200/피보나치 레벨 실수치 기반으로 계산. 해자(thesis_validity verdict) 판단과 연동 - 해자 유효=피보나치 38.2~50%, 해자 점검필요=피보나치 50~61.8%, 해자 훼손=MA200 근방 또는 추가매수 비권고. +{news_s} +[분석 대상 종목 데이터 (이 투자자의 실제 보유 상황)] +{target} +[출력 JSON 형식] +{{ + "recommendation_stars": "★★★★☆", + "summary": "한 줄 요약 - 반드시 '내 포트폴리오 전체 맥락에서' 이 종목의 현재 위치", + "action_type": "보유/추가매수/익절/손절 중 하나", + "confidence_score": 0, + "confidence_reason": "신뢰도 근거 - 포트폴리오 맥락 포함", + "portfolio_context_judgment": "포트폴리오 전체 손익 및 구성 감안 시 이 종목의 현재 역할과 판단 (3~4문장)", + "thesis_validity": {{ + "verdict": "유효/훼손/점검필요 중 하나", + "original_thesis": "매수 당시 근거 요약 - [매수 당시 근거] 항목에 내용이 있으면 그것을 기반으로 요약. '미기록'이면 반드시 '매수 근거 미기록 - 현재 재무 데이터만으로 판단'이라고 명시하고 창작 금지", + "quantitative_check": "정량 점검: 제공된 실제 수치(매출성장·이익률·PER 등) 변화 기반 (2~3문장). 없는 수치 추측 금지", + "qualitative_check": "정성 점검: 경쟁구도·경영진·해자 변화 (2~3문장) - 뉴스 컨텍스트가 있으면 반드시 반영", + "current_status": "종합 판정 요약 (2문장)" + }}, + "action_analysis": "현재 액션 판단 (3문장) - 포트폴리오 전체 상황을 반드시 반영", + "additional_buy_analysis": {{ + "possible": true, + "condition": "추가매수 가능 조건 - 해자 유효성 + 포트폴리오 리스크 수준 포함", + "forbidden_condition": "추가매수 금지 조건 - 해자 훼손 신호 또는 포트폴리오 전체 손실/집중도 과도 시", + "suggested_price": "추가매수 적정 가격대 (원화) - MA50/MA200/피보나치 61.8% 레벨 중 해자 강도 감안해 산출. 제공된 실수치 기반", + "price_basis": "가격 산출 근거 - 기술적 지지선(MA/피보나치) + 해자 강도 + ROIC/FCF 수준을 복합 반영해 1~2문장으로 설명" + }}, + "target_remaining": {{ + "target_price": "목표가 (원화)", + "upside_pct": "현재가 대비 상승 여력 (%)", + "exit_strategy": "목표가 도달 시 매도 전략 - 포트폴리오 리밸런싱 관점 포함", + "target_gap_reason": "AI 목표가와 애널리스트 컨센서스 목표가가 차이나는 이유 - 이 종목의 성장 기대치, 밸류에이션 관점, 리스크 인식 차이를 구체적으로 2~3문장. 비슷하면 왜 일치하는지 설명" + }} +}}""" + +def get_portfolio_quant_metrics(df, prices, rate): + """ + 포트폴리오 정량 지표를 실데이터로 직접 계산. + - 가중평균 베타, 애널리스트 컨센서스 업사이드, MA 위치, 밸류에이션 + Returns: dict + """ + import numpy as np + + total_val = 0.0 + rows_data = [] + + for _, row in df.iterrows(): + t = row['티커'] + ap = float(row['평단가']) + qty = float(row['수량']) + cp = prices.get(t, 0) * rate + if cp <= 0: cp = ap + val = cp * qty + total_val += val + rows_data.append({"t": t, "ap": ap, "cp": cp, "qty": qty, "val": val}) + + if total_val <= 0: + return {} + + metrics = { + "tickers": [], "weighted_beta": 0.0, + "consensus_upside_pct": None, "ma_status": [], + "weighted_fwd_pe": None, "weighted_rev_growth": None, + "per_stock": [], "spy_6m": None, "qqq_6m": None, + } + + w_beta = 0.0 + w_pe = 0.0; w_pe_total = 0.0 + w_gr = 0.0; w_gr_total = 0.0 + upside_vals = [] + per_stock = [] + + # S&P500 / QQQ 최근 6개월 수익률 (시장 기준점) + try: + spy_hist = yf.Ticker("SPY").history(period="6mo") + qqq_hist = yf.Ticker("QQQ").history(period="6mo") + if len(spy_hist) > 5: + metrics["spy_6m"] = round((spy_hist['Close'].iloc[-1] / spy_hist['Close'].iloc[0] - 1) * 100, 1) + if len(qqq_hist) > 5: + metrics["qqq_6m"] = round((qqq_hist['Close'].iloc[-1] / qqq_hist['Close'].iloc[0] - 1) * 100, 1) + except: pass + + for rd in rows_data: + t = rd["t"]; w = rd["val"] / total_val + try: + info = yf.Ticker(t).info + beta = info.get("beta", 1.0) or 1.0 + fwd_pe = info.get("forwardPE") + rev_gr = info.get("revenueGrowth") + cp_usd = info.get("currentPrice") or info.get("previousClose", 0) + ma50 = info.get("fiftyDayAverage", 0) + ma200 = info.get("twoHundredDayAverage", 0) + target = info.get("targetMeanPrice", 0) + rec = info.get("recommendationKey", "") + n_anal = info.get("numberOfAnalystOpinions", 0) + earn_gr = info.get("earningsGrowth") + + w_beta += beta * w + + if fwd_pe and fwd_pe > 0 and fwd_pe < 500: + w_pe += fwd_pe * w; w_pe_total += w + if rev_gr and isinstance(rev_gr, float): + w_gr += rev_gr * w; w_gr_total += w + + # 애널리스트 업사이드 + upside = None + if target and target > 0 and cp_usd and cp_usd > 0: + upside = round((target / cp_usd - 1) * 100, 1) + upside_vals.append((upside, w)) + + # MA 위치 + ma_pos = "N/A" + if cp_usd > 0 and ma50 > 0 and ma200 > 0: + if cp_usd > ma50 > ma200: + ma_pos = "MA50↑MA200↑" + elif cp_usd > ma50: + ma_pos = "MA50↑" + elif cp_usd < ma200: + ma_pos = "MA200↓" + else: + ma_pos = "MA50↓" + + per_stock.append({ + "ticker": t, + "weight_pct": round(w * 100, 1), + "beta": round(beta, 2), + "upside_pct": upside, + "ma_position": ma_pos, + "fwd_pe": round(fwd_pe, 1) if fwd_pe and fwd_pe > 0 else None, + "rev_growth_pct": round(rev_gr * 100, 1) if isinstance(rev_gr, float) else None, + "earn_growth_pct": round(earn_gr * 100, 1) if isinstance(earn_gr, float) else None, + "analyst_rec": rec, + "analyst_count": n_anal, + }) + except: + per_stock.append({"ticker": t, "weight_pct": round(w * 100, 1)}) + + metrics["weighted_beta"] = round(w_beta, 2) + metrics["per_stock"] = per_stock + metrics["tickers"] = [rd["t"] for rd in rows_data] + + if upside_vals: + # 비중 가�� 평균 업사이드 + total_w = sum(uw for _, uw in upside_vals) + metrics["consensus_upside_pct"] = round(sum(u * w for u, w in upside_vals) / total_w, 1) if total_w > 0 else None + + if w_pe_total > 0: + metrics["weighted_fwd_pe"] = round(w_pe / w_pe_total, 1) + if w_gr_total > 0: + metrics["weighted_rev_growth"] = round((w_gr / w_gr_total) * 100, 1) + + return metrics + + +def get_portfolio_prompt(target, owned=None, sector_summary=None, beta_info=None, quant_metrics=None): + owned_s = ", ".join(owned) if owned else "없음" + date_s = datetime.now().strftime("%Y년 %m월 %d일") + sector_s = json.dumps(sector_summary, ensure_ascii=False) if sector_summary else "{}" + beta_s = json.dumps(beta_info, ensure_ascii=False) if beta_info else "{}" + + # 실데이터 정량 지표 섹션 구성 + quant_s = "" + if quant_metrics and isinstance(quant_metrics, dict): + qm = quant_metrics + lines = [] + if qm.get("weighted_beta"): + lines.append(f"- 포트폴리오 가중평균 베타: {qm['weighted_beta']} (시장 대비 변동성 배수)") + if qm.get("consensus_upside_pct") is not None: + lines.append(f"- 애널리스트 컨센서스 가중평균 업사이드: {qm['consensus_upside_pct']:+.1f}%") + if qm.get("weighted_fwd_pe"): + lines.append(f"- 포트폴리오 가중평균 Forward PER: {qm['weighted_fwd_pe']:.1f}x") + if qm.get("weighted_rev_growth") is not None: + lines.append(f"- 포트폴리오 가중평균 매출성장률(YoY): {qm['weighted_rev_growth']:+.1f}%") + if qm.get("spy_6m") is not None: + lines.append(f"- S&P500 최근 6개월 실제 수익률: {qm['spy_6m']:+.1f}%") + if qm.get("qqq_6m") is not None: + lines.append(f"- QQQ(나스닥100) 최근 6개월 실제 수익률: {qm['qqq_6m']:+.1f}%") + # 종목별 세부 + per_s = [] + for ps in qm.get("per_stock", []): + parts = [ps.get("ticker","")] + if ps.get("weight_pct") is not None: parts.append(f"비중{ps['weight_pct']}%") + if ps.get("upside_pct") is not None: parts.append(f"업사이드{ps['upside_pct']:+.1f}%") + if ps.get("ma_position"): parts.append(f"MA위치:{ps['ma_position']}") + if ps.get("fwd_pe"): parts.append(f"FwdPE:{ps['fwd_pe']}") + if ps.get("rev_growth_pct") is not None: parts.append(f"매출성장:{ps['rev_growth_pct']:+.1f}%") + if ps.get("analyst_rec"): parts.append(f"애널:{ps['analyst_rec']}({ps.get('analyst_count',0)}명)") + per_s.append(" - " + " / ".join(parts)) + if per_s: + lines.append("- 종목별 실데이터:") + lines.extend(per_s) + quant_s = "\n[포트폴리오 실데이터 정량 지표 - 직접 계산값, 환각 금지]\n" + "\n".join(lines) + "\n" + + return f"""[중장기 성장주 포트폴리오 리스크 전문가 - {date_s}] +{get_investor_profile_str()} +[분석 목적] 기술주 중심 성장주 포트폴리오의 전체 리스크를 진단한다. +[반드시 지킬 규칙] +1. 금액은 반드시 원화(원)만. 달러 기호 $ 절대 금지. +2. 종목 간 관계, 섹터 분포, 상관관계, 리스크 완화 분석에 집중. +3. 순수 JSON만 출력. 마크다운 기호 금지. +4. portfolio_outlook의 수익률 숫자는 반드시 아래 실데이터(베타·업사이드·밸류에이션)를 근거로 산출할 것. 임의 숫자 금지. +[포트폴리오 데이터] +{target} +[섹터 분포] {sector_s} +[종목별 베타] {beta_s} +[보유 종목 목록] {owned_s} +{quant_s} +[출력 JSON 형식] +{{ + "recommendation_stars": "★★★★☆", + "summary": "한 줄 요약", + "confidence_score": 0, + "confidence_reason": "신뢰도 근거", + "correlation_risk": {{ + "risk_level": "낮음/보통/높음/매우높음 중 하나", + "risk_groups": ["같이 빠질 위험 있는 종목 그룹"], + "worst_scenario": "최악의 동시 하락 시나리오" + }}, + "rebalancing_priority": {{ + "sell_first": ["매도 우선 종목 및 이유"], + "buy_next": ["매수 추천 종목(티커) 및 이유"], + "hedge_suggestion": "리스크 헤지를 위한 다른 종목 추천" + }}, + "portfolio_outlook": {{ + "pct_basis": "수익률 산출 근거 - 반드시 제공된 포트폴리오 가중평균 베타·컨센서스 업사이드·Forward PER·매출성장률 실수치 기반으로 계산. 임의 숫자 절대 금지", + "optimistic_pct": "낙관 수익률% - 가중평균 베타×시장 상승 시나리오 + 컨센서스 고업사이드 기반", + "optimistic_desc": "포트폴리오 전체 관점의 낙관 시나리오 - 보유 종목 성장 가속, 섹터 테마 수혜 등 구체적 조건 2문장", + "base_pct": "기본 수익률% - 포트폴리오 가중평균 컨센서스 업사이드 기반", + "base_desc": "포트폴리오 전체 관점의 기��� 시나리오 - 현재 컨센서스 기반 2문장", + "pessimistic_pct": "비관 수익률% - 가중평균 베타×시장 하락 시나리오 기반 (반드시 음수)", + "pessimistic_desc": "포트폴리오 전체 관점의 비관 시나리오 - 섹터 집중 리스크, 매크로 악화 등 구체적 조건 2문장", + "beta_note": "포트폴리오 가중평균 베타 기반 변동폭 해석 1문장", + "upside_note": "포트폴리오 애널리스트 컨센서스 업사이드 해석 1문장", + "valuation_note": "포트폴리오 전체 밸류에이션(PER·성장률) 수준 평가 1문장", + "key_risk": "포트폴리오 수익률 실현을 막을 핵심 리스크 1가지" + }}, + "concentration_warning": {{ + "tech_weight_pct": 0, + "quantitative_concentration": "정량 집중도 (2문장)", + "qualitative_concentration": "정성 집중도: 테마 중복 식별 (2~3문장)", + "growth_vs_turnaround": "성장주 vs 턴어라운드 비율 평가" + }}, + "rebalancing_recommendations": [ + {{"ticker": "티커", "name": "기업명", "reason": "포트폴리오 리스크 분산 효과"}} + ], + "risk_contribution": [ + {{"ticker": "티커", "name": "기업명", "contribution_pct": 0, "reason": "리스크 기여 원인 1문장", "level": "높음/보통/낮음 중 하나"}} + ], + "thesis_summary": [ + {{"ticker": "티커", "name": "기업명", "verdict": "유효/훼손/점검필요 중 하나", "one_line": "해자 상태 1문장 요약", "action": "보유/추가매수/익절/손절 중 하나"}} + ], + "health_scores": {{ + "concentration": {{"score": 0, "label": "집중도 점수 (0~100, 낮을수록 위험)", "comment": "한 줄 코멘트"}}, + "volatility": {{"score": 0, "label": "변동성 점수 (0~100, 낮을수록 위험)", "comment": "한 줄 코멘트"}}, + "thesis": {{"score": 0, "label": "해자 유효성 점수 (0~100)", "comment": "한 줄 코멘트"}}, + "return": {{"score": 0, "label": "수익률 모멘텀 점수 (0~100)", "comment": "한 줄 코멘트"}} + }} +}}""" + +# ============================================================ +# 포트폴리오 종합 진단 리포트 렌더러 +# ============================================================ +def render_portfolio_report(rpt): + if not rpt or not isinstance(rpt, dict): return + summary = rpt.get("summary", "") + conf_score = rpt.get("confidence_score", 50) + conf_reason = rpt.get("confidence_reason", "") + stars = rpt.get("recommendation_stars", "") + + safe_sum = re.sub(r'\*\*(.*?)\*\*', r'\1', str(summary).replace('\n',' ')) + stars_html = f'{stars}

' if stars else '' + st.markdown( + f'
' + f'포트폴리오 종합 진단

' + f'{stars_html}' + f'{safe_sum}
', + unsafe_allow_html=True + ) + render_confidence_bar(conf_score, conf_reason) + + # ── 헬스 스코어카드 (탭 위에 항상 표시) + health = rpt.get("health_scores", {}) + if isinstance(health, dict) and health: + score_items = [ + ("집중도", health.get("concentration", {}), "🗂"), + ("변동성", health.get("volatility", {}), "⚡"), + ("해자유효", health.get("thesis", {}), "🎯"), + ("수익모멘", health.get("return", {}), "📈"), + ] + cards_html = "" + for label, item, icon in score_items: + if not isinstance(item, dict): continue + sc = max(0, min(100, int(item.get("score", 50)))) + cmt = item.get("comment", "") + if sc >= 70: bar_c, txt_c = "#AAAAAA", "#AAAAAA" + elif sc >= 40: bar_c, txt_c = "#D8D8D8", "#D8D8D8" + else: bar_c, txt_c = "#E05C5C", "#E05C5C" + cards_html += ( + f'
' + f'
' + f'{icon} {label}' + f'{sc}' + f'
' + f'
' + f'
' + f'
{cmt}
' + f'
' + ) + st.markdown( + f'
{cards_html}
', + unsafe_allow_html=True + ) + + # ── 탭 4개 + tab_risk, tab_thesis, tab_rebal, tab_outlook = st.tabs([ + "🛡 리스크", "🎯 해자 현황", "🔄 리밸런싱", "📈 수익률 전망" + ]) + + # ─────────── 탭 1: 리스크 (동시 하락 위험 + 리스크 기여도 + 집중도) ─────────── + with tab_risk: + # 종목별 리스크 기여도 + rc_list = rpt.get("risk_contribution", []) + if rc_list and isinstance(rc_list, list): + st.markdown( + '
📊 종목별 리스크 기여도
', + unsafe_allow_html=True + ) + for rc in rc_list: + t_rc = rc.get("ticker",""); n_rc = rc.get("name","") + pct_rc = max(0, min(100, int(rc.get("contribution_pct", 0)))) + rsn_rc = rc.get("reason","") + lv_rc = rc.get("level","보통") + lv_c = {"높음":"#E05C5C","보통":"#D8D8D8","낮음":"#AAAAAA"}.get(lv_rc, "#D8D8D8") + st.markdown( + f'
' + f'
' + f'{n_rc} ' + f'{t_rc}' + f'{lv_rc} {pct_rc}%' + f'
' + f'
' + f'
' + f'
{rsn_rc}
' + f'
', + unsafe_allow_html=True + ) + + # 동시 하락 위험 + corr = rpt.get("correlation_risk", {}) + if isinstance(corr, dict): + risk_level = corr.get("risk_level", "보통") + risk_groups = corr.get("risk_groups", []) + worst = corr.get("worst_scenario", "") + risk_color = {"낮음":"#AAAAAA","보통":"#D8D8D8","높음":"#E0E0E0","매우높음":"#E05C5C"}.get(risk_level, "#D8D8D8") + groups_html = "".join([ + f'
⚠️ {g}
' + for g in risk_groups + ]) + safe_worst = re.sub(r'\*\*(.*?)\*\*', r'\1', str(worst)) + st.markdown( + f'
' + f'
' + f'
동시 하락 위험
' + f'위험도: {risk_level}' + f'
{groups_html}' + f'
' + f'최악 시나리오 · {safe_worst}
', + unsafe_allow_html=True + ) + + # 집중도 경고 + conc = rpt.get("concentration_warning", {}) + if isinstance(conc, dict): + tech_w = conc.get("tech_weight_pct", 0) + gvt = conc.get("growth_vs_turnaround", "") + qn_conc = conc.get("quantitative_concentration", "") + ql_conc = conc.get("qualitative_concentration", "") + tech_color = "#E0E0E0" if tech_w >= 70 else ("#D8D8D8" if tech_w >= 50 else "#AAAAAA") + conc_detail = "" + if qn_conc: + conc_detail += ( + f'
' + f'
📊 정량 집중도
' + f'
{qn_conc.replace(chr(10),"
")}
' + ) + if ql_conc: + conc_detail += ( + f'
' + f'
💡 정성 집중도
' + f'
{ql_conc.replace(chr(10),"
")}
' + ) + st.markdown( + f'
' + f'
집중도 경고
' + f'
' + f'
기술주 비중
' + f'
{tech_w}%
' + f'
' + f'
' + f'
' + f'{conc_detail}' + f'{"
성장주 vs 턴어라운드 · " + gvt + "
" if gvt else ""}' + f'
', + unsafe_allow_html=True + ) + + if not isinstance(corr, dict) and not isinstance(conc, dict) and not rc_list: + st.markdown('
데이터 없음
', unsafe_allow_html=True) + + # ─────────── 탭 2: 해자 현황 + 실적 발표 달력 ─────────── + with tab_thesis: + # 해자 유효성 요약 + ts_list = rpt.get("thesis_summary", []) + if ts_list and isinstance(ts_list, list): + verdict_cfg = { + "유효": ("#AAAAAA", "✅"), + "점검필요": ("#D8D8D8", "🔍"), + "훼손": ("#E05C5C", "❌"), + } + for ts in ts_list: + t_ts = ts.get("ticker",""); n_ts = ts.get("name","") + vd = ts.get("verdict",""); ol = ts.get("one_line","") + act = ts.get("action","보유") + v_col, v_ico = verdict_cfg.get(vd, ("#888888","•")) + act_col = {"추가매수":"#AAAAAA","익절":"#9ABBE0","손절":"#E05C5C","보유":"#444444"}.get(act,"#444444") + st.markdown( + f'
' + f'
' + f'{n_ts} ' + f'{t_ts}' + f'
' + f'{v_ico} {vd}' + f'{act}' + f'
' + f'
{ol}
' + f'
', + unsafe_allow_html=True + ) + + # 실적 발표 달력 + st.markdown( + '
📅 실적 발표 달력
', + unsafe_allow_html=True + ) + owned_tickers = st.session_state.df['티커'].tolist() if not st.session_state.df.empty else [] + if owned_tickers: + render_earnings_calendar(owned_tickers, label="보유 종목") + else: + st.markdown('
보유 종목 없음
', unsafe_allow_html=True) + + # ─────────── 탭 3: 리밸런싱 ─────────── + with tab_rebal: + rebal = rpt.get("rebalancing_priority", {}) + if isinstance(rebal, dict): + sell_list = rebal.get("sell_first", []) + buy_list = rebal.get("buy_next", []) + hedge_s = rebal.get("hedge_suggestion", "") + sell_html = "".join([ + f'
📤 {s}
' + for s in sell_list + ]) + buy_html = "".join([ + f'
📥 {b}
' + for b in buy_list + ]) + st.markdown( + f'
' + f'
리밸런싱 우선순위
' + f'
' + f'
먼저 매도
' + f'{sell_html if sell_html else "
해당 없음
"}
' + f'
추가 매수
' + f'{buy_html if buy_html else "
해당 없음
"}
' + f'{"
헤지 추천 · " + hedge_s + "
" if hedge_s else ""}' + f'
', + unsafe_allow_html=True + ) + + recs = rpt.get("rebalancing_recommendations") + if recs and isinstance(recs, list): + st.markdown( + '
↻ 리스크 분산 추천 종목
', + unsafe_allow_html=True + ) + for i, rec in enumerate(recs): + t = rec.get("ticker","N/A"); n = rec.get("name","Unknown"); r = rec.get("reason","") + c1, c2 = st.columns([0.75, 0.25], vertical_alignment="center") + with c1: + st.markdown( + f'
' + f'
{n} ' + f'{t}
' + f'
{r}
', + unsafe_allow_html=True + ) + with c2: + if st.button("스캔", key=f"port_rec_btn_{i}_{t}", use_container_width=True): + st.session_state.active_ticker = t + st.session_state.main_menu = "⌂ 홈 & 스캔" + st.session_state.p_diag_mode = False + st.session_state.pop('detail_ticker', None) + st.rerun() + + # ─────────── 탭 4: 수익률 전망 ─────────── + with tab_outlook: + outlook = rpt.get("portfolio_outlook", {}) + qm = rpt.get("_quant_metrics", {}) or {} + + # ── 실데이터 근거 패널 (직접 계산값) + if qm: + beta_val = qm.get("weighted_beta") + upside_val = qm.get("consensus_upside_pct") + pe_val = qm.get("weighted_fwd_pe") + gr_val = qm.get("weighted_rev_growth") + spy_val = qm.get("spy_6m") + qqq_val = qm.get("qqq_6m") + + evidence_cards = "" + + if beta_val is not None: + beta_c = "#E05C5C" if beta_val >= 1.5 else ("#D8D8D8" if beta_val >= 1.1 else "#AAAAAA") + # beta 기반 시장 ±10% 시 포트폴리오 예상 변동 + port_up = round(10 * beta_val, 1) + port_down = round(-10 * beta_val, 1) + evidence_cards += ( + f'
' + f'
⚡ 가중평균 베타
' + f'
{beta_val}
' + f'
시장 ±10% 시 포트폴리오
' + f'상승 +{port_up}% / 하락 {port_down}% 예상
' + f'
' + ) + + if upside_val is not None: + up_c = "#AAAAAA" if upside_val >= 10 else ("#D8D8D8" if upside_val >= 0 else "#E05C5C") + evidence_cards += ( + f'
' + f'
🎯 애널리스트 컨센서스 업사이드
' + f'
{upside_val:+.1f}%
' + f'
보유 종목 비중 가중 평균
애널리스트 목표주가 대비
' + f'
' + ) + + if pe_val is not None or gr_val is not None: + pe_str = f"Forward PER {pe_val:.1f}x" if pe_val else "" + gr_str = f"매출성장률 {gr_val:+.1f}%" if gr_val is not None else "" + peg_str = "" + if pe_val and gr_val and gr_val > 0: + peg = pe_val / gr_val + peg_c = "#E05C5C" if peg > 3 else ("#D8D8D8" if peg > 1.5 else "#AAAAAA") + peg_str = f'
PEG {peg:.1f} (PER÷성장률)' + evidence_cards += ( + f'
' + f'
📊 밸류에이션
' + f'
{pe_str}{"
" if pe_str and gr_str else ""}{gr_str}
' + f'
포트폴리오 가중평균{peg_str}
' + f'
' + ) + + if spy_val is not None or qqq_val is not None: + spy_c = "#AAAAAA" if (spy_val or 0) >= 0 else "#E05C5C" + qqq_c = "#AAAAAA" if (qqq_val or 0) >= 0 else "#E05C5C" + evidence_cards += ( + f'
' + f'
📉 시장 기준점 (최근 6개월)
' + f'
' + f'SPY {f"{spy_val:+.1f}%" if spy_val is not None else "N/A"}  ' + f'QQQ {f"{qqq_val:+.1f}%" if qqq_val is not None else "N/A"}' + f'
' + f'
내 포트폴리오와 비교 기준점
' + f'
' + ) + + if evidence_cards: + cols_count = evidence_cards.count('
📐 실데이터 근거
' + f'
{evidence_cards}
', + unsafe_allow_html=True + ) + + # 종목별 업사이드 바 + per_stock = qm.get("per_stock", []) + if per_stock: + rows_html = "" + for ps in sorted(per_stock, key=lambda x: x.get("upside_pct") or -999, reverse=True): + t_ps = ps.get("ticker", "") + up_ps = ps.get("upside_pct") + rec_ps = ps.get("analyst_rec", "") + cnt_ps = ps.get("analyst_count", 0) + ma_ps = ps.get("ma_position", "") + if up_ps is None: continue + bar_w = min(abs(up_ps), 100) + bar_c = "#AAAAAA" if up_ps >= 10 else ("#D8D8D8" if up_ps >= 0 else "#E05C5C") + rec_html = f'{rec_ps} ({cnt_ps}명)' if rec_ps else "" + ma_html = f'{ma_ps}' if ma_ps else "" + rows_html += ( + f'
' + f'
' + f'{t_ps}{rec_html}{ma_html}' + f'{up_ps:+.1f}%' + f'
' + f'
' + f'
' + f'
' + ) + if rows_html: + st.markdown( + f'
' + f'
🎯 종목별 애널리스트 업사이드
' + f'{rows_html}
', + unsafe_allow_html=True + ) + + # ── AI 해석 (실데이터 기반 시나리오) + if isinstance(outlook, dict) and any(outlook.get(k) for k in ["optimistic_pct","optimistic","base_pct","base","pessimistic_pct","pessimistic"]): + import re as _re + + def _bold_numbers(text): + return _re.sub( + r'([+\-]?\d[\d,]*\.?\d*\s*[%배원억만]+)', + r'\1', + str(text) + ) + + scenarios = { + "낙관": { + "pct": outlook.get("optimistic_pct") or outlook.get("optimistic", "-"), + "desc": outlook.get("optimistic_desc") or outlook.get("optimistic", ""), + "color": "#AAAAAA", "sel_border": "rgba(200,200,200,0.6)", + "border": "rgba(255,255,255,0.10)", "bg": "rgba(255,255,255,0.05)", "icon": "🟢", + }, + "기본": { + "pct": outlook.get("base_pct") or outlook.get("base", "-"), + "desc": outlook.get("base_desc") or outlook.get("base", ""), + "color": "#D8D8D8", "sel_border": "rgba(220,220,220,0.6)", + "border": "rgba(255,255,255,0.10)", "bg": "rgba(255,255,255,0.04)", "icon": "⚪", + }, + "비관": { + "pct": outlook.get("pessimistic_pct") or outlook.get("pessimistic", "-"), + "desc": outlook.get("pessimistic_desc") or outlook.get("pessimistic", ""), + "color": "#E05C5C", "sel_border": "rgba(200,60,60,0.8)", + "border": "rgba(200,60,60,0.25)", "bg": "rgba(200,60,60,0.05)", "icon": "🔴", + }, + } + + p_key = f"p_outlook_tab_{id(rpt)}" + if p_key not in st.session_state: + st.session_state[p_key] = "기본" + p_selected = st.session_state[p_key] + + st.markdown( + '
🤖 AI 시나리오 해석
', + unsafe_allow_html=True + ) + + cols = st.columns(3) + for label, s in scenarios.items(): + col = cols[list(scenarios.keys()).index(label)] + with col: + if st.button(f"{s['icon']} {label}\n\n{s['pct']}", key=f"pol_{label}_{id(rpt)}", use_container_width=True): + st.session_state[p_key] = label + st.rerun() + + sel = scenarios[p_selected] + if sel["desc"] and len(str(sel["desc"])) > 5: + st.markdown( + f'
' + f'{_bold_numbers(sel["desc"])}' + f'
', + unsafe_allow_html=True + ) + + notes = [ + ("⚡ 베타 기반", outlook.get("beta_note", "")), + ("🎯 컨센서스", outlook.get("upside_note", "")), + ("📊 밸류에이션", outlook.get("valuation_note", "")), + ] + notes_html = "".join([ + f'
' + f'{lbl}' + f'
{_bold_numbers(txt)}
' + for lbl, txt in notes if txt + ]) + key_risk = outlook.get("key_risk", "") + risk_html = ( + f'
' + f'⚠️ 핵심 리스크 {key_risk}
' + ) if key_risk else "" + if notes_html or risk_html: + st.markdown( + f'
' + f'{notes_html}{risk_html}' + f'
', + unsafe_allow_html=True + ) + else: + st.markdown('
재진단을 실행하면 실데이터 기반 전망이 표시됩니다
', unsafe_allow_html=True) + + +# ============================================================ +# UI 헬퍼 +# ============================================================ +def render_confidence_bar(score, reason): + try: score = int(score) + except: score = 50 + score = max(0, min(100, score)) + if score >= 75: color, label, emoji = "#AAAAAA", "높음", "🟢" + elif score >= 45: color, label, emoji = "#D8D8D8", "보통", "🟡" + else: color, label, emoji = "#E0E0E0", "낮음", "🔴" + st.markdown( + f'
' + f'
' + f'' + f'{emoji} AI 분석 신뢰도' + f'{score}점 · {label}' + f'
' + f'
' + f'
' + f'
{reason}
' + f'
', + unsafe_allow_html=True + ) + +def render_target_price_compare(ai_target_str, analyst_target_krw, current_price_krw, gap_reason=""): + if not analyst_target_krw or analyst_target_krw == 0: return + ai_prices = parse_target_prices(ai_target_str) + if not ai_prices: return + ai_price = ai_prices[0] + if ai_price == 0: return + diff_pct = abs(ai_price - analyst_target_krw) / analyst_target_krw * 100 + ai_upside = (ai_price / current_price_krw - 1) * 100 if current_price_krw > 0 else 0 + an_upside = (analyst_target_krw / current_price_krw - 1) * 100 if current_price_krw > 0 else 0 + + if diff_pct >= 30: + gap_icon = "⚠️" + gap_color = "rgba(255,200,100,0.08)" + gap_border= "rgba(255,200,100,0.25)" + gap_text_color = "#D8D8D8" + gap_label = f"두 목표가가 {diff_pct:.0f}% 차이납니다" + else: + gap_icon = "✅" + gap_color = "rgba(255,255,255,0.03)" + gap_border= "rgba(255,255,255,0.10)" + gap_text_color = "#888888" + gap_label = f"두 목표가가 비슷합니다 (차이 {diff_pct:.0f}%)" + + reason_html = "" + if gap_reason: + reason_html = ( + f'
' + f'{gap_reason}' + f'
' + ) + + st.markdown( + f'
' + f'
📊 목표가 비교
' + f'
' + f'
' + f'
AI 분석 목표가
' + f'
{ai_price:,}원
' + f'
=0 else "#9ABBE0"}; margin-top:4px;">{ai_upside:+.1f}%
' + f'
' + f'
' + f'
전문가 평균 목표가
' + f'
{analyst_target_krw:,}원
' + f'
=0 else "#9ABBE0"}; margin-top:4px;">{an_upside:+.1f}%
' + f'
' + f'
' + f'
' + f'{gap_icon} {gap_label}' + f'{reason_html}' + f'
' + f'
', + unsafe_allow_html=True + ) + +def render_52w_gauge(ticker, current_price_usd): + pos = calc_52w_position(ticker, current_price_usd) + try: + info = yf.Ticker(ticker).info + h52 = info.get('fiftyTwoWeekHigh', 0) + l52 = info.get('fiftyTwoWeekLow', 0) + rate = get_exchange_rate() + h_krw = int(h52 * rate); l_krw = int(l52 * rate) + except: + h_krw = l_krw = 0 + + if pos <= 30: bar_color = "#AAAAAA"; label = "저점 구간" + elif pos <= 70: bar_color = "#D8D8D8"; label = "중간 구간" + else: bar_color = "#E0E0E0"; label = "고점 구간" + + st.markdown( + f'
' + f'
' + f'52주 가격 위치' + f'{pos:.1f}% · {label}' + f'
' + f'
' + f'
' + f'
' + f'
' + f'52주 저점 {l_krw:,}원52주 고점 {h_krw:,}원' + f'
', + unsafe_allow_html=True + ) + +def render_dividend_info(ticker): + div = get_dividend_info(ticker) + if div["yield_pct"] <= 0: return + st.markdown( + f'
' + f'💰 배당 {div["yield_pct"]}%' + f'전 배당락일 {div["ex_date"]}' + f'
', + unsafe_allow_html=True + ) + +# ============================================================ +# ★ 개선된 render_stock_header - 배지 통합 +# ============================================================ +def render_stock_header(name, ticker, price, stars, mode_label, has_rich, extra_badges=None): + """ + extra_badges: list of (label, value, color) - 헤더 하단 한 줄에 배지로 통합 표시 + """ + badge = ( + '재무데이터 반영' + if has_rich else + '데이터 제한적' + ) + try: + rate = get_exchange_rate() + usd_val = price / rate if rate > 0 else 0 + usd_str = f"${usd_val:,.2f}" + except: + usd_str = "" + + show_usd = st.session_state.get('show_usd', False) + price_html = ( + f'' + f'{price:,}원' + f'{"" + usd_str + "" if show_usd and usd_str else ""}' + f'' + ) + + # 통합 배지 행 + badges_html = "" + if extra_badges: + badges_inner = "" + for label, value, color in extra_badges: + badges_inner += ( + f'{label} {value}' + ) + badges_html = f'
{badges_inner}
' + + st.markdown( + f'
' + f'
{mode_label}' + f'
{badge}
' + f'
' + f'{name}' + f'{ticker}
' + f'
' + f'{price_html}' + f'
{stars}
' + f'{badges_html}' + f'
', + unsafe_allow_html=True + ) + # USD 토글 (헤더 바로 아래 우측) + if usd_str: + _, usd_col = st.columns([0.82, 0.18]) + with usd_col: + toggle_label = "$ OFF" if show_usd else "$ ON" + if st.button(toggle_label, key=f"usd_toggle_{ticker}_{mode_label[:4]}", use_container_width=True): + st.session_state.show_usd = not show_usd + st.rerun() + +# ============================================================ +# ★ 개선된 render_owned_report - 탭 4개로 분리 +# ============================================================ +def render_owned_report(rpt, analyst_target_krw=0, current_price_krw=0): + if not rpt or not isinstance(rpt, dict): return + summary = rpt.get("summary", "") + action = rpt.get("action_type", "보유") + conf_score = rpt.get("confidence_score", 50) + conf_reason = rpt.get("confidence_reason", "") + + border_color = { + "보유": "rgba(255,255,255,0.09)", "추가매수": "#E0E0E0", + "익절": "#9ABBE0", "손절": "#E0E0E0", + }.get(action, "rgba(255,255,255,0.08)") + + safe_sum = re.sub(r'\*\*(.*?)\*\*', r'\1', str(summary).replace('\n',' ')) + st.markdown( + f'
' + f'보유 종목 진단 리포트

' + f'{safe_sum}
', + unsafe_allow_html=True + ) + render_confidence_bar(conf_score, conf_reason) + + # ── 탭 분리: 요약 / 해자 / 액션 / 목표가 + tab_sum, tab_thesis, tab_action, tab_target = st.tabs(["📋 요약", "🔍 해자", "⚡ 액션", "🎯 목표가"]) + + # ─────────── 탭 1: 요약 ─────────── + with tab_sum: + pcj = rpt.get("portfolio_context_judgment", "") + if pcj: + safe_pcj = re.sub(r'\*\*(.*?)\*\*', r'\1', str(pcj).replace('\n','
')) + st.markdown( + f'
' + f'
🎯 포트폴리오 맥락 판단
' + f'
{safe_pcj}
' + f'
', + unsafe_allow_html=True + ) + action_analysis = rpt.get("action_analysis", "") + if action_analysis: + safe = re.sub(r'\*\*(.*?)\*\*', r'\1', str(action_analysis).replace('\n','
')) + st.markdown( + f'
현재 액션 판단
' + f'
{safe}
', + unsafe_allow_html=True + ) + + # ─────────── 탭 2: 해자 ─────────── + with tab_thesis: + thesis = rpt.get("thesis_validity", {}) + if isinstance(thesis, dict): + verdict = thesis.get("verdict", "점검필요") + orig = thesis.get("original_thesis", "") + curr = thesis.get("current_status", "") + no_reason = (not orig or "미기록" in orig or "확인 불가" in orig) + + if no_reason: + st.markdown( + '
' + '
' + '매수 근거를 기록하면 해자 유효성을 정확히 판단해드릴 수 있어요.' + '
' + '
' + '💡 포트폴리오 목록에서 ⋯ 편집을 눌러 매수 근거를 추가하세요.' + '
', + unsafe_allow_html=True + ) + else: + verdict_color = {"유효": "#AAAAAA", "훼손": "#E0E0E0", "점검필요": "#D8D8D8"}.get(verdict, "#888888") + verdict_bg = {"유효": "rgba(255,255,255,0.06)", "훼손": "rgba(255,255,255,0.05)", "점검필요": "rgba(255,255,255,0.05)"}.get(verdict, "rgba(255,255,255,0.035)") + quant_chk = thesis.get("quantitative_check", "") + qual_chk = thesis.get("qualitative_check", "") + safe_curr = re.sub(r'\*\*(.*?)\*\*', r'\1', str(curr).replace('\n','
')) + safe_qn = re.sub(r'\*\*(.*?)\*\*', r'\1', str(quant_chk).replace('\n','
')) + safe_ql = re.sub(r'\*\*(.*?)\*\*', r'\1', str(qual_chk).replace('\n','
')) + + st.markdown( + f'
' + f'
' + f'매수 해자 유효성' + f'{verdict}' + f'
' + f'
' + f'
매수 당시 근거
' + f'
{orig}
', + unsafe_allow_html=True + ) + if safe_qn: + st.markdown( + f'
' + f'
📊 정량 점검
' + f'
{safe_qn}
', + unsafe_allow_html=True + ) + if safe_ql: + st.markdown( + f'
' + f'
💡 정성 점검
' + f'
{safe_ql}
', + unsafe_allow_html=True + ) + if safe_curr: + st.markdown( + f'
' + f'
⚖️ 종합 판정
' + f'
{safe_curr}
' + f'
', + unsafe_allow_html=True + ) + + # ─────────── 탭 3: 액션 ─────────── + with tab_action: + add_buy = rpt.get("additional_buy_analysis", {}) + if isinstance(add_buy, dict): + possible = add_buy.get("possible", False) + condition = add_buy.get("condition", "") + forbidden = add_buy.get("forbidden_condition", "") + sug_price = add_buy.get("suggested_price", "-") + poss_color = "#AAAAAA" if possible else "#E0E0E0" + poss_label = "추가매수 가능" if possible else "추가매수 주의" + st.markdown( + f'
' + f'
' + f'{poss_label}' + f'
' + f'
' + f'
' + f'
✅ 가능 조건
' + f'
{condition}
' + f'
' + f'
🚫 금지 조건
' + f'
{forbidden}
' + f'
' + f'
' + f'추가매수 적정가' + f'{sug_price}' + f'
', + unsafe_allow_html=True + ) + + # ─────────── 탭 4: 목표가 ─────────── + with tab_target: + target_rem = rpt.get("target_remaining", {}) + if isinstance(target_rem, dict): + tp = target_rem.get("target_price", "-") + upside = target_rem.get("upside_pct", "-") + exit_s = target_rem.get("exit_strategy", "-") + st.markdown( + f'
' + f'
' + f'
' + f'
목표가
' + f'
{tp}
' + f'
' + f'
' + f'
' + f'
상승 여력
' + f'
{upside}
' + f'
' + f'
' + f'
' + f'매도 전략' + f'{exit_s}
', + unsafe_allow_html=True + ) + if analyst_target_krw and current_price_krw: + gap_reason = target_rem.get("target_gap_reason", "") + render_target_price_compare(tp, analyst_target_krw, current_price_krw, gap_reason) + + +def render_scan_report(rpt, analyst_target_krw=0, current_price_krw=0): + if not rpt or not isinstance(rpt, dict): return + summary = rpt.get("summary", "") + action = rpt.get("action_type", "관망") + conf_score = rpt.get("confidence_score", 50) + conf_reason = rpt.get("confidence_reason", "") + catalyst = rpt.get("catalyst", "") + + border_color = "#E0E0E0" if "매수" in action else ("#9ABBE0" if "관망" in action else "rgba(255,255,255,0.08)") + safe_sum = re.sub(r'\*\*(.*?)\*\*', r'\1', str(summary).replace('\n',' ')) + + st.markdown( + f'
' + f'중장기 스캔 리포트

' + f'{safe_sum}
', + unsafe_allow_html=True + ) + render_confidence_bar(conf_score, conf_reason) + + # ── 스캔 리포트도 탭으로 분리 + tab_fit, tab_growth, tab_timing, tab_risk, tab_outlook = st.tabs(["📊 포트폴리오 적합", "🛡 성장 해자", "⏱ 타이밍", "! 리스크", "📈 수익률 전망"]) + + with tab_fit: + pfit = rpt.get("portfolio_fit", {}) + if catalyst: + safe_cat = re.sub(r'\*\*(.*?)\*\*', r'\1', str(catalyst)) + st.markdown( + f'
' + f'
⚡ 지금 투자해야 할 촉매
' + f'
{safe_cat}
', + unsafe_allow_html=True + ) + if isinstance(pfit, dict) and any(pfit.values()): + overlap = pfit.get("sector_overlap", "") + divers = pfit.get("risk_diversification", "") + port_sig = pfit.get("current_portfolio_signal", "") + for title, content, col in [ + ("🗂 섹터/테마 중복", overlap, "#444444"), + ("⚖️ 리스크 분산", divers, "#AAAAAA"), + ("🎯 현재 포트폴리오 판단", port_sig, "#D8D8D8"), + ]: + if content: + safe_c = re.sub(r'\*\*(.*?)\*\*', r'\1', str(content)) + st.markdown( + f'
' + f'
{title}
' + f'
{safe_c}
', + unsafe_allow_html=True + ) + + with tab_growth: + growth_quant = rpt.get("growth_moat_quantitative", "") or rpt.get("growth_moat_analysis", "") + growth_qual = rpt.get("growth_moat_qualitative", "") + valuation = rpt.get("valuation_growth_fit", "") + for title, content, col in [ + ("📊 정량 근거", growth_quant, "#444444"), + ("💡 정성 판단", growth_qual, "#888888"), + ("💰 밸류에이션", valuation, "#D8D8D8"), + ]: + if content: + safe_c = re.sub(r'\*\*(.*?)\*\*', r'\1', str(content).replace('\n','
')) + st.markdown( + f'
' + f'
{title}
' + f'
{safe_c}
', + unsafe_allow_html=True + ) + + with tab_timing: + timing = rpt.get("timing_entry_analysis", "") + zones = rpt.get("entry_zones", {}) + if timing: + safe_t = re.sub(r'\*\*(.*?)\*\*', r'\1', str(timing).replace('\n','
')) + st.markdown(f'
{safe_t}
', unsafe_allow_html=True) + if isinstance(zones, dict): + z1 = zones.get("first_buy", "-"); z2 = zones.get("second_buy", "-"); zs = zones.get("stop_thesis", "-") + st.markdown( + f'
' + f'
' + f'
1차 분할매수
' + f'
{z1}
' + f'
' + f'
2차 추가매수
' + f'
{z2}
' + f'
' + f'
해자 붕괴선
' + f'
{zs}
' + f'
', + unsafe_allow_html=True + ) + if analyst_target_krw and current_price_krw: + entry_zones = rpt.get("entry_zones", {}) + first_buy_str = entry_zones.get("first_buy", "") if isinstance(entry_zones, dict) else "" + render_target_price_compare(first_buy_str, analyst_target_krw, current_price_krw) + + with tab_risk: + hedge = rpt.get("tech_risk_hedge", "") + if hedge: + safe = re.sub(r'\*\*(.*?)\*\*', r'\1', str(hedge).replace('\n','
')) + st.markdown( + f'
' + f'
기술주 리스크 헤지
' + f'
{safe}
', + unsafe_allow_html=True + ) + recs = rpt.get("rebalancing_recommendations") + if recs and isinstance(recs, list): + st.markdown('
↻ 리스크 분산 추천
', unsafe_allow_html=True) + for i, rec in enumerate(recs): + t = rec.get("ticker","N/A"); n = rec.get("name","Unknown"); r = rec.get("reason","") + c1, c2 = st.columns([0.75, 0.25], vertical_alignment="center") + with c1: + st.markdown( + f'
' + f'
{n} ' + f'{t}
' + f'
{r}
', + unsafe_allow_html=True + ) + with c2: + if st.button(f"스캔", key=f"re_scan_btn_{i}_{t}", use_container_width=True): + st.session_state.active_ticker = t + st.session_state.main_menu = "⌂ 홈 & 스캔" + st.session_state.p_diag_mode = False + st.session_state.pop('detail_ticker', None) + st.rerun() + + # ─────────── 탭 3: 수익률 전망 ─────────── + with tab_outlook: + outlook = rpt.get("portfolio_outlook", {}) + if isinstance(outlook, dict): + import re as _re + + def _bold_numbers(text): + return _re.sub( + r'([+\-]?\d[\d,]*\.?\d*\s*[%배원억만]+)', + r'\1', + str(text) + ) + + scenarios = { + "낙관": { + "pct": outlook.get("optimistic_pct") or outlook.get("optimistic", "-"), + "desc": outlook.get("optimistic_desc") or outlook.get("optimistic", ""), + "color": "#AAAAAA", "sel_border": "rgba(200,200,200,0.6)", + "border": "rgba(255,255,255,0.10)", "bg": "rgba(255,255,255,0.05)", "icon": "🟢", + }, + "기본": { + "pct": outlook.get("base_pct") or outlook.get("base", "-"), + "desc": outlook.get("base_desc") or outlook.get("base", ""), + "color": "#D8D8D8", "sel_border": "rgba(220,220,220,0.6)", + "border": "rgba(255,255,255,0.10)", "bg": "rgba(255,255,255,0.04)", "icon": "⚪", + }, + "비관": { + "pct": outlook.get("pessimistic_pct") or outlook.get("pessimistic", "-"), + "desc": outlook.get("pessimistic_desc") or outlook.get("pessimistic", ""), + "color": "#E08080", "sel_border": "rgba(200,60,60,0.8)", + "border": "rgba(200,60,60,0.25)", "bg": "rgba(200,60,60,0.05)", "icon": "🔴", + }, + } + + key = f"outlook_tab_{id(rpt)}" + if key not in st.session_state: + st.session_state[key] = "기본" + selected = st.session_state[key] + + cols = st.columns(3) + for label, s in scenarios.items(): + col = cols[list(scenarios.keys()).index(label)] + with col: + clicked = st.button( + f"{s['icon']} {label}\n\n{s['pct']}", + key=f"ol_{label}_{id(rpt)}", + use_container_width=True + ) + if clicked: + st.session_state[key] = label + st.rerun() + + # 선택된 시나리오 설명 + sel = scenarios[selected] + if sel["desc"] and len(str(sel["desc"])) > 5: + st.markdown( + f'
' + f'{_bold_numbers(sel["desc"])}' + f'
', + unsafe_allow_html=True + ) + + # 근거 노트 + st.markdown( + f'
' + f'
📐 {_bold_numbers(outlook.get("beta_note",""))}
' + f'
🎯 {_bold_numbers(outlook.get("upside_note",""))}
' + f'
📊 {_bold_numbers(outlook.get("valuation_note",""))}
' + f'
' + f'⚠️ 핵심 리스크 {outlook.get("key_risk","")}
' + f'
', + unsafe_allow_html=True + ) + else: + st.markdown('
데이터 없음
', unsafe_allow_html=True) + + + +def draw_chart(ticker): + ph = st.empty() + ph.markdown('
', unsafe_allow_html=True) + try: + hist = yf.Ticker(ticker).history(period="1mo", interval="1d") + ph.empty() + if not hist.empty: + tab1, tab2 = st.tabs(["캔들차트", "라인차트"]) + with tab1: + fig = go.Figure(go.Candlestick( + x=hist.index, open=hist['Open'], high=hist['High'], + low=hist['Low'], close=hist['Close'], + increasing_line_color='#D8D8D8', decreasing_line_color='#5C7A8A' + )) + fig.update_layout( + height=220, margin=dict(l=0,r=0,t=0,b=0), + paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', + xaxis=dict(showgrid=False, visible=False, rangeslider=dict(visible=False)), + yaxis=dict(showgrid=True, gridcolor='rgba(255,255,255,0.035)', visible=False), + hovermode="x unified" + ) + st.plotly_chart(fig, use_container_width=True, config={'displayModeBar':False}) + with tab2: + fig2 = go.Figure(go.Scatter( + x=hist.index, y=hist['Close'], fill='tozeroy', mode='lines', + line=dict(color='#D8D8D8', width=2), fillcolor='rgba(255,255,255,0.05)' + )) + fig2.update_layout( + height=220, margin=dict(l=0,r=0,t=0,b=0), + paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', + xaxis=dict(showgrid=False, visible=False), + yaxis=dict(showgrid=True, gridcolor='rgba(255,255,255,0.035)', visible=False), + hovermode="x unified" + ) + st.plotly_chart(fig2, use_container_width=True, config={'displayModeBar':False}) + except: ph.warning("차트 데이터를 불러올 수 없습니다.") + +def parse_target_prices(target_price_str): + nums = re.findall(r'[\d,]+', str(target_price_str)) + result = [] + for n in nums: + try: + v = int(n.replace(',', '')) + if v >= 10000: + result.append(v) + except: pass + return sorted(set(result)) + +def get_price_alert(action, current_price, target_price_str, avg_price, report=None): + action = str(action) + report = report or {} + + if "익절" in action and target_price_str and target_price_str != "-": + prices = parse_target_prices(target_price_str) + if prices: + tp = min(prices) + ratio = current_price / tp if tp > 0 else 0 + if ratio >= 1.0: + return 'tp_hit', f"익절 목표가 {tp:,}원 도달 · 지금 바로 점검하세요" + elif ratio >= 0.95: + return 'tp', f"익절 목표가 {tp:,}원까지 {tp - current_price:,}원 남음 ({ratio*100:.1f}%)" + + thesis = report.get("thesis_validity", {}) + verdict = thesis.get("verdict", "") if isinstance(thesis, dict) else "" + if verdict == "훼손": + return 'sl_broken', "매수 해자 훼손 판정 · 손절 검토 필요" + + if ("손절" in action or "추가매수" in action or "보유" in action) \ + and target_price_str and target_price_str != "-": + prices = parse_target_prices(target_price_str) + if prices: + sl = min(prices) + if sl > 0 and current_price <= sl: + return 'sl_broken', f"손절 대응가 {sl:,}원 이탈 · 즉시 대응 필요" + elif sl > 0 and current_price <= sl * 1.05: + return 'sl', f"손절 대응가 {sl:,}원 근접 ({((current_price / sl) - 1) * 100:+.1f}%)" + + if ("보유" in action or "추가매수" in action) and current_price < avg_price: + if verdict == "점검필요": + loss_pct = (current_price / avg_price - 1) * 100 + return 'sl', f"해자 점검필요 + 손실 중 ({loss_pct:+.1f}%) · 재진단 권장" + + return None, None + +def _build_alert_groups(prices, rate): + groups = {"급변": [], "매수": [], "익절": [], "스톱로스": []} + if st.session_state.df.empty: + return groups + + tickers = tuple(sorted(st.session_state.df['티커'].tolist())) + daily_changes = get_daily_change_bulk(tickers) + + for _, row in st.session_state.df.iterrows(): + t = row['티커'] + ap = float(row['평단가']) + nm = row['종목명'] + ck = prices.get(t, 0) * rate + if ck <= 0 or ap <= 0: + continue + + daily_pct = daily_changes.get(t, 0.0) + total_pct = (ck / ap - 1) * 100 + + rp = st.session_state.full_stock_reports.get(f"{t}_{ap}", {}).get("report", {}) + act = rp.get("action_type", "") + + target_rem = rp.get("target_remaining", {}) + add_buy = rp.get("additional_buy_analysis", {}) + if isinstance(target_rem, dict) and target_rem.get("target_price", "-") not in ("-", "", None): + tgp = target_rem["target_price"] + elif isinstance(add_buy, dict) and add_buy.get("suggested_price", "-") not in ("-", "", None): + tgp = add_buy["suggested_price"] + else: + tgp = "-" + + item_base = dict( + ticker=t, name=nm, change_pct=daily_pct, + current_price=int(ck), avg_price=int(ap), + target_price=tgp, action=act + ) + + if abs(daily_pct) >= 5.0: + groups["급변"].append(item_base) + + if not act: + continue + + thesis = rp.get("thesis_validity", {}) + verdict = thesis.get("verdict", "") if isinstance(thesis, dict) else "" + thesis_broken = (verdict == "훼손") + + item_strat = dict( + ticker=t, name=nm, change_pct=total_pct, + current_price=int(ck), avg_price=int(ap), + target_price=tgp, action=act + ) + if "손절" in act or thesis_broken: + groups["스톱로스"].append(item_strat) + elif "익절" in act: + groups["익절"].append(item_strat) + elif "추가매수" in act or "매수" in act: + groups["매수"].append(item_strat) + + return groups + +def _navigate_to_ticker(ticker): + in_portfolio = ticker in st.session_state.df['티커'].values if not st.session_state.df.empty else False + if in_portfolio: + st.session_state.detail_ticker = ticker + st.session_state.main_menu = "▤ 자산 상세 진단" + st.session_state.p_diag_mode = False + st.session_state.pop('active_ticker', None) + else: + st.session_state.active_ticker = ticker + st.session_state.main_menu = "⌂ 홈 & 스캔" + st.session_state.p_diag_mode = False + st.session_state.pop('detail_ticker', None) + +def render_price_alert(level, message, ticker, name): + if level is None: return + cfg = { + 'tp_hit': ("#9ABBE0", "rgba(255,255,255,0.05)", "rgba(255,255,255,0.12)", "익절 목표 도달"), + 'tp': ("#9ABBE0", "rgba(255,255,255,0.04)", "rgba(255,255,255,0.10)", "익절 임박"), + 'sl': ("#E0E0E0", "rgba(255,255,255,0.04)", "rgba(200,60,60,0.18)", "손절 주의"), + 'sl_broken': ("#E0E0E0", "rgba(229,62,62,0.1)", "rgba(200,60,60,0.28)", "손절가 이탈"), + } + color, bg, border, label = cfg.get(level, ("#D8D8D8","rgba(255,255,255,0.04)","rgba(201,168,76,0.2)","알림")) + pulse = "animation:alertPulse 1.8s ease-in-out infinite;" if "broken" in level or "hit" in level else "" + st.markdown( + f'
' + f'
' + f'{label}' + f'{name} ({ticker})' + f'
' + f'
{message}
' + f'
', + unsafe_allow_html=True + ) + +def render_grouped_alert_panel(prices, rate): + groups = _build_alert_groups(prices, rate) + total_cnt = sum(len(v) for v in groups.values()) + + if total_cnt == 0 and not st.session_state.df.empty: + tickers_fb = tuple(sorted(st.session_state.df['티커'].tolist())) + daily_changes_fb = get_daily_change_bulk(tickers_fb) + for _, row in st.session_state.df.iterrows(): + t = row["티커"]; ap = float(row["평단가"]) + ck = prices.get(t, 0) * rate + if ck <= 0 or ap <= 0: continue + pct = daily_changes_fb.get(t, 0.0) + groups["급변"].append(dict( + ticker=t, name=row["종목명"], change_pct=pct, + current_price=int(ck), avg_price=int(ap), target_price="", action="" + )) + total_cnt = len(groups["급변"]) + + if total_cnt == 0: return + + react_data = {"급변": [], "매수": [], "익절": [], "스톱로스": []} + for tab in react_data.keys(): + for item in groups[tab]: + pct = item["change_pct"] + react_data[tab].append({ + "ticker": item["ticker"], + "name": item["name"], + "change": f"{'▲' if pct >= 0 else '▼'} {abs(pct):.1f}%", + "price": f"{item['current_price']:,}원", + }) + + elapsed = int(time.time() - st.session_state.get("alert_panel_start_time", time.time())) + time_left = max(0, 60 - elapsed) + data_json = json.dumps(react_data, ensure_ascii=False) + + inject_html = f""" + + + +""" + components.html(inject_html, height=1) + +def render_target_progress(avg_price, current_price, target_return_pct=20.0): + target_price = avg_price * (1 + target_return_pct / 100) + progress = min((current_price - avg_price) / (target_price - avg_price) * 100, 100) if target_price > avg_price else 0 + progress = max(progress, 0) + bar_color = "#AAAAAA" if progress >= 100 else ("#D8D8D8" if progress >= 50 else "#444444") + st.markdown( + f'
' + f'
' + f'' + f'목표 {target_return_pct:.0f}% 달성도' + f'{progress:.1f}%' + f'
' + f'
' + f'
' + f'
' + f'
목표가: {int(target_price):,}원
' + f'
', + unsafe_allow_html=True + ) + +def render_trade_analytics(tdf): + if tdf.empty or len(tdf) < 2: return + wins = tdf[tdf['실현손익'] > 0] + losses = tdf[tdf['실현손익'] < 0] + wr = len(wins) / len(tdf) * 100 + aw = wins['실현손익'].mean() if not wins.empty else 0 + al = abs(losses['실현손익'].mean()) if not losses.empty else 1 + rr = aw / al if al > 0 else 0 + bew = 100 / (1 + rr) if rr > 0 else 50 + total = tdf['실현손익'].sum() + total_fee = tdf['수수료'].sum() if '수수료' in tdf.columns else 0 + + st.markdown("### 매매 성과 분석") + c1, c2, c3, c4 = st.columns(4) + for col, label, val, color in [ + (c1, "총 누적 실현손익", f"{int(total):,}원", "#E0E0E0" if total>=0 else "#9ABBE0"), + (c2, "승률", f"{wr:.1f}%", "#AAAAAA" if wr>=bew else "#E0E0E0"), + (c3, "손익비 (R)", f"{rr:.2f}", "#AAAAAA" if rr>=1.5 else "#D8D8D8"), + (c4, "누적 수수료", f"{int(total_fee):,}원", "#888888"), + ]: + with col: + st.markdown( + f'
' + f'
{label}
' + f'
{val}
', + unsafe_allow_html=True + ) + + r_msg = "우수 (1.5↑)" if rr>=1.5 else ("양호 (1.0↑)" if rr>=1.0 else "개선 필요") + r_color = "#AAAAAA" if rr>=1.5 else ("#D8D8D8" if rr>=1.0 else "#E0E0E0") + st.markdown( + f'
' + f'손익비: {r_msg}  |  ' + f'손익분기 승률: {bew:.1f}% (현재: {wr:.1f}%)
', + unsafe_allow_html=True + ) + + if '일시' in tdf.columns and not tdf.empty: + try: + tdf2 = tdf.copy() + tdf2['월'] = pd.to_datetime(tdf2['일시']).dt.to_period('M').astype(str) + monthly = tdf2.groupby('월')['실현손익'].sum().reset_index() + monthly.columns = ['월', '손익'] + colors_m = ['#E0E0E0' if v >= 0 else '#9ABBE0' for v in monthly['손익']] + fig_m = go.Figure(go.Bar( + x=monthly['월'], y=monthly['손익'], + marker_color=colors_m, + text=[f"{int(v):,}" for v in monthly['손익']], + textposition='outside', textfont=dict(color='#888888', size=11) + )) + fig_m.update_layout( + height=200, margin=dict(l=0,r=0,t=10,b=0), + paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', + xaxis=dict(showgrid=False, color='#444444', tickfont=dict(size=11)), + yaxis=dict(showgrid=True, gridcolor='rgba(255,255,255,0.035)', visible=False), + bargap=0.3 + ) + st.markdown("#### 월별 실현손익") + st.plotly_chart(fig_m, use_container_width=True, config={'displayModeBar':False}) + except: pass + + st.markdown("#### 전략 태그별 성과") + ts = tdf.groupby('태그')['실현손익'].agg(횟수='count', 합계='sum').reset_index().sort_values('합계', ascending=False) + for _, row in ts.iterrows(): + c = "#E0E0E0" if row['합계'] >= 0 else "#9ABBE0" + st.markdown( + f'
' + f'{row["태그"]}' + f'{int(row["횟수"])}회' + f'{int(row["합계"]):+,}원
', + unsafe_allow_html=True + ) + +def render_earnings_calendar(tickers, label="보유 종목"): + if not tickers: return + with st.spinner("실적 발표 일정 조회 중..."): + cal = get_earnings_calendar(tuple(sorted(tickers))) + if not cal: return + + import calendar as cal_lib + cal_lib.setfirstweekday(6) + + now = datetime.now() + year = now.year + month = now.month + today_day = now.day + + month_matrix = cal_lib.monthcalendar(year, month) + month_name = f"{year}년 {month}월" + + day_to_stocks = {} + upcoming_other = [] + + for ticker, info in cal.items(): + try: + dt = datetime.strptime(info["date"], "%Y-%m-%d") + try: + _nm = st.session_state.df[st.session_state.df['티커'] == ticker]['종목명'].values + nm = _nm[0] if len(_nm) > 0 else ticker + except: + nm = ticker + + entry = { + "ticker": ticker, + "name": nm, + "days_left": info["days_left"], + "date": info["date"], + } + + if dt.year == year and dt.month == month: + d = dt.day + if d not in day_to_stocks: + day_to_stocks[d] = [] + day_to_stocks[d].append(entry) + else: + upcoming_other.append(entry) + except: + pass + + upcoming_other.sort(key=lambda x: x["days_left"]) + + dow_labels = ["SUN","MON","TUE","WED","THU","FRI","SAT"] + dow_html = "".join([ + f'
{d}
' + for i, d in enumerate(dow_labels) + ]) + + cells_html = "" + for week in month_matrix: + for day in week: + if day == 0: + cells_html += '
' + continue + + is_today = (day == today_day) + stocks_day = day_to_stocks.get(day, []) + has_event = len(stocks_day) > 0 + + if is_today: + cell_style = "background:rgba(255,255,255,0.07);border:1px solid rgba(255,255,255,0.30);box-shadow:0 0 12px rgba(255,255,255,0.08);" + day_color = "#D8D8D8"; day_weight = "900" + elif has_event: + cell_style = "background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.12);" + day_color = "#EBEBEB"; day_weight = "700" + else: + cell_style = "background:transparent;border:1px solid rgba(255,255,255,0.04);" + day_color = "#3A3530"; day_weight = "400" + + today_indicator = ( + '
' + ) if is_today else '
' + + badges_html = "" + for stk in stocks_day[:2]: + dl = stk["days_left"] + if dl == 0: b_bg="#212,90,90,0.20)"; b_col="#E0E0E0"; b_brd="rgba(200,60,60,0.32)"; b_lbl="TODAY" + elif dl < 0: b_bg="rgba(92,82,71,0.15)"; b_col="#444444"; b_brd="rgba(92,82,71,0.25)"; b_lbl="완료" + elif dl <= 7: b_bg="rgba(200,60,60,0.12)"; b_col="#E0E0E0"; b_brd="rgba(200,60,60,0.24)"; b_lbl=f"D-{dl}" + else: b_bg="rgba(255,255,255,0.07)"; b_col="#D8D8D8"; b_brd="rgba(255,255,255,0.14)"; b_lbl=f"D-{dl}" + short = stk["name"][:5] if len(stk["name"]) > 5 else stk["name"] + badges_html += ( + f'
' + f'
{short}
' + f'
{b_lbl}
' + ) + if len(stocks_day) > 2: + badges_html += f'
+{len(stocks_day)-2}
' + + cells_html += ( + f'
' + f'
{day}
' + f'{today_indicator}{badges_html}
' + ) + + total_this_month = sum(len(v) for v in day_to_stocks.values()) + imminent = sum(1 for stocks in day_to_stocks.values() for s in stocks if 0 <= s["days_left"] <= 7) + summary_html = "" + if total_this_month > 0: + summary_html = ( + f'
' + f'이번 달 {total_this_month}건' + ) + if imminent > 0: + summary_html += ( + f'⚡ {imminent}건 7일 이내' + ) + summary_html += '
' + + calendar_html = f""" +
+
+
+
📅 실적 발표 캘린더 - {label}
+
{month_name}
+
+
{summary_html}
+
+
{dow_html}
+
{cells_html}
+
+ """ + st.markdown(calendar_html, unsafe_allow_html=True) + + if day_to_stocks: + st.markdown('
이번 달 실적 상세
', unsafe_allow_html=True) + for d in sorted(day_to_stocks.keys()): + for stk in day_to_stocks[d]: + dl = stk["days_left"]; date_str = stk["date"] + if dl < 0: uc,ub,ubrd,ul="#444444","rgba(255,255,255,0.025)","rgba(255,255,255,0.05)",f"{abs(dl)}일 전" + elif dl == 0: uc,ub,ubrd,ul="#E0E0E0","rgba(200,60,60,0.14)","rgba(200,60,60,0.32)","🔴 TODAY" + elif dl <= 7: uc,ub,ubrd,ul="#E0E0E0","rgba(255,255,255,0.05)","rgba(229,62,62,0.22)",f"D{dl}" + else: uc,ub,ubrd,ul="#D8D8D8","rgba(255,255,255,0.05)","rgba(255,255,255,0.13)",f"D{dl}" + pulse = "animation:alertPulse 1.8s ease-in-out infinite;" if dl == 0 else "" + st.markdown( + f'
' + f'
' + f'
' + f'
' + f'{stk["ticker"][:4]}
' + f'
{stk["name"]}
' + f'
{stk["ticker"]} · {date_str}
' + f'
' + f'
{ul}
' + f'
실적 발표
' + f'
', + unsafe_allow_html=True + ) + + if upcoming_other: + st.markdown('
다음 달 이후 예정
', unsafe_allow_html=True) + for stk in upcoming_other[:6]: + dl = stk["days_left"]; date = stk["date"] + st.markdown( + f'
' + f'
' + f'{stk["name"]}' + f'{stk["ticker"]}
' + f'
' + f'{date}' + f'D{dl}' + f'
', + unsafe_allow_html=True + ) + +def calc_realized_pnl(sell_price, avg_price, qty, fee_rate=None): + if fee_rate is None: + fee_rate = st.session_state.get('fee_rate', 0.00015) + gross = (sell_price - avg_price) * qty + fee_buy = avg_price * qty * fee_rate + fee_sell = sell_price * qty * fee_rate + net = gross - fee_buy - fee_sell + return round(net), round(fee_buy + fee_sell) + +# ============================================================ +# 메인 라우팅 +# ============================================================ +_ap = st.query_params.get("alert_action", "") +if _ap: + st.query_params.clear() + if _ap == "minimize": st.session_state.alert_panel_minimized = True; st.rerun() + elif _ap == "open": st.session_state.alert_panel_minimized = False; st.session_state.alert_panel_start_time = time.time(); st.rerun() + elif _ap == "expired": st.session_state.alert_panel_minimized = True; st.rerun() + elif _ap.startswith("tab:"): + t_ = _ap[4:] + if t_ in ("급변","매수","익절","스톱로스"): st.session_state.alert_active_tab = t_ + st.rerun() + elif _ap.startswith("goto:"): + _navigate_to_ticker(_ap[5:]); st.rerun() + +if st.session_state.show_menu: + st.markdown("### 메뉴") + st.markdown('', unsafe_allow_html=True) + +elif st.session_state.main_menu == "⌂ 홈 & 스캔": + prices = get_all_prices() + rate = get_exchange_rate() + _take_portfolio_snapshot(prices, rate) + + if 'active_ticker' not in st.session_state: + t_cost = t_val = 0 + port_ai = [] + for _, r in st.session_state.df.iterrows(): + cp = prices.get(r['티커'], 0) * rate + t_cost += r['평단가'] * r['수량'] + t_val += (cp if cp > 0 else r['평단가']) * r['수량'] + pct = ((cp / r['평단가']) - 1) * 100 if r['평단가'] > 0 else 0 + port_ai.append(f"{r['종목명']}({pct:.1f}%)") + + p_pct = ((t_val / t_cost - 1) * 100) if t_cost > 0 else 0 + + st.markdown('
', unsafe_allow_html=True) + txt = (f"총 평가액\n~{int(t_val):,}원~\n" + f"**수익률: {'▲' if p_pct>=0 else '▼'} {abs(p_pct):.2f}%**\n(상세 진단으로 이동)") + if st.button(txt, key="home_port_btn", use_container_width=True): + select_menu("▤ 자산 상세 진단"); st.rerun() + + if st.session_state.df.empty: + st.markdown(""" +
+

Invest Pro Alpha에 오신 걸 환영합니다

+
Step 1. 자산 상세 진단 -> 보유 종목 추가
+
Step 2. AI 스캔으로 중장기 성장주 분석
+
Step 3. 매매 일지로 승률·손익비 데이터 쌓기
+
+ """, unsafe_allow_html=True) + + if not st.session_state.df.empty: + render_grouped_alert_panel(prices, rate) + with st.spinner("포트폴리오 분석 중..."): + msg = get_ai_alert(", ".join(port_ai), _key_hash(), st.session_state.selected_model) + st.markdown( + f'
' + f'
AI PORTFOLIO BRIEFING
' + f'{msg}
', + unsafe_allow_html=True + ) + + search = st.text_input("종목 검색", placeholder="종목명 또는 티커 (예: TSLA, 테슬라)").strip() + if search: + _, pc, tt = get_ticker_info(search) + if pc > 0: st.session_state.active_ticker = tt; st.rerun() + + all_cal_tickers = list(set( + st.session_state.df['티커'].tolist() + + st.session_state.fav_df['티커'].tolist() + )) + if all_cal_tickers: + st.write(""); st.divider(); st.write("") + with st.expander("📅 실적 발표 캘린더", expanded=False): + render_earnings_calendar(all_cal_tickers, label="보유 + 관심 종목") + + st.write(""); st.divider(); st.write("") + c1, c2 = st.columns([0.65, 0.35], vertical_alignment="bottom") + with c1: st.subheader("맞춤 성장주 스캔") + with c2: + if st.button("새로고침", use_container_width=True): + with st.spinner("성장주/턴어라운드 탐색 중..."): + themes = ["AI 인프라 수혜 성장주","실적 턴어라운드 진행 중","강력 기관 매수 포착","역사적 저평가 탈출 성장주","중장기 해자 보유 기술주"] + owned_s = ", ".join(st.session_state.df['티커'].tolist()) or "없음" + disc = get_ai_json_response( + f"중장기(6개월+) 성장주 또는 턴어라운드 미국 주식 3개 영문 티커 추천. " + f"[\"MSFT\",\"CRWD\",\"PLTR\"] 형태의 1차원 JSON 배열 형식 필수. " + f"테마:{random.choice(themes)}, ID:{time.time()}. " + f"기보유 [{owned_s}] 및 애플·테슬라·엔비디아 같은 빅테크 제외. " + f"실질적 성장 모멘텀 또는 턴어라운드 진행 중인 종목만.", + bypass_cache=True + ) + if disc and isinstance(disc, list): + st.session_state.ai_finds = [t for t in disc if isinstance(t, str)][:3] + + finds = st.session_state.get('ai_finds', ['PLTR','DOCN','CRWD']) + cols = st.columns(3) + for i, t in enumerate(finds): + n, p, ct = get_ticker_info(t) + sn = str(n)[:14]+".." if len(str(n)) > 14 else str(n) + with cols[i]: + st.markdown('
', unsafe_allow_html=True) + if st.button(f"*{ct}*\n**{sn}**\n~{p:,}원~", key=f"h_scan_{i}", use_container_width=True): + st.session_state.active_ticker = ct; st.rerun() + + else: + tn = st.session_state.active_ticker + n, p, _ = get_ticker_info(tn) + + c1, c2 = st.columns(2) + with c1: + if st.button("재분석", use_container_width=True): + st.session_state.force_home_refresh = True; st.rerun() + with c2: + is_fav = tn in st.session_state.fav_df['티커'].values + if st.button("관심종목 해제" if is_fav else "관심종목 추가", use_container_width=True): + if is_fav: st.session_state.fav_df = st.session_state.fav_df[st.session_state.fav_df['티커'] != tn] + else: st.session_state.fav_df = pd.concat([st.session_state.fav_df, pd.DataFrame([{"티커":tn,"종목명":n}])], ignore_index=True) + save_fav(); st.rerun() + + bypass = st.session_state.pop('force_home_refresh', False) + scan_key = f"scan_{tn}" + stored_scan = st.session_state.full_stock_reports.get(scan_key, {}) + needs_scan = bypass or stored_scan.get("date") != today_str + + if needs_scan: + with st.spinner(f"{n} 중장기 성장주 스캔 중..."): + fin_ctx, has_rich = get_rich_financial_context(tn) + news_ctx = get_recent_news(tn) + owned_list = st.session_state.df['티커'].tolist() if not st.session_state.df.empty else [] + port_ctx = _build_portfolio_context(prices, rate) + target_info = f"종목: {n}({tn})\n현재가: {p:,}원\n[실제 재무 데이터]\n{fin_ctx}" + report = get_ai_json_response( + get_scan_prompt(target_info, tid=tn, owned=owned_list, news=news_ctx, portfolio_context=port_ctx), + bypass_cache=True + ) + if report: + st.session_state.full_stock_reports[scan_key] = { + "date": today_str, "report": report, "avg_price": 0 + } + _record_report_history(scan_key, report) + save_cache() + else: + report = stored_scan["report"] + has_rich = True + + stars = report.get("recommendation_stars","★★★★☆") if report else "★★★★☆" + + # ── 스캔: 헤더에 배당/52주 위치 통합 + extra_badges_scan = [] + try: + usd_price_s = p / get_exchange_rate() + pos_s = calc_52w_position(tn, usd_price_s) + pos_label = "저점" if pos_s <= 30 else ("중간" if pos_s <= 70 else "고점") + pos_color = "#AAAAAA" if pos_s <= 30 else ("#D8D8D8" if pos_s <= 70 else "#E0E0E0") + extra_badges_scan.append(("52주", f"{pos_s:.0f}% · {pos_label}", pos_color)) + except: pass + + div_s = get_dividend_info(tn) + if div_s["yield_pct"] > 0: + extra_badges_scan.append(("💰", f"배당 {div_s['yield_pct']}%", "#AAAAAA")) + + _earn_s = get_earnings_calendar((tn,)) + if tn in _earn_s: + _ei_s = _earn_s[tn]; _edl_s = _ei_s["days_left"] + _ec_s = "#E0E0E0" if 0 <= _edl_s <= 7 else ("#D8D8D8" if _edl_s <= 30 else "#444444") + extra_badges_scan.append(("📅 실적", f"D-{_edl_s}" if _edl_s >= 0 else f"{abs(_edl_s)}일 전", _ec_s)) + + render_stock_header(n, tn, p, stars, "중장기 성장주 스캔", has_rich, extra_badges=extra_badges_scan) + + tp = get_analyst_target(tn) + if tp > 0: + st.markdown( + f"
" + f"전문가 평균 목표가 {tp:,}원
", + unsafe_allow_html=True + ) + + if report: + _zones = report.get("entry_zones", {}) + _f_buy = _zones.get("first_buy", "-") if isinstance(_zones, dict) else "-" + _act_s = report.get("action_type", "") + if "매수" in _act_s and _f_buy != "-": + _prices = parse_target_prices(_f_buy) + if _prices: + _zone_top = max(_prices) + if p <= _zone_top: + render_price_alert('tp_hit', f"현재가 {p:,}원 - 1차 분할매수 구간 진입", tn, n) + elif p <= _zone_top * 1.05: + render_price_alert('tp', f"1차 분할매수 구간({_zone_top:,}원) 근접 중", tn, n) + + draw_chart(tn) + render_scan_report(report, analyst_target_krw=tp, current_price_krw=p) + render_report_history_diff(scan_key, report) + +elif st.session_state.main_menu == "▤ 자산 상세 진단": + prices = get_all_prices() + rate = get_exchange_rate() + _take_portfolio_snapshot(prices, rate) + + if st.session_state.get('p_diag_mode'): + if st.button("최신 데이터로 재진단", key="port_reanalyze", use_container_width=True): + st.session_state.p_diag_mode = False + st.session_state.force_portfolio_refresh = True; st.rerun() + st.markdown("### 포트폴리오 종합 진단 리포트") + render_portfolio_report(st.session_state.get('p_diag_res')) + st.divider() + + if 'detail_ticker' in st.session_state and not st.session_state.get('p_diag_mode'): + dt = st.session_state.detail_ticker + n, p, _ = get_ticker_info(dt) + + c1, c2 = st.columns(2) + with c1: + if st.button("재분석", key="det_re", use_container_width=True): + st.session_state.force_detail_refresh = True; st.rerun() + with c2: + is_fav = dt in st.session_state.fav_df['티커'].values + if st.button("관심종목 해제" if is_fav else "관심종목 추가", key=f"fav_{dt}", use_container_width=True): + if is_fav: st.session_state.fav_df = st.session_state.fav_df[st.session_state.fav_df['티커'] != dt] + else: st.session_state.fav_df = pd.concat([st.session_state.fav_df, pd.DataFrame([{"티커":dt,"종목명":n}])], ignore_index=True) + save_fav(); st.rerun() + + bypass = st.session_state.pop('force_detail_refresh', False) + row = st.session_state.df[st.session_state.df['티커'] == dt].iloc[0] + cur_k = int(p) + p_pct = ((cur_k / row['평단가']) - 1) * 100 if row['평단가'] > 0 else 0 + ukey = f"{dt}_{row['평단가']}" + stored = st.session_state.full_stock_reports.get(ukey, {}) + needs = ( + bypass + or stored.get("date") != today_str + or stored.get("avg_price") != row['평단가'] + or not _is_new_structure(stored.get("report", {})) + ) + + buy_date_str = str(row.get('매수일', '') or '') + holding_days = "-" + if buy_date_str: + try: + bd = datetime.strptime(buy_date_str[:10], "%Y-%m-%d") + holding_days = f"{(datetime.now() - bd).days}일" + except: pass + + buy_reason_pre = str(row.get('매수근거', '') or '').strip() + if not buy_reason_pre and not st.session_state.get(f"reason_skip_{ukey}", False): + st.markdown( + '
' + '
✏️ 매수 근거 미기록
' + '
' + '매수 당시 생각을 적어두면 해자 유효성을 정확하게 판단할 수 있어요.' + '
', + unsafe_allow_html=True + ) + reason_col1, reason_col2 = st.columns([0.75, 0.25], vertical_alignment="bottom") + with reason_col1: + inline_reason = st.text_input( + "매수 근거 (선택)", + placeholder="예: AI 수주 모멘텀 / MA50 지지 확인 / 저평가 구간 분할매수", + key=f"inline_reason_{ukey}" + ) + with reason_col2: + if st.button("저장 후 분석", key=f"save_reason_{ukey}", type="primary", use_container_width=True): + if inline_reason.strip(): + idx_r = st.session_state.df[st.session_state.df['티커'] == dt].index[0] + st.session_state.df.at[idx_r, '매수근거'] = inline_reason.strip() + save_assets() + st.session_state[f"reason_skip_{ukey}"] = True + st.rerun() + if st.button("근거 없이 바로 분석", key=f"skip_reason_{ukey}", use_container_width=False): + st.session_state[f"reason_skip_{ukey}"] = True; st.rerun() + st.stop() + + if needs: + with st.spinner(f"{n} 보유 종목 진단 중..."): + fin_ctx, has_rich = get_rich_financial_context(dt) + news_ctx = get_recent_news(dt) + buy_reason = str(row.get('매수근거', '') or '').strip() + port_ctx = _build_portfolio_context(prices, rate) + ti = ( + f"종목: {n}({dt})\n" + f"평단가: {int(row['평단가']):,}원\n" + f"현재가: {cur_k:,}원\n" + f"수익률: {p_pct:.2f}%\n" + f"수량: {row['수량']}주\n" + f"보유기간: {holding_days}\n" + f"[매수 당시 근거] {buy_reason if buy_reason else '미기록'}\n" + f"[실제 재무 데이터]\n{fin_ctx}" + ) + report = get_ai_json_response( + get_owned_prompt(ti, tid=ukey, news=news_ctx, portfolio_context=port_ctx), + bypass_cache=True + ) + if report and "action_type" in report: + st.session_state.full_stock_reports[ukey] = {"date":today_str,"report":report,"avg_price":row['평단가']} + _record_report_history(ukey, report) + save_cache() + else: + report = stored["report"]; has_rich = True + + stars = report.get("recommendation_stars","★★★★☆") if report else "★★★★☆" + + # ── 보유 진단: 헤더에 수익률 + 보유기간 + 실적일 + 52주 + 배당 통합 + extra_badges_owned = [] + p_color_b = "#E0E0E0" if p_pct >= 0 else "#9ABBE0" + extra_badges_owned.append(("보유", holding_days, "#444444")) + extra_badges_owned.append(("수익률", f"{'▲' if p_pct>=0 else '▼'} {abs(p_pct):.2f}%", p_color_b)) + + try: + pos_o = calc_52w_position(dt, p / rate) + pos_label_o = "저점" if pos_o <= 30 else ("중간" if pos_o <= 70 else "고점") + pos_color_o = "#AAAAAA" if pos_o <= 30 else ("#D8D8D8" if pos_o <= 70 else "#E0E0E0") + extra_badges_owned.append(("52주", f"{pos_o:.0f}% · {pos_label_o}", pos_color_o)) + except: pass + + div_o = get_dividend_info(dt) + if div_o["yield_pct"] > 0: + extra_badges_owned.append(("배당", f"{div_o['yield_pct']}%", "#AAAAAA")) + + _earn2 = get_earnings_calendar((dt,)) + if dt in _earn2: + _ei2 = _earn2[dt]; _edl2 = _ei2["days_left"]; _edate2 = _ei2["date"] + _ec2 = "#E0E0E0" if 0 <= _edl2 <= 7 else ("#D8D8D8" if _edl2 <= 30 else "#444444") + _elabel2 = f"D-{_edl2}" if _edl2 >= 0 else f"{abs(_edl2)}일 전" + extra_badges_owned.append(("📅 실적", f"{_edate2} ({_elabel2})", _ec2)) + + render_stock_header(n, dt, p, stars, "보유 종목 진단 리포트", has_rich, + extra_badges=extra_badges_owned) + + tp = get_analyst_target(dt) + if tp > 0: + st.markdown( + f"
" + f"전문가 평균 목표가 {tp:,}원
", + unsafe_allow_html=True + ) + + render_target_progress(row['평단가'], cur_k, st.session_state.get('target_return_pct', 20.0)) + + if report: + _trem = report.get("target_remaining", {}) + _tgp_str = _trem.get("target_price", "-") if isinstance(_trem, dict) else "-" + _act = report.get("action_type", "") + alv, alm = get_price_alert( + action=_act, current_price=cur_k, + target_price_str=_tgp_str, avg_price=int(row['평단가']), + report=report + ) + render_price_alert(alv, alm, dt, n) + + draw_chart(dt) + render_owned_report(report, analyst_target_krw=tp, current_price_krw=cur_k) + render_report_history_diff(ukey, report) + + elif not st.session_state.get('p_diag_mode'): + st.markdown("### 보유 자산 관리") + + with st.expander("새로운 종목 추가", expanded=False): + c1, c2, c3 = st.columns([0.35, 0.3, 0.35], vertical_alignment="bottom") + with c1: add_in = st.text_input("종목명/티커", placeholder="예: AAPL") + with c2: add_p = st.number_input("평단가(원)", min_value=0) + with c3: add_q = st.number_input("수량", min_value=0.01) + add_reason = st.text_input( + "매수 근거", placeholder="예: MA50 지지 확인 후 진입 / AI 수주 모멘텀", + key="add_reason_input" + ) + rc1, rc2 = st.columns([0.5, 0.5], vertical_alignment="bottom") + with rc1: add_date = st.text_input("매수일", placeholder="예: 2025-06-12", key="add_date_input") + with rc2: + if st.button("등록", type="primary", use_container_width=True) and add_in: + with st.spinner("종목 정보 조회 중..."): + n, pc, ct = get_ticker_info(add_in) + if pc > 0: + st.session_state.df = pd.concat( + [st.session_state.df, pd.DataFrame([{ + "티커": ct, "종목명": n, "평단가": add_p, "수량": add_q, + "매수근거": add_reason, + "매수일": add_date if add_date else datetime.now().strftime("%Y-%m-%d") + }])], + ignore_index=True) + save_assets() + st.session_state.price_cache_ts = 0; st.rerun() + else: + st.error(f"'{add_in}' 종목을 찾을 수 없습니다.") + + if not st.session_state.df.empty: + st.markdown("### 포트폴리오 자산 비중") + try: + dv = st.session_state.df.copy() + dv['현재가'] = dv['티커'].apply(lambda x: prices.get(x,0)*rate) + dv['평가액'] = dv.apply(lambda r: (r['현재가'] if r['현재가']>0 else r['평단가'])*r['수량'], axis=1) + dv['수익률'] = dv.apply(lambda r: ((r['현재가']/r['평단가'])-1)*100 if r['평단가']>0 else 0, axis=1) + fig = px.treemap( + dv, path=['종목명'], values='평가액', color='수익률', + color_continuous_scale=['#5C7A8A','#1C1C1C','#D8D8D8'], + color_continuous_midpoint=0, custom_data=['수익률','현재가','티커'] + ) + fig.update_traces( + textfont=dict(family="Noto Sans KR", size=14, color="#EBEBEB"), + marker=dict(line=dict(color='#0C0C0C', width=2)), + texttemplate="%{label}
%{customdata[0]:.1f}%", + hovertemplate='%{label} (%{customdata[2]})
평가액: %{value:,.0f}원
수익률: %{customdata[0]:.2f}%' + ) + fig.update_layout( + margin=dict(t=0,l=0,r=0,b=0), height=270, + paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', + coloraxis_showscale=False, clickmode='event+select' + ) + try: + ev = st.plotly_chart(fig, use_container_width=True, config={'displayModeBar':False}, + on_select="rerun", selection_mode="points") + if ev and len(ev.selection.points) > 0: + cn = ev.selection.points[0]["label"] + ct = dv[dv['종목명']==cn]['티커'].values[0] + st.session_state.detail_ticker = ct + st.session_state.p_diag_mode = False; st.rerun() + except TypeError: + st.plotly_chart(fig, use_container_width=True, config={'displayModeBar':False}) + except: pass + + cb = ch = cp2 = cl = cn2 = 0 + for _, row in st.session_state.df.iterrows(): + s = st.session_state.full_stock_reports.get(f"{row['티커']}_{row['평단가']}", {}).get("report",{}).get("action_type","미분석") + if "추가매수" in s or (s == "매수"): cb += 1 + elif "익절" in s: cp2 += 1 + elif "손절" in s: cl += 1 + elif "보유" in s: ch += 1 + else: cn2 += 1 + + st.markdown("### 포트폴리오 전략 현황") + cs, cb2 = st.columns([0.7,0.3], gap="medium", vertical_alignment="center") + with cs: + st.markdown( + f'
' + f'
' + f'추가매수 {cb}' + f'보유 {ch}' + f'익절 {cp2}' + f'손절 {cl}' + f'미분석 {cn2}' + f'
', + unsafe_allow_html=True + ) + with cb2: + if st.button("전체 종합 진단", type="primary", use_container_width=True) \ + or st.session_state.pop('force_portfolio_refresh', False): + + total_stocks = len(st.session_state.df) + prg = st.empty() + prg.text(f"0 / {total_stocks} 종목 개별 분석 중...") + asset_list = [] + completed = [0] + sector_summary = {} + beta_info = {} + _shared_lock = threading.Lock() + _thread_results = {} + + def _analyze(row): + t = row['티커']; ap = row['평단가'] + key = f"{t}_{ap}" + ni, pi, ci = get_ticker_info(t) + sec, beta = get_ticker_metadata(t) + ck = int(pi) + pct = ((ck/ap)-1)*100 if ap>0 else 0 + buy_reason = str(row.get('매수근거', '') or '').strip() + + with _shared_lock: + sector_summary[sec] = sector_summary.get(sec, 0) + 1 + beta_info[t] = round(beta, 2) + + buy_date_str = str(row.get('매수일', '') or '') + holding_days = "-" + if buy_date_str: + try: + bd = datetime.strptime(buy_date_str[:10], "%Y-%m-%d") + holding_days = f"{(datetime.now() - bd).days}일" + except: pass + + fc, _ = get_rich_financial_context(t) + news_ctx = get_recent_news(t) + ti2 = ( + f"종목: {ni}({ci})\n" + f"평단가: {int(ap):,}원\n" + f"현재가: {ck:,}원\n" + f"수익률: {pct:.2f}%\n" + f"수량: {row['수량']}주\n" + f"보유기간: {holding_days}\n" + f"섹터: {sec} / Beta: {beta:.2f}\n" + f"[매수 당시 근거] {buy_reason if buy_reason else '미기록'}\n" + f"[실제 재무 데이터]\n{fc}" + ) + rp = get_ai_json_response( + get_owned_prompt(ti2, tid=key, news=news_ctx, + portfolio_context=_build_portfolio_context(prices, rate)), + bypass_cache=True + ) + with _shared_lock: + completed[0] += 1 + if rp and "action_type" in rp: + _thread_results[key] = { + "date": today_str, "report": rp, "avg_price": ap + } + + if rp and "action_type" in rp: + act = rp.get("action_type", "보유") + thesis = rp.get("thesis_validity", {}) + verdict = thesis.get("verdict", "") if isinstance(thesis, dict) else "" + verdict_tag = f"/해자:{verdict}" if verdict else "" + return f"- {row['종목명']}({t}) [섹터:{sec}/Beta:{beta:.2f}]: 수익률{pct:.1f}%, [전략:{act}{verdict_tag}]" + return f"- {row['종목명']}({t}): 수익률{pct:.1f}%" + + ctx = get_script_run_ctx() + def _wrap(row): + add_script_run_ctx(threading.current_thread(), ctx) + return _analyze(row) + + with concurrent.futures.ThreadPoolExecutor(max_workers=5) as ex: + futs = {ex.submit(_wrap, row): row['종목명'] for _, row in st.session_state.df.iterrows()} + for f in concurrent.futures.as_completed(futs): + r2 = f.result() + if r2: asset_list.append(r2) + prg.text(f"{completed[0]} / {total_stocks} 종목 분석 완료...") + + st.session_state.full_stock_reports.update(_thread_results) + save_cache() + prg.text("전체 포트폴리오 종합 진단 중...") + owned_list = st.session_state.df['티커'].tolist() + + # 실데이터 정량 지표 계산 + prg.text("실데이터 정량 지표 계산 중 (애널리스트·베타·MA)...") + try: + quant_metrics = get_portfolio_quant_metrics(st.session_state.df, prices, rate) + except: + quant_metrics = {} + + st.session_state.p_diag_res = get_ai_json_response( + get_portfolio_prompt( + "\n".join(asset_list), + owned=owned_list, + sector_summary=sector_summary, + beta_info=beta_info, + quant_metrics=quant_metrics + ), + bypass_cache=True + ) + # quant_metrics를 렌더러에서도 쓸 수 있게 저장 + if st.session_state.p_diag_res: + st.session_state.p_diag_res["_quant_metrics"] = quant_metrics + save_cache() + st.session_state.p_diag_mode = True; st.rerun() + + st.divider() + render_portfolio_history_chart() + st.markdown("### 내 포트폴리오") + + # ── 포트폴리오 카드: v16 방식 (st.button + action-marker) 으로 버튼 작동 + for idx, row in st.session_state.df.iterrows(): + t = row['티커']; ap = row['평단가'] + ck = int(prices.get(t,0)*rate) if prices.get(t,0)>0 else int(ap) + pct = ((ck/ap)-1)*100 if ap>0 else 0 + rp = st.session_state.full_stock_reports.get(f"{t}_{ap}",{}).get("report",{}) + act = rp.get("action_type","미분석") + + target_rem = rp.get("target_remaining", {}) + tgp = target_rem.get("target_price", "-") if isinstance(target_rem, dict) else "-" + thesis = rp.get("thesis_validity", {}) + tv = thesis.get("verdict", "") if isinstance(thesis, dict) else "" + tv_color = {"유효":"#AAAAAA","훼손":"#E0E0E0","점검필요":"#D8D8D8"}.get(tv, "#444444") + pc = "#E0E0E0" if pct>=0 else "#9ABBE0" + pa = "▲" if pct>=0 else "▼" + buy_reason = str(row.get('매수근거', '') or '').strip() + tgp_val = tgp if tgp != "-" else "-" + + with st.container(border=True): + st.markdown('
', unsafe_allow_html=True) + ct_col, cl2, ce, cd = st.columns([0.7, 0.1, 0.1, 0.1], vertical_alignment="center") + with ct_col: + tv_span = ( + f'{tv}' + ) if tv else "" + st.markdown( + f'
' + f'{row["종목명"]} ' + f'{t}' + f'{tv_span}
', + unsafe_allow_html=True + ) + with cl2: + st.markdown('
', unsafe_allow_html=True) + if st.button("↑", key=f"log_{idx}"): + st.session_state[f"log_mode_{idx}"] = not st.session_state.get(f"log_mode_{idx}", False) + st.session_state[f"edit_mode_{idx}"] = False + st.rerun() + with ce: + st.markdown('
', unsafe_allow_html=True) + if st.button("✎", key=f"edit_{idx}"): + st.session_state[f"edit_mode_{idx}"] = not st.session_state.get(f"edit_mode_{idx}", False) + st.session_state[f"log_mode_{idx}"] = False + st.rerun() + with cd: + st.markdown('
', unsafe_allow_html=True) + if st.button("✕", key=f"del_{idx}"): + st.session_state.df = st.session_state.df.drop(idx).reset_index(drop=True) + save_assets() + st.session_state.price_cache_ts = 0 + st.rerun() + + st.markdown( + f'
' + f'평단 {int(ap):,}원  ·  ' + f'현재 {ck:,}원  ·  ' + f'{pa} {abs(pct):.2f}%
', + unsafe_allow_html=True + ) + reason_inline = ( + f'  ·  ' + f'근거 {buy_reason}' + ) if buy_reason else "" + st.markdown( + f'
' + f'전략 [{act}]' + f'  ·  목표가 {tgp_val}' + f'{reason_inline}
', + unsafe_allow_html=True + ) + + if st.button("상세 진단 리포트", key=f"rep_{idx}", use_container_width=True): + st.session_state.detail_ticker = t + st.rerun() + + # ── 매도 일지 폼 (↑ 클릭 시 인라인 표시) + if st.session_state.get(f"log_mode_{idx}", False): + st.markdown('
', unsafe_allow_html=True) + lc1, lc2 = st.columns(2) + with lc1: sp = st.number_input("매도 단가(원)", value=float(ck), step=100.0, key=f"sp_{idx}") + with lc2: sq = st.number_input("매도 수량", value=float(row['수량']), max_value=float(row['수량']), min_value=0.01, step=1.0, key=f"sq_{idx}") + tags = ["#목표가도달_익절","#해자붕괴_손절","#비중조절","#뇌동매매_반성","#추세이탈","#턴어라운드_실패"] + stag = st.selectbox("전략 태그", tags, key=f"tag_{idx}") + memo = st.text_input("복기 메모", placeholder="예: 성장 스토리 훼손으로 손절", key=f"memo_{idx}") + if st.button("일지 저장", key=f"slog_{idx}", type="primary", use_container_width=True): + net_pnl, fee_amt = calc_realized_pnl(sp, row['평단가'], sq) + orig_reason = str(row.get('매수근거', '') or '') + st.session_state.trade_df = pd.concat([pd.DataFrame([{ + "일시": datetime.now().strftime("%Y-%m-%d %H:%M"), + "티커": t, "종목명": row['종목명'], + "구분": "매도", "매매가": sp, "수량": sq, + "실현손익": net_pnl, "수수료": fee_amt, + "태그": stag, "메모": memo, "매수근거": orig_reason + }]), st.session_state.trade_df], ignore_index=True) + save_trades() + if sq >= row['수량']: st.session_state.df = st.session_state.df.drop(idx).reset_index(drop=True) + else: st.session_state.df.at[idx,'수량'] = row['수량'] - sq + save_assets() + st.session_state[f"log_mode_{idx}"] = False + st.session_state.price_cache_ts = 0; st.rerun() + st.markdown('
', unsafe_allow_html=True) + + # ── 편집 폼 (✎ 클릭 시 인라인 표시) + if st.session_state.get(f"edit_mode_{idx}", False): + st.markdown('
', unsafe_allow_html=True) + ec1, ec2 = st.columns([0.5, 0.5], vertical_alignment="bottom") + with ec1: np2 = st.number_input("새 평단가(원)", value=float(ap), min_value=0.0, step=100.0, key=f"ep_{idx}") + with ec2: nq2 = st.number_input("새 수량", value=float(row['수량']), min_value=0.01, step=1.0, key=f"eq_{idx}") + cur_reason = str(row.get('매수근거', '') or '') + cur_date = str(row.get('매수일', '') or '') + new_reason = st.text_input("매수 근거", value=cur_reason, key=f"er_{idx}") + ed1, ed2 = st.columns([0.5, 0.5], vertical_alignment="bottom") + with ed1: new_date = st.text_input("매수일", value=cur_date, key=f"ed_{idx}") + with ed2: + if st.button("저장", key=f"esv_{idx}", type="primary", use_container_width=True): + st.session_state.df.at[idx,'평단가'] = np2 + st.session_state.df.at[idx,'수량'] = nq2 + st.session_state.df.at[idx,'매수근거'] = new_reason + st.session_state.df.at[idx,'매수일'] = new_date + save_assets() + st.session_state[f"edit_mode_{idx}"] = False; st.rerun() + st.markdown('
', unsafe_allow_html=True) + +elif st.session_state.main_menu == "📖 나의 매매 일지": + st.markdown("### 매매 복기록") + if st.session_state.trade_df.empty: + st.info("아직 기록된 매매 일지가 없습니다. 보유 자산 화면에서 매도 기록을 남겨보세요.") + else: + render_trade_analytics(st.session_state.trade_df) + st.divider() + st.markdown("### 매매 기록") + for _, log in st.session_state.trade_df.iterrows(): + ip = log['실현손익'] >= 0 + pnl_color = "#E0E0E0" if ip else "#9ABBE0" + fee_val = int(log.get('수수료', 0) or 0) + log_reason = str(log.get('매수근거', '') or '').strip() + reason_html = ( + f'
' + f'매수 근거  {log_reason}
' + ) if log_reason else '' + st.markdown( + f'
' + f'
' + f'
{log["종목명"]}' + f'{log["일시"]}
' + f'
' + f'{("+" if ip else "")}{int(log["실현손익"]):,}원
' + f'
' + f'{log["구분"]}가 {int(log["매매가"]):,}원 · {log["수량"]}주' + f'{f" · 수수료 {fee_val:,}원" if fee_val > 0 else ""}
' + f'
' + f'{log["태그"]}' + f'{log["메모"]}
' + f'{reason_html}
', + unsafe_allow_html=True + ) + +elif st.session_state.main_menu == "★ 관심 종목": + st.markdown("### 관심 종목") + st.markdown( + '

스캔 또는 자산 상세에서 관심종목으로 추가한 종목입니다.

', + unsafe_allow_html=True + ) + st.divider() + if st.session_state.fav_df.empty: + st.info("등록된 관심 종목이 없습니다.") + else: + prices = get_all_prices(); rate = get_exchange_rate() + cols = st.columns(3) + for i, row in st.session_state.fav_df.iterrows(): + t = row['티커']; n = row['종목명'] + p = int(prices.get(t,0)*rate) + sn = str(n)[:14]+".." if len(str(n))>14 else str(n) + with cols[i % 3]: + st.markdown('
', unsafe_allow_html=True) + if st.button(f"*{t}*\n**{sn}**\n~{p:,}원~", key=f"fav_btn_{i}", use_container_width=True): + st.session_state.active_ticker = t + st.session_state.main_menu = "⌂ 홈 & 스캔" + st.rerun() + +elif st.session_state.main_menu == "⚙ 시스템 설정": + st.markdown("### 시스템 설정") + + # ── 내 데이터 공간 정보 + h = _key_hash() + st.markdown(f""" +
+
+ 내 데이터 공간 +
+
+
+
+ users/{h}/ +
+
+
+ API 키 기반으로 격리된 개인 공간입니다. 타인과 데이터가 공유되지 않습니다. +
+
+ """, unsafe_allow_html=True) + + st.markdown('

GEMINI API KEY

', unsafe_allow_html=True) + nk = st.text_input("API KEY", value=st.session_state.api_key, type="password", label_visibility="collapsed") + + st.markdown('

분석 모델

', unsafe_allow_html=True) + nm = st.selectbox("모델", AVAILABLE_MODELS, label_visibility="collapsed", + index=AVAILABLE_MODELS.index(st.session_state.selected_model) + if st.session_state.selected_model in AVAILABLE_MODELS else 0) + + # ── ① 투자자 프로필 ───────────────────────────────────────── + st.markdown(""" +

투자자 프로필

+

+ AI가 이 설정을 기준으로 분석 성향·매수 기준·리스크 판단을 조정합니다. +

+ """, unsafe_allow_html=True) + + _cur_prof = st.session_state.get("investor_profile", dict(DEFAULT_INVESTOR_PROFILE)) + _style_opts = list(_PROFILE_STYLE_MAP.keys()) + _risk_opts = _RISK_LEVEL_LABELS + + _style_idx = _style_opts.index(_cur_prof.get("style", "중장기 성장주")) \ + if _cur_prof.get("style") in _style_opts else 0 + _risk_idx = _risk_opts.index(_cur_prof.get("risk_level", "중간~높음")) \ + if _cur_prof.get("risk_level") in _risk_opts else 2 + + pf1, pf2 = st.columns(2) + with pf1: + new_style = st.selectbox( + "투자 성향", + _style_opts, + index=_style_idx, + label_visibility="visible", + help="AI 분석의 기본 성향 기준이 됩니다." + ) + with pf2: + new_risk = st.selectbox( + "리스크 허용도", + _risk_opts, + index=_risk_idx, + label_visibility="visible", + help="낮을수록 방어적 조언, 높을수록 공격적 진입 기준을 제시합니다." + ) + + new_extra = st.text_area( + "추가 지침 (선택)", + value=_cur_prof.get("extra_notes", ""), + placeholder="예: 기술주 집중에 따른 리스크 헤지 조언 항상 포함 / 레버리지 ETF 제외 / 배당 수익률 2% 이상 종목 우선", + height=80, + label_visibility="visible", + help="AI에게 전달할 추가 지침을 자유롭게 입력하세요." + ) + + # 선택한 성향의 설명 미리보기 + _prev_sm = _PROFILE_STYLE_MAP.get(new_style, _PROFILE_STYLE_MAP["중장기 성장주"]) + st.markdown(f""" +
+
+ 프로필 미리보기 +
+
+ 성향 {_prev_sm['desc']}
+ 선호 {_prev_sm['preferred']}
+ 리스크 {new_risk} — {_prev_sm['risk_hint']} + {"
추가 " + new_extra if new_extra.strip() else ""} +
+
+ """, unsafe_allow_html=True) + + # ── ② 매매 설정 ──────────────────────────────────────────── + st.markdown('

매매 설정

', unsafe_allow_html=True) + sf1, sf2 = st.columns(2) + with sf1: + new_fee = st.number_input( + "매매 수수료율 (%)", value=st.session_state.fee_rate * 100, + min_value=0.0, max_value=1.0, step=0.001, format="%.3f", + ) + with sf2: + new_target = st.number_input( + "목표 수익률 (%)", value=st.session_state.target_return_pct, + min_value=1.0, max_value=500.0, step=1.0, + ) + + # ── ③ 데이터 관리 ────────────────────────────────────────── + st.markdown('

데이터 관리

', unsafe_allow_html=True) + c1, c2 = st.columns(2) + with c1: + if st.button("가격 캐시 초기화", use_container_width=True): + st.session_state.price_cache_ts = 0 + st.success("가격 캐시가 초기화되었습니다.") + with c2: + if st.button("분석 캐시 초기화", use_container_width=True): + st.session_state.full_stock_reports = {} + st.session_state.p_diag_res = None + save_cache() + st.success("분석 캐시가 초기화되었습니다.") + + # ── ④ 설정 저장 ──────────────────────────────────────────── + st.write("") + if st.button("설정 저장", type="primary", use_container_width=True): + prev_key = st.session_state.api_key + st.session_state.api_key = nk + st.session_state.selected_model = nm + st.session_state.fee_rate = new_fee / 100 + st.session_state.target_return_pct = new_target + st.session_state.investor_profile = { + "style": new_style, + "risk_level": new_risk, + "extra_notes": new_extra.strip(), + } + genai.configure(api_key=nk) + save_settings() # ← 투자자 프로필 + 앱 설정 HF 저장 + + # API 키가 바뀌면 다른 사용자 공간 → 데이터 전부 재로드 + if nk != prev_key: + for k in ['df','fav_df','trade_df','full_stock_reports','portfolio_history', + 'report_history','p_diag_res','price_cache','price_cache_ts', + 'investor_profile']: + st.session_state.pop(k, None) + st.success("API 키가 변경되었습니다. 해당 키의 데이터를 불러옵니다...") + else: + st.success("설정이 저장되었습니다.") + time.sleep(0.5); st.rerun() + +# ── 숨김 트리거 버튼 +_trigger_key = f"hidden_alert_btn_{st.session_state.get('main_menu','home')}" +st.button("alert_trigger", key=_trigger_key, help="alert_trigger_btn", on_click=lambda: None) + +components.html(""" + + + +""", height=1) + + +# ────────────────────────────────────────────────────────────────── +# 하단 네비게이션 바 +# ────────────────────────────────────────────────────────────────── +st.markdown('', unsafe_allow_html=True) + +# ── 메뉴 드로어 (show_menu=True 일 때) ── +ALL_MENUS = [ + ("⌂ 홈 & 스캔", "⌂ 홈 & AI 스캔"), + ("▤ 자산 상세 진단", "▤ 자산 상세 진단"), + ("📖 나의 매매 일지", "📖 나의 매매 일지"), + ("★ 관심 종목", "★ 관심 종목"), + ("⚙ 시스템 설정", "⚙ 시스템 설정"), +] + +if st.session_state.get("show_menu", False): + st.markdown('', unsafe_allow_html=True) + for menu_key, label in ALL_MENUS: + active = st.session_state.main_menu == menu_key + btn_label = f"**{label}**" if active else label + if st.button(btn_label, key=f"drawer_{menu_key}", use_container_width=True): + select_menu(menu_key) + st.rerun() + +# ── 네비게이션 바 3개 버튼 ── +nb_left, nb_mid, nb_right = st.columns(3) + +with nb_left: + menu_icon = "*☰*\n**메뉴**" if st.session_state.get("show_menu") else "*☰*\n메뉴" + if st.button(menu_icon, key="nav_menu", use_container_width=True): + toggle_menu() + st.rerun() + +with nb_mid: + is_home = st.session_state.main_menu == "⌂ 홈 & 스캔" + home_label = "*⌂*\n**홈**" if is_home else "*⌂*\n홈" + if st.button(home_label, key="nav_home", use_container_width=True): + go_home() + st.rerun() + +with nb_right: + if st.button("*←*\n뒤로", key="nav_back", use_container_width=True): + go_back() + st.rerun() \ No newline at end of file