Spaces:
Sleeping
Sleeping
Update streamlit_app.py
Browse files- streamlit_app.py +195 -168
streamlit_app.py
CHANGED
|
@@ -20,81 +20,131 @@ else:
|
|
| 20 |
st.stop()
|
| 21 |
|
| 22 |
# ==============================================================================
|
| 23 |
-
#
|
| 24 |
# ==============================================================================
|
| 25 |
-
def
|
| 26 |
"""
|
| 27 |
-
|
| 28 |
"""
|
| 29 |
try:
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
except:
|
|
|
|
| 54 |
|
| 55 |
# ==============================================================================
|
| 56 |
-
# ๐ ๏ธ [ํต์ฌ ์์ง
|
| 57 |
# ==============================================================================
|
| 58 |
-
def
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
# 2. FDR (Yahoo ์คํจ ์)
|
| 67 |
try:
|
| 68 |
fdr_symbol = ticker
|
| 69 |
-
if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
|
| 70 |
-
elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
|
| 71 |
-
elif ".
|
| 72 |
|
| 73 |
-
|
| 74 |
-
hist = fdr.DataReader(fdr_symbol, start)
|
| 75 |
if not hist.empty:
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
| 78 |
except: pass
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
|
|
|
| 81 |
def get_news(keyword):
|
| 82 |
summary = ""
|
| 83 |
try:
|
| 84 |
with DDGS() as ddgs:
|
| 85 |
results = ddgs.news(keyword, timelimit="m", max_results=5)
|
| 86 |
-
for r in results:
|
| 87 |
-
summary += f"[{r.get('date','?')}] {r['title']}\n"
|
| 88 |
return summary if summary else "No recent news."
|
| 89 |
-
except: return "
|
| 90 |
|
| 91 |
def parse_stream(stream):
|
| 92 |
for chunk in stream:
|
| 93 |
if chunk.choices: yield chunk.choices[0].delta.content or ""
|
| 94 |
|
| 95 |
-
#
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
def plot_candle_chart(hist, title, source):
|
| 99 |
fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
|
| 100 |
fig.update_layout(title=f"{title} ({source})", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
|
|
@@ -107,13 +157,14 @@ def plot_bar_chart(df):
|
|
| 107 |
return fig
|
| 108 |
|
| 109 |
# ==============================================================================
|
| 110 |
-
# ๐พ [๋ฐ์ดํฐ]
|
| 111 |
# ==============================================================================
|
|
|
|
| 112 |
TICKER_NAMES = {
|
| 113 |
"AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
|
| 114 |
"005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "207940.KS": "Samsung Bio",
|
| 115 |
-
"VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VNM.VN": "Vinamilk", "VCB.VN": "Vietcombank",
|
| 116 |
-
"BBCA.JK": "BCA", "BBRI.JK": "BRI", "GOTO.JK": "GoTo",
|
| 117 |
"7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank",
|
| 118 |
"9988.HK": "Alibaba", "0700.HK": "Tencent", "2330.TW": "TSMC",
|
| 119 |
"RELIANCE.NS": "Reliance", "TCS.NS": "TCS"
|
|
@@ -122,148 +173,124 @@ TICKER_NAMES = {
|
|
| 122 |
MARKET_SAMPLES = {
|
| 123 |
"๐ป๐ณ ๋ฒ ํธ๋จ (Vietnam)": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN"],
|
| 124 |
"๐ฎ๐ฉ ์ธ๋๋ค์์": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
|
| 125 |
-
"๐ฐ๐ท ํ๊ตญ (Korea)": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "207940.KS"
|
| 126 |
-
"๐บ๐ธ ๋ฏธ๊ตญ (USA)": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD"
|
| 127 |
-
"๐ฏ๐ต ์ผ๋ณธ (Japan)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T"
|
| 128 |
-
"๐จ๐ณ ์ค๊ตญ/ํ์ฝฉ": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK"
|
| 129 |
-
"๐น๐ผ ๋๋ง (Taiwan)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW"
|
| 130 |
-
"๐ฎ๐ณ ์ธ๋ (India)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS"
|
| 131 |
-
"๐ธ๐ฌ ์ฑ๊ฐํฌ๋ฅด": ["D05.SI", "O39.SI", "U11.SI", "Z74.SI"],
|
| 132 |
-
"๐ฒ๐พ ๋ง๋ ์ด์์": ["1155.KL", "1023.KL", "1295.KL"],
|
| 133 |
-
"๐น๐ญ ํ๊ตญ": ["PTT.BK", "AOT.BK", "CPALL.BK"]
|
| 134 |
}
|
| 135 |
|
| 136 |
# ==============================================================================
|
| 137 |
-
# ๐ฅ๏ธ
|
| 138 |
# ==============================================================================
|
| 139 |
with st.sidebar:
|
| 140 |
st.title("๐ง Pocket Quant AI")
|
| 141 |
st.divider()
|
| 142 |
-
# ๋ฉ๋ด ๋ถํ!
|
| 143 |
menu = st.radio("MENU", ["๐ AI ์ค๋งํธ ๊ฒ์", "๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋"], index=0)
|
| 144 |
-
st.divider()
|
| 145 |
-
st.caption("Auto-Detect & Multi-Source")
|
| 146 |
|
| 147 |
-
# ------
|
| 148 |
-
# ๋ชจ๋ 1: AI ์ค๋งํธ ๊ฒ์ (๊ฐ๋ก๊ฐ์ด ๋งํด๋ ์ฐฐ๋ก๊ฐ์ด)
|
| 149 |
-
# ------------------------------------------------------------------------------
|
| 150 |
if menu == "๐ AI ์ค๋งํธ ๊ฒ์":
|
| 151 |
-
st.subheader("๐ง ๋ฌด์์ด๋ ๋ฌผ์ด๋ณด์ธ์
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
with col1:
|
| 156 |
-
user_query = st.text_input("๊ฒ์์ด ์
๋ ฅ", "๋น๋๋ฐํฌ", label_visibility="collapsed")
|
| 157 |
-
with col2:
|
| 158 |
-
btn = st.button("๋ถ์ ์คํ", use_container_width=True)
|
| 159 |
|
| 160 |
if btn:
|
| 161 |
-
with st.status("๐ง AI๊ฐ
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
if target_info:
|
| 167 |
-
name = target_info.get('name', 'Unknown')
|
| 168 |
-
ticker = target_info.get('ticker', '')
|
| 169 |
-
keyword = target_info.get('search_keyword', '')
|
| 170 |
|
| 171 |
-
|
|
|
|
| 172 |
|
| 173 |
-
# 2. ๋ฐ์ดํฐ ์์ง
|
| 174 |
-
st.write("๐ ์์ฅ ๋ฐ์ดํฐ ์์ง ์ค...")
|
| 175 |
-
hist, src = get_market_data(ticker)
|
| 176 |
-
|
| 177 |
-
st.write("๐ฐ ๊ธ๋ก๋ฒ ๋ด์ค ์์ง ์ค...")
|
| 178 |
-
news_data = get_news(keyword)
|
| 179 |
-
|
| 180 |
-
# ๋ฐ์ดํฐ ์ ๋ฆฌ
|
| 181 |
curr, pct = "N/A", 0
|
| 182 |
-
if not
|
| 183 |
-
curr =
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
status.update(label="โ
๋ถ์ ์๋ฃ!", state="complete", expanded=False)
|
| 187 |
else:
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
st.divider()
|
| 191 |
-
|
| 192 |
-
# ์๊ฐํ
|
| 193 |
m1, m2 = st.columns(2)
|
| 194 |
-
m1.metric("
|
| 195 |
m2.metric("Source", src)
|
| 196 |
|
| 197 |
-
if not
|
| 198 |
-
|
| 199 |
-
else:
|
| 200 |
-
st.warning("์ฐจํธ ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ฌ ์ ์์ต๋๋ค.")
|
| 201 |
-
|
| 202 |
-
with st.expander("๐ฐ ๋ด์ค ์๋ฌธ ๋ณด๊ธฐ"):
|
| 203 |
-
st.text(news_data)
|
| 204 |
|
| 205 |
-
|
| 206 |
-
st.subheader(f"๐ง AI Insight: {name}")
|
| 207 |
-
prompt = f"""
|
| 208 |
-
[ROLE] Global Analyst.
|
| 209 |
-
[TARGET] {name} ({ticker})
|
| 210 |
-
[QUERY] "{user_query}"
|
| 211 |
-
[DATA] Price: {curr}, Trend: {pct:.2f}%
|
| 212 |
-
[NEWS] {news_data}
|
| 213 |
-
[TASK] Analyze sentiment and provide investment verdict.
|
| 214 |
-
[LANG] Korean.
|
| 215 |
-
"""
|
| 216 |
-
messages = [{"role": "user", "content": prompt}]
|
| 217 |
-
stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, stream=True)
|
| 218 |
-
st.write_stream(parse_stream(stream))
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
-
# ------
|
| 225 |
-
# ๋ชจ๋ 2: ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋ (Top 10 ๋ฑ๋ฝ๋ฅ ) - ๋ณต๊ตฌ ์๋ฃ!
|
| 226 |
-
# ------------------------------------------------------------------------------
|
| 227 |
elif menu == "๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋":
|
| 228 |
-
st.subheader("๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ ๊ดํ (
|
|
|
|
| 229 |
|
| 230 |
c1, c2 = st.columns([3, 1])
|
| 231 |
-
with c1:
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
results = []
|
| 240 |
-
progress = st.progress(0)
|
| 241 |
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
h, s = get_market_data(t)
|
| 245 |
-
if not h.empty:
|
| 246 |
-
last = h['Close'].iloc[-1]
|
| 247 |
-
prev = h['Close'].iloc[-2]
|
| 248 |
-
pct = ((last - prev)/prev)*100
|
| 249 |
-
# ์ด๋ฆํ ๋ถ์ด๊ธฐ
|
| 250 |
-
name = TICKER_NAMES.get(t, t)
|
| 251 |
-
results.append({'Name': name, 'Price': last, 'Change(%)': pct})
|
| 252 |
-
progress.progress((i+1)/len(tickers))
|
| 253 |
|
| 254 |
-
if
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
with col_up:
|
| 263 |
-
st.success("๐ฅ ๊ธ๋ฑ Top 10")
|
| 264 |
-
st.dataframe(df.head(10).style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
|
| 265 |
-
with col_down:
|
| 266 |
-
st.error("๐ง ๊ธ๋ฝ Top 10")
|
| 267 |
-
st.dataframe(df.tail(10).sort_values('Change(%)').style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
|
| 268 |
else:
|
| 269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
st.stop()
|
| 21 |
|
| 22 |
# ==============================================================================
|
| 23 |
+
# ๐ต๏ธ [์์กด ๊ธฐ์ ] ์น ๊ฒ์์ผ๋ก ๊ฐ๊ฒฉ ๊ฐ์ ์ถ์ถ (Last Resort)
|
| 24 |
# ==============================================================================
|
| 25 |
+
def scrape_price_from_web(name, ticker):
|
| 26 |
"""
|
| 27 |
+
์ผํ/FDR ๋ชจ๋ ์คํจํ์ ๋, ๊ฒ์ ์์ง์ ๋๋ ค์ ๊ฐ๊ฒฉ์ ํ
์คํธ์์ ๋ฏ์ด๋.
|
| 28 |
"""
|
| 29 |
try:
|
| 30 |
+
with DDGS() as ddgs:
|
| 31 |
+
# ๊ฒ์์ด: "Vinamilk stock price today"
|
| 32 |
+
query = f"{name} {ticker} stock price quote today"
|
| 33 |
+
results = ddgs.text(query, max_results=3)
|
| 34 |
+
|
| 35 |
+
# ๊ฒ์ ๊ฒฐ๊ณผ ํ
์คํธ ํฉ์น๊ธฐ
|
| 36 |
+
text_blob = " ".join([r['body'] for r in results])
|
| 37 |
+
|
| 38 |
+
# ์ ๊ทํํ์์ผ๋ก ์ซ์ ์ฐพ๊ธฐ (๊ฐ๋จํ ๋ก์ง)
|
| 39 |
+
# ์: "trading at 45,000" ๋๋ "Price: 123.45"
|
| 40 |
+
# (์ ๋ฐ๋๋ AI๋ณด๋ค ๋ฎ์ง๋ง ์๋๋ฅผ ์ํด ์ ๊ท์ ์ฌ์ฉ)
|
| 41 |
+
# ๋ฒ ํธ๋จ ๋(VND) ๊ฐ์ ํฐ ์ซ์๋ ์์์ ์ซ์ ๋งค์นญ
|
| 42 |
+
match = re.search(r'(\d{1,3}(,\d{3})*(\.\d+)?)', text_blob)
|
| 43 |
+
|
| 44 |
+
if match:
|
| 45 |
+
price_str = match.group(0)
|
| 46 |
+
# ์ผํ ์ ๊ฑฐ ํ float ๋ณํ ์๋
|
| 47 |
+
try:
|
| 48 |
+
price = float(price_str.replace(",", ""))
|
| 49 |
+
return price, 0.0 # ๋ฑ๋ฝ๋ฅ ์ ์ฐพ๊ธฐ ์ด๋ ค์ฐ๋ฏ๋ก 0์ผ๋ก ๋
|
| 50 |
+
except: pass
|
| 51 |
+
|
| 52 |
+
return None, None
|
| 53 |
+
except:
|
| 54 |
+
return None, None
|
| 55 |
|
| 56 |
# ==============================================================================
|
| 57 |
+
# ๐ ๏ธ [ํต์ฌ ์์ง] 3๋จ๊ณ ๋ฐ์ดํฐ ์์ง (FDR -> Yahoo -> Web)
|
| 58 |
# ==============================================================================
|
| 59 |
+
def get_price_data_robust(ticker, name):
|
| 60 |
+
"""
|
| 61 |
+
1. FDR (Investing.com/Naver) -> ๋ฒ ํธ๋จ/ํ๊ตญ์ ๊ฐ๋ ฅ
|
| 62 |
+
2. Yahoo (๋ฏธ๊ตญ/์ผ๋ณธ์ ๊ฐ๋ ฅ)
|
| 63 |
+
3. Web Search (์ตํ์ ์๋จ)
|
| 64 |
+
"""
|
| 65 |
+
# [1๋จ๊ณ] FinanceDataReader (๋๋จ์/ํ๊ตญ ์ฐ์ )
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
fdr_symbol = ticker
|
| 68 |
+
if ".VN" in ticker: fdr_symbol = ticker.split('.')[0] # ๋ฒ ํธ๋จ (HOSE)
|
| 69 |
+
elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}" # ์ธ๋๋ค์์
|
| 70 |
+
elif ".KS" in ticker or ".KQ" in ticker: fdr_symbol = ticker.split('.')[0] # ํ๊ตญ
|
| 71 |
|
| 72 |
+
# ์ต๊ทผ 5์ผ์น๋ง ๊ฐ์ ธ์ด (์๋ ์ต์ ํ)
|
| 73 |
+
hist = fdr.DataReader(fdr_symbol, start=(datetime.datetime.now() - datetime.timedelta(days=10)))
|
| 74 |
if not hist.empty:
|
| 75 |
+
curr = hist['Close'].iloc[-1]
|
| 76 |
+
prev = hist['Close'].iloc[-2] if len(hist) > 1 else curr
|
| 77 |
+
pct = ((curr - prev)/prev)*100
|
| 78 |
+
return curr, pct, "FDR"
|
| 79 |
except: pass
|
| 80 |
+
|
| 81 |
+
# [2๋จ๊ณ] Yahoo Finance (๋ฏธ๊ตญ/์ผ๋ณธ ์ฐ์ )
|
| 82 |
+
try:
|
| 83 |
+
stock = yf.Ticker(ticker)
|
| 84 |
+
# fast_info๊ฐ ๋ ๋น ๋ฆ
|
| 85 |
+
price = stock.fast_info.last_price
|
| 86 |
+
prev = stock.fast_info.previous_close
|
| 87 |
+
if price and prev:
|
| 88 |
+
pct = ((price - prev)/prev)*100
|
| 89 |
+
return price, pct, "Yahoo"
|
| 90 |
+
except: pass
|
| 91 |
+
|
| 92 |
+
# [3๋จ๊ณ] ์ตํ์ ์๋จ: ์น ๊ฒ์ (Qwen์ด ์ํจ ๊ฒ์)
|
| 93 |
+
# ์ฐจํธ ๋ฐ์ดํฐ๋ ์์ง๋ง ์ค์บ๋ ๋น์นธ์ ์ฑ์์ผ ํจ
|
| 94 |
+
price, pct = scrape_price_from_web(name, ticker)
|
| 95 |
+
if price is not None:
|
| 96 |
+
return price, pct if pct else 0.0, "Web Search ๐ต๏ธ"
|
| 97 |
+
|
| 98 |
+
return None, None, "Fail"
|
| 99 |
+
|
| 100 |
+
# ==============================================================================
|
| 101 |
+
# ๐ง [์์ง 1] AI ์ง๋ฅํ ๊ฒ์
|
| 102 |
+
# ==============================================================================
|
| 103 |
+
def identify_target_with_ai(user_query):
|
| 104 |
+
try:
|
| 105 |
+
prompt = f"""
|
| 106 |
+
[ROLE] Financial Entity Resolver. [QUERY] "{user_query}"
|
| 107 |
+
[TASK] Identify company, ticker, and news keyword.
|
| 108 |
+
[OUTPUT JSON] {{ "name": "English Name", "ticker": "TICKER", "search_keyword": "Keyword" }}
|
| 109 |
+
"""
|
| 110 |
+
messages = [{"role": "user", "content": prompt}]
|
| 111 |
+
response = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=messages, max_tokens=150)
|
| 112 |
+
content = re.sub(r"```json|```", "", response.choices[0].message.content.strip()).strip()
|
| 113 |
+
return json.loads(content)
|
| 114 |
+
except: return None
|
| 115 |
|
| 116 |
+
# ๋ด์ค ๊ฒ์
|
| 117 |
def get_news(keyword):
|
| 118 |
summary = ""
|
| 119 |
try:
|
| 120 |
with DDGS() as ddgs:
|
| 121 |
results = ddgs.news(keyword, timelimit="m", max_results=5)
|
| 122 |
+
for r in results: summary += f"[{r.get('date','?')}] {r['title']}\n"
|
|
|
|
| 123 |
return summary if summary else "No recent news."
|
| 124 |
+
except: return "Search Error"
|
| 125 |
|
| 126 |
def parse_stream(stream):
|
| 127 |
for chunk in stream:
|
| 128 |
if chunk.choices: yield chunk.choices[0].delta.content or ""
|
| 129 |
|
| 130 |
+
# ์ฐจํธ (๋ถ์์ฉ)
|
| 131 |
+
def get_chart_data(ticker):
|
| 132 |
+
try:
|
| 133 |
+
fdr_symbol = ticker
|
| 134 |
+
if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
|
| 135 |
+
elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
|
| 136 |
+
start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
|
| 137 |
+
hist = fdr.DataReader(fdr_symbol, start)
|
| 138 |
+
if not hist.empty:
|
| 139 |
+
return hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low'}), "FDR"
|
| 140 |
+
except: pass
|
| 141 |
+
try:
|
| 142 |
+
hist = yf.Ticker(ticker).history(period="3mo")
|
| 143 |
+
if not hist.empty: return hist, "Yahoo"
|
| 144 |
+
except: pass
|
| 145 |
+
return pd.DataFrame(), "None"
|
| 146 |
+
|
| 147 |
+
# ์๊ฐํ ํจ์
|
| 148 |
def plot_candle_chart(hist, title, source):
|
| 149 |
fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
|
| 150 |
fig.update_layout(title=f"{title} ({source})", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
|
|
|
|
| 157 |
return fig
|
| 158 |
|
| 159 |
# ==============================================================================
|
| 160 |
+
# ๐พ [๋ฐ์ดํฐ]
|
| 161 |
# ==============================================================================
|
| 162 |
+
# ๋งคํ ๋ฐ์ดํฐ (์ค์บ๋ ํ์์ฉ)
|
| 163 |
TICKER_NAMES = {
|
| 164 |
"AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
|
| 165 |
"005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "207940.KS": "Samsung Bio",
|
| 166 |
+
"VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VNM.VN": "Vinamilk", "VCB.VN": "Vietcombank", "GAS.VN": "PV Gas",
|
| 167 |
+
"BBCA.JK": "BCA", "BBRI.JK": "BRI", "GOTO.JK": "GoTo", "ASII.JK": "Astra Intl",
|
| 168 |
"7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank",
|
| 169 |
"9988.HK": "Alibaba", "0700.HK": "Tencent", "2330.TW": "TSMC",
|
| 170 |
"RELIANCE.NS": "Reliance", "TCS.NS": "TCS"
|
|
|
|
| 173 |
MARKET_SAMPLES = {
|
| 174 |
"๐ป๐ณ ๋ฒ ํธ๋จ (Vietnam)": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN"],
|
| 175 |
"๐ฎ๐ฉ ์ธ๋๋ค์์": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
|
| 176 |
+
"๐ฐ๐ท ํ๊ตญ (Korea)": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "207940.KS"],
|
| 177 |
+
"๐บ๐ธ ๋ฏธ๊ตญ (USA)": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD"],
|
| 178 |
+
"๐ฏ๐ต ์ผ๋ณธ (Japan)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T"],
|
| 179 |
+
"๐จ๐ณ ์ค๊ตญ/ํ์ฝฉ": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK"],
|
| 180 |
+
"๐น๐ผ ๋๋ง (Taiwan)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW"],
|
| 181 |
+
"๐ฎ๐ณ ์ธ๋ (India)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS"]
|
|
|
|
|
|
|
|
|
|
| 182 |
}
|
| 183 |
|
| 184 |
# ==============================================================================
|
| 185 |
+
# ๐ฅ๏ธ UI
|
| 186 |
# ==============================================================================
|
| 187 |
with st.sidebar:
|
| 188 |
st.title("๐ง Pocket Quant AI")
|
| 189 |
st.divider()
|
|
|
|
| 190 |
menu = st.radio("MENU", ["๐ AI ์ค๋งํธ ๊ฒ์", "๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋"], index=0)
|
|
|
|
|
|
|
| 191 |
|
| 192 |
+
# --- 1. AI ์ค๋งํธ ๊ฒ์ ---
|
|
|
|
|
|
|
| 193 |
if menu == "๐ AI ์ค๋งํธ ๊ฒ์":
|
| 194 |
+
st.subheader("๐ง ๋ฌด์์ด๋ ๋ฌผ์ด๋ณด์ธ์")
|
| 195 |
+
c1, c2 = st.columns([3, 1])
|
| 196 |
+
with c1: query = st.text_input("๊ฒ์์ด", "๋ฒ ํธ๋จ ๋น๊ทธ๋ฃน", label_visibility="collapsed")
|
| 197 |
+
with c2: btn = st.button("๋ถ์", use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
if btn:
|
| 200 |
+
with st.status("๐ง AI ๊ฐ๋ ์ค...", expanded=True) as status:
|
| 201 |
+
info = identify_target_with_ai(query)
|
| 202 |
+
if info:
|
| 203 |
+
name, ticker, key = info.get('name'), info.get('ticker'), info.get('search_keyword')
|
| 204 |
+
st.info(f"ํ๊ฒ: **{name} ({ticker})** | ํค์๋: {key}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
|
| 206 |
+
h, src = get_chart_data(ticker) # ์ฐจํธ์ฉ ๋ฐ์ดํฐ
|
| 207 |
+
news = get_news(key)
|
| 208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
curr, pct = "N/A", 0
|
| 210 |
+
if not h.empty:
|
| 211 |
+
curr = h['Close'].iloc[-1]
|
| 212 |
+
pct = ((curr - h['Close'].iloc[-2])/h['Close'].iloc[-2])*100
|
| 213 |
+
status.update(label="โ
๋ถ์ ์๋ฃ", state="complete", expanded=False)
|
|
|
|
| 214 |
else:
|
| 215 |
+
# ์ฐจํธ ์์ผ๋ฉด ์น ๊ฒ์ ์๋
|
| 216 |
+
c_web, p_web, s_web = get_price_data_robust(ticker, name)
|
| 217 |
+
if c_web:
|
| 218 |
+
curr, pct, src = c_web, p_web, s_web
|
| 219 |
+
status.update(label="โ ๏ธ ์ฐจํธ ์์ (์น ๋ฐ์ดํฐ ์ฌ์ฉ)", state="complete", expanded=False)
|
| 220 |
+
else:
|
| 221 |
+
status.update(label="โ ๋ฐ์ดํฐ ์์", state="complete", expanded=False)
|
| 222 |
|
| 223 |
st.divider()
|
|
|
|
|
|
|
| 224 |
m1, m2 = st.columns(2)
|
| 225 |
+
m1.metric("Price", f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
|
| 226 |
m2.metric("Source", src)
|
| 227 |
|
| 228 |
+
if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
|
| 229 |
+
else: st.warning(f"์ฐจํธ๋ฅผ ๊ทธ๋ฆด ์ ์์ต๋๋ค. (Source: {src})")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
+
with st.expander("๋ด์ค ๋ณด๊ธฐ"): st.text(news)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
+
st.subheader(f"๐ง Insight: {name}")
|
| 234 |
+
prompt = f"[ROLE] Analyst. [TARGET] {name} ({ticker}). [DATA] Price:{curr}, Trend:{pct:.2f}%. [NEWS] {news}. [TASK] Analyze & Verdict. [LANG] Korean."
|
| 235 |
+
msg = [{"role": "user", "content": prompt}]
|
| 236 |
+
stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
|
| 237 |
+
st.write_stream(parse_stream(stream))
|
| 238 |
+
else: st.error("์ธ์ ์คํจ")
|
| 239 |
|
| 240 |
+
# --- 2. ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋ (Total War Mode) ---
|
|
|
|
|
|
|
| 241 |
elif menu == "๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋":
|
| 242 |
+
st.subheader("๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ ๊ดํ (Total War Mode)")
|
| 243 |
+
st.caption("์ผํ -> FDR -> ์น ๊ฒ์ 3๋จ๊ณ๋ฅผ ๊ฑฐ์ณ ๋น์นธ ์์ด ๋ฐ์ดํฐ๋ฅผ ์ฑ์๋๋ค. (์๋๊ฐ ์กฐ๊ธ ๋๋ฆด ์ ์์ต๋๋ค)")
|
| 244 |
|
| 245 |
c1, c2 = st.columns([3, 1])
|
| 246 |
+
with c1: target = st.selectbox("๊ตญ๊ฐ", list(MARKET_SAMPLES.keys()))
|
| 247 |
+
with c2: scan = st.button("์ค์บ ์์")
|
| 248 |
+
|
| 249 |
+
if scan:
|
| 250 |
+
tickers = MARKET_SAMPLES[target]
|
| 251 |
+
results = []
|
| 252 |
+
|
| 253 |
+
# ํ๋ก๊ทธ๋ ์ค ๋ฐ
|
| 254 |
+
bar = st.progress(0)
|
| 255 |
+
status_text = st.empty()
|
| 256 |
|
| 257 |
+
for i, t in enumerate(tickers):
|
| 258 |
+
name_display = TICKER_NAMES.get(t, t)
|
| 259 |
+
status_text.text(f"Scanning {name_display} ({t})...")
|
|
|
|
|
|
|
| 260 |
|
| 261 |
+
# [ํต์ฌ] 3๋จ๊ณ ์ง์ํ ๋ฐ์ดํฐ ์์ง ํจ์ ํธ์ถ
|
| 262 |
+
price, pct, src = get_price_data_robust(t, name_display)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
+
if price is not None:
|
| 265 |
+
results.append({
|
| 266 |
+
'Name': name_display,
|
| 267 |
+
'Ticker': t,
|
| 268 |
+
'Price': price,
|
| 269 |
+
'Change(%)': pct,
|
| 270 |
+
'Source': src # ์ถ์ฒ๋ ๊ธฐ๋ก (FDR, Yahoo, Web...)
|
| 271 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
else:
|
| 273 |
+
# ์ ๋ง ์๋ฌด๋ฆฌ ๋ค์ ธ๋ ์์ผ๋ฉด N/A๋ก๋ผ๋ ํ์
|
| 274 |
+
results.append({'Name': name_display, 'Ticker': t, 'Price': 0, 'Change(%)': 0, 'Source': 'Fail'})
|
| 275 |
+
|
| 276 |
+
bar.progress((i+1)/len(tickers))
|
| 277 |
+
|
| 278 |
+
status_text.empty()
|
| 279 |
+
|
| 280 |
+
if results:
|
| 281 |
+
df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
|
| 282 |
+
|
| 283 |
+
# ํํธ๋งต
|
| 284 |
+
st.plotly_chart(plot_bar_chart(df), use_container_width=True)
|
| 285 |
+
|
| 286 |
+
# ํ์ํ ์ปฌ๋ผ ์ ๋ฆฌ
|
| 287 |
+
disp_cols = ['Name', 'Price', 'Change(%)', 'Source']
|
| 288 |
+
|
| 289 |
+
c_up, c_down = st.columns(2)
|
| 290 |
+
with c_up:
|
| 291 |
+
st.success("๐ฅ Top Gainers")
|
| 292 |
+
st.dataframe(df.head(10)[disp_cols].style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
|
| 293 |
+
with c_down:
|
| 294 |
+
st.error("๐ง Top Losers")
|
| 295 |
+
st.dataframe(df.tail(10)[disp_cols].sort_values('Change(%)').style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
|
| 296 |
+
else: st.warning("๋ฐ์ดํฐ ์์ง ์คํจ")
|