Spaces:
Runtime error

ditgun commited on
Commit
3120bce
Β·
verified Β·
1 Parent(s): fdff697

Update src/app.py

Browse files
Files changed (1) hide show
  1. src/app.py +109 -44
src/app.py CHANGED
@@ -785,13 +785,16 @@ FAV_FILE = "my_fav_v30.csv"
785
  TRADE_FILE = "my_trades_v30.csv"
786
 
787
  # μƒˆ λ³΄μœ μ§„λ‹¨ κ΅¬μ‘°μ—μ„œ λ°˜λ“œμ‹œ μžˆμ–΄μ•Ό ν•  ν•„λ“œ
788
- _NEW_REPORT_FIELDS = {"thesis_validity", "action_analysis", "additional_buy_analysis", "target_remaining"}
 
 
 
 
789
 
790
  def _is_new_structure(report: dict) -> bool:
791
- """ꡬ ꡬ쑰(target_price, value_growth_analysis λ“±)인지 μƒˆ ꡬ쑰인지 νŒλ³„"""
792
  if not isinstance(report, dict):
793
  return False
794
- # μƒˆ ꡬ쑰 ν•„λ“œ 쀑 ν•˜λ‚˜λΌλ„ 있으면 μƒˆ ꡬ쑰둜 νŒμ •
795
  return bool(_NEW_REPORT_FIELDS & report.keys())
796
 
797
  def _hf_dl(fn):
@@ -1803,24 +1806,52 @@ def parse_target_prices(target_price_str):
1803
  pass
1804
  return sorted(set(result))
1805
 
1806
- def get_price_alert(action, current_price, target_price_str, avg_price):
1807
- if not target_price_str or target_price_str == "-": return None, None
1808
- prices = parse_target_prices(target_price_str)
1809
- if not prices: return None, None
1810
  action = str(action)
1811
- if "읡절" in action:
1812
- tp = min(prices)
1813
- ratio = current_price / tp if tp > 0 else 0
1814
- if ratio >= 1.0:
1815
- return 'tp_hit', f"읡절 λͺ©ν‘œκ°€ {tp:,}원 도달 Β· μ§€κΈˆ λ°”λ‘œ μ κ²€ν•˜μ„Έμš”"
1816
- elif ratio >= 0.95:
1817
- return 'tp', f"읡절 λͺ©ν‘œκ°€ {tp:,}μ›κΉŒμ§€ {tp-current_price:,}원 λ‚¨μŒ ({ratio*100:.1f}%)"
1818
- if "μ†μ ˆ" in action or ("보유" in action and current_price < avg_price):
1819
- sl = min(prices)
1820
- if sl > 0 and current_price <= sl:
1821
- return 'sl_broken', f"μ†μ ˆ λŒ€μ‘κ°€ {sl:,}원 μ΄νƒˆ Β· μ¦‰μ‹œ λŒ€μ‘ ν•„μš”"
1822
- elif sl > 0 and current_price <= sl * 1.05:
1823
- return 'sl', f"μ†μ ˆ λŒ€μ‘κ°€ {sl:,}원 κ·Όμ ‘ ({((current_price/sl)-1)*100:+.1f}%)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1824
  return None, None
1825
 
1826
  def render_price_alert(level, message, ticker, name):
@@ -1939,9 +1970,16 @@ def _build_alert_groups(prices, rate):
1939
 
1940
  rp = st.session_state.full_stock_reports.get(f"{t}_{ap}", {}).get("report", {})
1941
  act = rp.get("action_type", "")
1942
- # 보유 진단 리포트 κ΅¬μ‘°μ—μ„œ λͺ©ν‘œκ°€ μΆ”μΆœ
1943
- target_rem = rp.get("target_remaining", {})
1944
- tgp = target_rem.get("target_price", "-") if isinstance(target_rem, dict) else rp.get("target_price", "-")
 
 
 
 
 
 
 
1945
 
1946
  if abs(daily_pct) >= 5.0:
1947
  groups["κΈ‰λ³€"].append(dict(
@@ -1954,12 +1992,17 @@ def _build_alert_groups(prices, rate):
1954
  if not act:
1955
  continue
1956
 
 
 
 
 
 
1957
  item_strat = dict(
1958
  ticker=t, name=nm, change_pct=total_pct,
1959
  current_price=int(ck), avg_price=int(ap),
1960
  target_price=tgp, action=act
1961
  )
1962
- if "μ†μ ˆ" in act:
1963
  groups["μŠ€ν†±λ‘œμŠ€"].append(item_strat)
1964
  elif "읡절" in act:
1965
  groups["읡절"].append(item_strat)
@@ -2406,17 +2449,32 @@ elif st.session_state.main_menu == "βŒ‚ ν™ˆ & μŠ€μΊ”":
2406
  else: st.session_state.fav_df = pd.concat([st.session_state.fav_df, pd.DataFrame([{"티컀":tn,"μ’…λͺ©λͺ…":n}])], ignore_index=True)
2407
  save_fav(); st.rerun()
2408
 
2409
- bypass = st.session_state.pop('force_home_refresh', False)
2410
- with st.spinner(f"{n} 쀑μž₯κΈ° μ„±μž₯μ£Ό μŠ€μΊ” 쀑..."):
2411
- fin_ctx, has_rich = get_rich_financial_context(tn)
2412
- news_ctx = get_recent_news(tn)
2413
- owned_list = st.session_state.df['티컀'].tolist() if not st.session_state.df.empty else []
2414
- target_info = f"μ’…λͺ©: {n}({tn})\nν˜„μž¬κ°€: {p:,}원\n[μ‹€μ œ 재무 데이터]\n{fin_ctx}"
2415
- report = get_ai_json_response(
2416
- get_scan_prompt(target_info, tid=tn, owned=owned_list, news=news_ctx),
2417
- bypass_cache=bypass
2418
- )
2419
- stars = report.get("recommendation_stars","β˜…β˜…β˜…β˜…β˜†") if report else "β˜…β˜…β˜…β˜…β˜†"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2420
 
2421
  render_stock_header(n, tn, p, stars, "쀑μž₯κΈ° μ„±μž₯μ£Ό μŠ€μΊ”", has_rich)
2422
  tp = get_analyst_target(tn)
@@ -2661,24 +2719,27 @@ elif st.session_state.main_menu == "β–€ μžμ‚° 상세 진단":
2661
  prg.text("포트폴리였 λ™μ‹œ μŠ€μΊ” 및 재무 데이터 μˆ˜μ§‘ 쀑...")
2662
  asset_list = []
2663
 
2664
- # μ„Ήν„° 집계 & 베타 집계
2665
  sector_summary = {}
2666
- beta_info = {}
 
2667
 
2668
  def _analyze(row):
2669
  t = row['티컀']; ap = row['평단가']
2670
  key = f"{t}_{ap}"
2671
- st2 = st.session_state.full_stock_reports.get(key, {})
2672
- needs2 = st2.get("date") != today_str or st2.get("avg_price") != ap
2673
  ni, pi, ci = get_ticker_info(t)
2674
  sec, beta = get_ticker_metadata(t)
2675
  ck = int(pi)
2676
  pct = ((ck/ap)-1)*100 if ap>0 else 0
2677
  buy_reason = str(row.get('맀수근거', '') or '').strip()
2678
 
2679
- # μ„Ήν„°/베타 집계 (μŠ€λ ˆλ“œ μ•ˆμ „ν•˜μ§€ μ•Šμ§€λ§Œ μ†Œκ·œλͺ¨λΌ ν—ˆμš©)
2680
- sector_summary[sec] = sector_summary.get(sec, 0) + 1
2681
- beta_info[t] = round(beta, 2)
 
 
 
 
2682
 
2683
  if needs2:
2684
  fc, _ = get_rich_financial_context(t)
@@ -2693,12 +2754,16 @@ elif st.session_state.main_menu == "β–€ μžμ‚° 상세 진단":
2693
  bypass_cache=True
2694
  )
2695
  if rp and "action_type" in rp:
2696
- st.session_state.full_stock_reports[key] = {"date":today_str,"report":rp,"avg_price":ap}
 
 
 
 
2697
  act = rp.get("action_type","보유")
2698
  return f"- {row['μ’…λͺ©λͺ…']}({t}) [μ„Ήν„°:{sec}/Beta:{beta:.2f}]: 수읡λ₯ {pct:.1f}%, [μ „λž΅:{act}]"
2699
  return f"- {row['μ’…λͺ©λͺ…']}({t}): 수읡λ₯ {pct:.1f}%"
2700
  else:
2701
- act = st2['report'].get('action_type','보유')
2702
  return f"- {row['μ’…λͺ©λͺ…']}({t}) [μ„Ήν„°:{sec}/Beta:{beta:.2f}]: 수읡λ₯ {pct:.1f}%, [μ „λž΅:{act}]"
2703
 
2704
  ctx = get_script_run_ctx()
 
785
  TRADE_FILE = "my_trades_v30.csv"
786
 
787
  # μƒˆ λ³΄μœ μ§„λ‹¨ κ΅¬μ‘°μ—μ„œ λ°˜λ“œμ‹œ μžˆμ–΄μ•Ό ν•  ν•„λ“œ
788
+ # 보유 진단 μƒˆ ꡬ쑰 ν•„λ“œ
789
+ _OWNED_NEW_FIELDS = {"thesis_validity", "action_analysis", "additional_buy_analysis", "target_remaining"}
790
+ # μ‹ κ·œ μŠ€μΊ” μƒˆ ꡬ쑰 ν•„λ“œ
791
+ _SCAN_NEW_FIELDS = {"growth_moat_quantitative", "growth_moat_qualitative", "catalyst", "entry_zones"}
792
+ _NEW_REPORT_FIELDS = _OWNED_NEW_FIELDS | _SCAN_NEW_FIELDS
793
 
794
  def _is_new_structure(report: dict) -> bool:
795
+ """ꡬ ꡬ쑰인지 μƒˆ ꡬ쑰인지 νŒλ³„ β€” λ³΄μœ μ§„λ‹¨/μŠ€μΊ” ν•„λ“œ λͺ¨λ‘ 포함"""
796
  if not isinstance(report, dict):
797
  return False
 
798
  return bool(_NEW_REPORT_FIELDS & report.keys())
799
 
800
  def _hf_dl(fn):
 
1806
  pass
1807
  return sorted(set(result))
1808
 
1809
+ def get_price_alert(action, current_price, target_price_str, avg_price, report=None):
 
 
 
1810
  action = str(action)
1811
+ report = report or {}
1812
+
1813
+ # 읡절 μ•ŒλžŒ: target_remaining.target_price κΈ°μ€€
1814
+ if "읡절" in action and target_price_str and target_price_str != "-":
1815
+ prices = parse_target_prices(target_price_str)
1816
+ if prices:
1817
+ tp = min(prices)
1818
+ ratio = current_price / tp if tp > 0 else 0
1819
+ if ratio >= 1.0:
1820
+ return 'tp_hit', f"읡절 λͺ©ν‘œκ°€ {tp:,}원 도달 Β· μ§€κΈˆ λ°”λ‘œ μ κ²€ν•˜μ„Έμš”"
1821
+ elif ratio >= 0.95:
1822
+ return 'tp', f"읡절 λͺ©ν‘œκ°€ {tp:,}μ›κΉŒμ§€ {tp-current_price:,}원 λ‚¨μŒ ({ratio*100:.1f}%)"
1823
+
1824
+ # μ†μ ˆ μ•ŒλžŒ: ν…Œμ œ 훼손 νŒμ • μš°μ„ , μ—†μœΌλ©΄ 가격 κΈ°μ€€
1825
+ if "μ†μ ˆ" in action:
1826
+ thesis = report.get("thesis_validity", {})
1827
+ verdict = thesis.get("verdict", "") if isinstance(thesis, dict) else ""
1828
+ if verdict == "훼손":
1829
+ return 'sl_broken', "맀수 ν…Œμ œ 훼손 νŒμ • Β· μ†μ ˆ κ²€ν†  ν•„μš”"
1830
+ if target_price_str and target_price_str != "-":
1831
+ prices = parse_target_prices(target_price_str)
1832
+ if prices:
1833
+ sl = min(prices)
1834
+ if sl > 0 and current_price <= sl:
1835
+ return 'sl_broken', f"μ†μ ˆ λŒ€μ‘κ°€ {sl:,}원 μ΄νƒˆ Β· μ¦‰μ‹œ λŒ€μ‘ ν•„μš”"
1836
+ elif sl > 0 and current_price <= sl * 1.05:
1837
+ return 'sl', f"μ†μ ˆ λŒ€μ‘κ°€ {sl:,}원 κ·Όμ ‘ ({((current_price/sl)-1)*100:+.1f}%)"
1838
+
1839
+ # 보유 쀑 손싀 + ν…Œμ œ μ κ²€ν•„μš”
1840
+ if "보유" in action and current_price < avg_price:
1841
+ thesis = report.get("thesis_validity", {})
1842
+ verdict = thesis.get("verdict", "") if isinstance(thesis, dict) else ""
1843
+ if verdict == "μ κ²€ν•„μš”":
1844
+ loss_pct = (current_price / avg_price - 1) * 100
1845
+ return 'sl', f"ν…Œμ œ μ κ²€ν•„μš” + 손싀 쀑 ({loss_pct:+.1f}%) Β· μž¬μ§„λ‹¨ ꢌμž₯"
1846
+ if target_price_str and target_price_str != "-":
1847
+ prices = parse_target_prices(target_price_str)
1848
+ if prices:
1849
+ sl = min(prices)
1850
+ if sl > 0 and current_price <= sl:
1851
+ return 'sl_broken', f"μ†μ ˆ λŒ€μ‘κ°€ {sl:,}원 μ΄νƒˆ Β· μ¦‰μ‹œ λŒ€μ‘ ν•„μš”"
1852
+ elif sl > 0 and current_price <= sl * 1.05:
1853
+ return 'sl', f"μ†μ ˆ λŒ€μ‘κ°€ {sl:,}원 κ·Όμ ‘ ({((current_price/sl)-1)*100:+.1f}%)"
1854
+
1855
  return None, None
1856
 
1857
  def render_price_alert(level, message, ticker, name):
 
1970
 
1971
  rp = st.session_state.full_stock_reports.get(f"{t}_{ap}", {}).get("report", {})
1972
  act = rp.get("action_type", "")
1973
+
1974
+ # ── λͺ©ν‘œκ°€ μΆ”μΆœ: μƒˆ ꡬ쑰(target_remaining) μš°μ„ , μΆ”κ°€λ§€μˆ˜κ°€ fallback ──
1975
+ target_rem = rp.get("target_remaining", {})
1976
+ add_buy = rp.get("additional_buy_analysis", {})
1977
+ if isinstance(target_rem, dict) and target_rem.get("target_price", "-") not in ("-", "", None):
1978
+ tgp = target_rem["target_price"] # μƒˆ ꡬ쑰 λͺ©ν‘œκ°€
1979
+ elif isinstance(add_buy, dict) and add_buy.get("suggested_price", "-") not in ("-", "", None):
1980
+ tgp = add_buy["suggested_price"] # μΆ”κ°€λ§€μˆ˜ 적정가 fallback
1981
+ else:
1982
+ tgp = "-" # 뢄석 μ „ λ˜λŠ” 미기둝
1983
 
1984
  if abs(daily_pct) >= 5.0:
1985
  groups["κΈ‰λ³€"].append(dict(
 
1992
  if not act:
1993
  continue
1994
 
1995
+ # ν…Œμ œ 훼손 μ—¬λΆ€ 확인 β€” action이 "보유"여도 μŠ€ν†±λ‘œμŠ€ 그룹으둜
1996
+ thesis = rp.get("thesis_validity", {})
1997
+ verdict = thesis.get("verdict", "") if isinstance(thesis, dict) else ""
1998
+ thesis_broken = (verdict == "훼손")
1999
+
2000
  item_strat = dict(
2001
  ticker=t, name=nm, change_pct=total_pct,
2002
  current_price=int(ck), avg_price=int(ap),
2003
  target_price=tgp, action=act
2004
  )
2005
+ if "μ†μ ˆ" in act or thesis_broken:
2006
  groups["μŠ€ν†±λ‘œμŠ€"].append(item_strat)
2007
  elif "읡절" in act:
2008
  groups["읡절"].append(item_strat)
 
2449
  else: st.session_state.fav_df = pd.concat([st.session_state.fav_df, pd.DataFrame([{"티컀":tn,"μ’…λͺ©λͺ…":n}])], ignore_index=True)
2450
  save_fav(); st.rerun()
2451
 
2452
+ bypass = st.session_state.pop('force_home_refresh', False)
2453
+ scan_key = f"scan_{tn}"
2454
+ stored_scan = st.session_state.full_stock_reports.get(scan_key, {})
2455
+ # 당일 μΊμ‹œ 유효 μ—¬λΆ€: λ‚ μ§œ κ°™κ³  κ°•μ œ μƒˆλ‘œκ³ μΉ¨ 아닐 λ•Œ
2456
+ needs_scan = bypass or stored_scan.get("date") != today_str
2457
+
2458
+ if needs_scan:
2459
+ with st.spinner(f"{n} 쀑μž₯κΈ° μ„±μž₯μ£Ό μŠ€μΊ” 쀑..."):
2460
+ fin_ctx, has_rich = get_rich_financial_context(tn)
2461
+ news_ctx = get_recent_news(tn)
2462
+ owned_list = st.session_state.df['티컀'].tolist() if not st.session_state.df.empty else []
2463
+ target_info = f"μ’…λͺ©: {n}({tn})\nν˜„μž¬κ°€: {p:,}원\n[μ‹€μ œ 재무 데이터]\n{fin_ctx}"
2464
+ report = get_ai_json_response(
2465
+ get_scan_prompt(target_info, tid=tn, owned=owned_list, news=news_ctx),
2466
+ bypass_cache=True
2467
+ )
2468
+ if report:
2469
+ st.session_state.full_stock_reports[scan_key] = {
2470
+ "date": today_str, "report": report, "avg_price": 0
2471
+ }
2472
+ save_cache()
2473
+ else:
2474
+ report = stored_scan["report"]
2475
+ has_rich = True
2476
+
2477
+ stars = report.get("recommendation_stars","β˜…β˜…β˜…β˜…β˜†") if report else "β˜…β˜…β˜…β˜…β˜†"
2478
 
2479
  render_stock_header(n, tn, p, stars, "쀑μž₯κΈ° μ„±μž₯μ£Ό μŠ€μΊ”", has_rich)
2480
  tp = get_analyst_target(tn)
 
2719
  prg.text("포트폴리였 λ™μ‹œ μŠ€μΊ” 및 재무 데이터 μˆ˜μ§‘ 쀑...")
2720
  asset_list = []
2721
 
2722
+ # μ„Ήν„° 집계 & 베타 집계 β€” μŠ€λ ˆλ“œ μ•ˆμ „ Lock μ‚¬μš©
2723
  sector_summary = {}
2724
+ beta_info = {}
2725
+ _shared_lock = threading.Lock()
2726
 
2727
  def _analyze(row):
2728
  t = row['티컀']; ap = row['평단가']
2729
  key = f"{t}_{ap}"
 
 
2730
  ni, pi, ci = get_ticker_info(t)
2731
  sec, beta = get_ticker_metadata(t)
2732
  ck = int(pi)
2733
  pct = ((ck/ap)-1)*100 if ap>0 else 0
2734
  buy_reason = str(row.get('맀수근거', '') or '').strip()
2735
 
2736
+ # ── 곡유 λ”•μ…”λ„ˆλ¦¬ μ“°κΈ°: Lock으둜 보호 ──────────────
2737
+ with _shared_lock:
2738
+ sector_summary[sec] = sector_summary.get(sec, 0) + 1
2739
+ beta_info[t] = round(beta, 2)
2740
+ cached = st.session_state.full_stock_reports.get(key, {})
2741
+
2742
+ needs2 = cached.get("date") != today_str or cached.get("avg_price") != ap
2743
 
2744
  if needs2:
2745
  fc, _ = get_rich_financial_context(t)
 
2754
  bypass_cache=True
2755
  )
2756
  if rp and "action_type" in rp:
2757
+ # ── μΊμ‹œ 쓰기도 Lock 보호 ────────────────────
2758
+ with _shared_lock:
2759
+ st.session_state.full_stock_reports[key] = {
2760
+ "date": today_str, "report": rp, "avg_price": ap
2761
+ }
2762
  act = rp.get("action_type","보유")
2763
  return f"- {row['μ’…λͺ©λͺ…']}({t}) [μ„Ήν„°:{sec}/Beta:{beta:.2f}]: 수읡λ₯ {pct:.1f}%, [μ „λž΅:{act}]"
2764
  return f"- {row['μ’…λͺ©λͺ…']}({t}): 수읡λ₯ {pct:.1f}%"
2765
  else:
2766
+ act = cached.get('report', {}).get('action_type','보유')
2767
  return f"- {row['μ’…λͺ©λͺ…']}({t}) [μ„Ήν„°:{sec}/Beta:{beta:.2f}]: 수읡λ₯ {pct:.1f}%, [μ „λž΅:{act}]"
2768
 
2769
  ctx = get_script_run_ctx()