Spaces:
Sleeping
Sleeping
Update streamlit_app.py
Browse files- streamlit_app.py +200 -111
streamlit_app.py
CHANGED
|
@@ -9,7 +9,7 @@ import json
|
|
| 9 |
import datetime
|
| 10 |
import re
|
| 11 |
import time
|
| 12 |
-
import random
|
| 13 |
|
| 14 |
# 1. ํ์ด์ง ์ค์
|
| 15 |
st.set_page_config(page_title="Pocket Quant AI", page_icon="๐ง ", layout="wide")
|
|
@@ -18,36 +18,125 @@ st.set_page_config(page_title="Pocket Quant AI", page_icon="๐ง ", layout="wide"
|
|
| 18 |
if "HF_TOKEN" in st.secrets:
|
| 19 |
client = InferenceClient(api_key=st.secrets["HF_TOKEN"])
|
| 20 |
else:
|
| 21 |
-
st.error("๐จ
|
| 22 |
st.stop()
|
| 23 |
|
| 24 |
# ==============================================================================
|
| 25 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
# ==============================================================================
|
| 27 |
FAKE_HEADERS = {
|
| 28 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
| 29 |
-
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
|
| 30 |
-
'Accept-Language': 'en-US,en;q=0.5',
|
| 31 |
'Referer': 'https://www.google.com/'
|
| 32 |
}
|
| 33 |
|
| 34 |
# ==============================================================================
|
| 35 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
# ==============================================================================
|
| 37 |
def fetch_news_robust(keyword):
|
| 38 |
summary = ""
|
| 39 |
seen_urls = set()
|
| 40 |
try:
|
| 41 |
with DDGS() as ddgs:
|
| 42 |
-
# 1๋จ๊ณ: ์ต๊ทผ 1๋ฌ (์๊ฒฉ)
|
| 43 |
results = list(ddgs.news(keyword, timelimit="m", max_results=3))
|
| 44 |
-
|
| 45 |
-
# 2๋จ๊ณ: ์์ผ๋ฉด ์ ์ฒด ๊ธฐ๊ฐ (์ํ)
|
| 46 |
if not results:
|
| 47 |
-
time.sleep(random.uniform(0.5, 1.0))
|
| 48 |
results = list(ddgs.news(keyword, max_results=3))
|
| 49 |
-
|
| 50 |
-
# 3๋จ๊ณ: ์น ๋ฌธ์ ๊ฒ์ (๋ด์คํญ ์ฐจ๋จ ์ฐํ)
|
| 51 |
if not results:
|
| 52 |
time.sleep(random.uniform(0.5, 1.0))
|
| 53 |
results = list(ddgs.text(f"{keyword} latest news", max_results=3))
|
|
@@ -57,30 +146,21 @@ def fetch_news_robust(keyword):
|
|
| 57 |
if url not in seen_urls:
|
| 58 |
date = r.get('date', 'Unknown')
|
| 59 |
title = r.get('title', '')
|
| 60 |
-
|
| 61 |
-
summary += f"[{date}] {title}: {body}\n"
|
| 62 |
seen_urls.add(url)
|
| 63 |
-
|
| 64 |
except Exception as e: return f"News Error: {e}"
|
| 65 |
-
return summary if summary else "No news found
|
| 66 |
|
| 67 |
# ==============================================================================
|
| 68 |
-
# ๐ ๏ธ [ํต์ฌ ์์ง] ๋ฐ์ดํฐ ์์ง
|
| 69 |
# ==============================================================================
|
| 70 |
def scrape_price_from_web(name, ticker):
|
| 71 |
-
"""
|
| 72 |
-
์ตํ์ ์๋จ: ์น ๊ฒ์์ผ๋ก ๊ฐ๊ฒฉ ๋ฏ์ด์ค๊ธฐ
|
| 73 |
-
"""
|
| 74 |
try:
|
| 75 |
-
|
| 76 |
-
time.sleep(random.uniform(1.0, 2.0)) # 1~2์ด ๋๋ ์ด (์ฌ๋์ฒ๋ผ)
|
| 77 |
-
|
| 78 |
with DDGS() as ddgs:
|
| 79 |
query = f"{name} {ticker} stock price quote today"
|
| 80 |
results = ddgs.text(query, max_results=2)
|
| 81 |
blob = " ".join([r['body'] for r in results])
|
| 82 |
-
|
| 83 |
-
# ์ซ์ ์ถ์ถ (์ผํ ํฌํจ, ์์์ ํฌํจ)
|
| 84 |
match = re.search(r'(\d{1,3}(,\d{3})*(\.\d+)?)', blob)
|
| 85 |
if match:
|
| 86 |
price = float(match.group(0).replace(",", ""))
|
|
@@ -89,7 +169,7 @@ def scrape_price_from_web(name, ticker):
|
|
| 89 |
except: return None, None
|
| 90 |
|
| 91 |
def get_price_data_robust(ticker, name):
|
| 92 |
-
# 1. FDR
|
| 93 |
try:
|
| 94 |
fdr_symbol = ticker
|
| 95 |
if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
|
|
@@ -105,7 +185,7 @@ def get_price_data_robust(ticker, name):
|
|
| 105 |
return curr, pct, "FDR"
|
| 106 |
except: pass
|
| 107 |
|
| 108 |
-
# 2. Yahoo
|
| 109 |
try:
|
| 110 |
stock = yf.Ticker(ticker)
|
| 111 |
price = stock.fast_info.last_price
|
|
@@ -115,14 +195,30 @@ def get_price_data_robust(ticker, name):
|
|
| 115 |
return price, pct, "Yahoo"
|
| 116 |
except: pass
|
| 117 |
|
| 118 |
-
# 3. Web Search
|
| 119 |
price, pct = scrape_price_from_web(name, ticker)
|
| 120 |
-
if price is not None: return price, pct, "Web Search
|
| 121 |
|
| 122 |
return None, None, "Fail"
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
# ==============================================================================
|
| 125 |
-
# ๐ง [์์ง] AI
|
| 126 |
# ==============================================================================
|
| 127 |
def identify_target_with_ai(user_query):
|
| 128 |
try:
|
|
@@ -147,89 +243,54 @@ def parse_stream(stream):
|
|
| 147 |
for chunk in stream:
|
| 148 |
if chunk.choices: yield chunk.choices[0].delta.content or ""
|
| 149 |
|
| 150 |
-
# ์ฐจํธ ๋ฐ์ดํฐ
|
| 151 |
-
def get_chart_data(ticker):
|
| 152 |
-
try:
|
| 153 |
-
fdr_symbol = ticker
|
| 154 |
-
if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
|
| 155 |
-
elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
|
| 156 |
-
elif ".T" in ticker: fdr_symbol = f"TSE:{ticker.split('.')[0]}"
|
| 157 |
-
start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
|
| 158 |
-
# [์์ฅ์ ] requests๋ฅผ ์ง์ ์ฐ๋ FDR ๋ด๋ถ ๋ก์ง์ ๊ฑด๋๋ฆฌ๊ธฐ ํ๋ค์ง๋ง,
|
| 159 |
-
# ๋๋ถ๋ถ Investing.com์ ๋ด ์ฐจ๋จ์ด ๋ํจ.
|
| 160 |
-
hist = fdr.DataReader(fdr_symbol, start)
|
| 161 |
-
if not hist.empty: return hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low'}), "FDR"
|
| 162 |
-
except: pass
|
| 163 |
-
try:
|
| 164 |
-
hist = yf.Ticker(ticker).history(period="3mo")
|
| 165 |
-
if not hist.empty: return hist, "Yahoo"
|
| 166 |
-
except: pass
|
| 167 |
-
return pd.DataFrame(), "None"
|
| 168 |
-
|
| 169 |
# ์๊ฐํ
|
| 170 |
def plot_candle_chart(hist, title, source):
|
| 171 |
fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
|
| 172 |
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)')
|
| 173 |
return fig
|
| 174 |
|
| 175 |
-
def plot_bar_chart(df):
|
| 176 |
colors = ['#00FF00' if x > 0 else '#FF0000' for x in df['Change(%)']]
|
| 177 |
fig = go.Figure(go.Bar(x=df['Name'], y=df['Change(%)'], marker_color=colors, text=df['Change(%)'].apply(lambda x: f"{x:.2f}%")))
|
| 178 |
fig.update_layout(title="Market Heatmap", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
|
| 179 |
return fig
|
| 180 |
|
| 181 |
# ==============================================================================
|
| 182 |
-
#
|
| 183 |
-
# ==============================================================================
|
| 184 |
-
TICKER_NAMES = {
|
| 185 |
-
"AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
|
| 186 |
-
"005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "207940.KS": "Samsung Bio",
|
| 187 |
-
"VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VNM.VN": "Vinamilk", "VCB.VN": "Vietcombank", "GAS.VN": "PV Gas",
|
| 188 |
-
"BBCA.JK": "BCA", "BBRI.JK": "BRI", "GOTO.JK": "GoTo", "ASII.JK": "Astra Intl",
|
| 189 |
-
"7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank",
|
| 190 |
-
"9988.HK": "Alibaba", "0700.HK": "Tencent", "2330.TW": "TSMC",
|
| 191 |
-
"RELIANCE.NS": "Reliance", "TCS.NS": "TCS"
|
| 192 |
-
}
|
| 193 |
-
|
| 194 |
-
MARKET_SAMPLES = {
|
| 195 |
-
"๐ป๐ณ ๋ฒ ํธ๋จ (Vietnam)": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN"],
|
| 196 |
-
"๐ฎ๐ฉ ์ธ๋๋ค์์": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
|
| 197 |
-
"๐ฐ๐ท ํ๊ตญ (Korea)": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "207940.KS"],
|
| 198 |
-
"๐บ๐ธ ๋ฏธ๊ตญ (USA)": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD"],
|
| 199 |
-
"๐ฏ๐ต ์ผ๋ณธ (Japan)": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T"],
|
| 200 |
-
"๐จ๐ณ ์ค๊ตญ/ํ์ฝฉ": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK"],
|
| 201 |
-
"๐น๐ผ ๋๋ง (Taiwan)": ["2330.TW", "2454.TW", "2317.TW", "2308.TW"],
|
| 202 |
-
"๐ฎ๐ณ ์ธ๋ (India)": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS"]
|
| 203 |
-
}
|
| 204 |
-
|
| 205 |
-
# ==============================================================================
|
| 206 |
-
# ๐ฅ๏ธ UI
|
| 207 |
# ==============================================================================
|
| 208 |
with st.sidebar:
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
st.divider()
|
| 211 |
-
|
|
|
|
|
|
|
| 212 |
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
| 215 |
c1, c2 = st.columns([3, 1])
|
| 216 |
-
with c1: query = st.text_input("
|
| 217 |
-
with c2: btn = st.button(
|
| 218 |
|
| 219 |
if btn:
|
| 220 |
-
with st.status(
|
| 221 |
info = identify_target_with_ai(query)
|
| 222 |
if info:
|
| 223 |
name, ticker = info.get('name'), info.get('ticker')
|
| 224 |
eng_key, native_key = info.get('eng_key'), info.get('native_key')
|
| 225 |
|
| 226 |
-
st.info(f"๐ก
|
| 227 |
|
| 228 |
-
# ๋ฐ์ดํฐ ์์ง
|
| 229 |
h, src = get_chart_data(ticker)
|
| 230 |
-
|
| 231 |
-
# ๋ด์ค ์์ง (์ฌ๋์ธ ์ฒ ๋๋ ์ด ํฌํจ)
|
| 232 |
-
st.write("๐ฐ ๋ด์ค ๊ฒ์ ์ค...")
|
| 233 |
news_data = get_polyglot_news(eng_key, native_key)
|
| 234 |
|
| 235 |
curr, pct = "N/A", 0
|
|
@@ -238,38 +299,59 @@ if menu == "๐ AI ์ค๋งํธ ๊ฒ์":
|
|
| 238 |
if len(h) >= 2:
|
| 239 |
prev = h['Close'].iloc[-2]
|
| 240 |
if prev != 0: pct = ((curr - prev)/prev)*100
|
| 241 |
-
status.update(label="โ
|
| 242 |
else:
|
| 243 |
c_web, p_web, s_web = get_price_data_robust(ticker, name)
|
| 244 |
if c_web:
|
| 245 |
curr, pct, src = c_web, p_web, s_web
|
| 246 |
-
status.update(label=
|
| 247 |
else:
|
| 248 |
-
status.update(label=
|
| 249 |
|
| 250 |
st.divider()
|
| 251 |
m1, m2 = st.columns(2)
|
| 252 |
-
m1.metric(
|
| 253 |
-
m2.metric(
|
| 254 |
|
| 255 |
if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
|
| 256 |
-
else: st.warning(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
msg = [{"role": "user", "content": prompt}]
|
| 263 |
stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
|
| 264 |
st.write_stream(parse_stream(stream))
|
| 265 |
-
else: st.error("
|
| 266 |
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
c1, c2 = st.columns([3, 1])
|
| 271 |
-
with c1: target = st.selectbox("
|
| 272 |
-
with c2: scan = st.button(
|
| 273 |
|
| 274 |
if scan:
|
| 275 |
tickers = MARKET_SAMPLES[target]
|
|
@@ -278,22 +360,29 @@ elif menu == "๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋":
|
|
| 278 |
|
| 279 |
for i, t in enumerate(tickers):
|
| 280 |
name_display = TICKER_NAMES.get(t, t)
|
| 281 |
-
# ์ฌ๊ธฐ ๋ด๋ถ์์ Web Search ๋ฐ๋ ์ ๋๋ค sleep์ด ์ ์ฉ๋จ
|
| 282 |
p, c, s = get_price_data_robust(t, name_display)
|
| 283 |
if p is not None:
|
| 284 |
-
results.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
bar.progress((i+1)/len(tickers))
|
| 286 |
|
| 287 |
if results:
|
| 288 |
df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
|
| 289 |
-
st.plotly_chart(plot_bar_chart(df), use_container_width=True)
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
-
disp_cols = ['Name', 'Ticker', 'Price', 'Change(%)', 'Source']
|
| 292 |
c_up, c_down = st.columns(2)
|
| 293 |
with c_up:
|
| 294 |
-
st.success(
|
| 295 |
-
st.dataframe(df.head(10)[disp_cols].style.format({
|
| 296 |
with c_down:
|
| 297 |
-
st.error(
|
| 298 |
-
st.dataframe(df.tail(10)[disp_cols].sort_values('Change(%)').style.format({
|
| 299 |
-
else: st.warning(
|
|
|
|
| 9 |
import datetime
|
| 10 |
import re
|
| 11 |
import time
|
| 12 |
+
import random
|
| 13 |
|
| 14 |
# 1. ํ์ด์ง ์ค์
|
| 15 |
st.set_page_config(page_title="Pocket Quant AI", page_icon="๐ง ", layout="wide")
|
|
|
|
| 18 |
if "HF_TOKEN" in st.secrets:
|
| 19 |
client = InferenceClient(api_key=st.secrets["HF_TOKEN"])
|
| 20 |
else:
|
| 21 |
+
st.error("๐จ HF_TOKEN required in secrets.")
|
| 22 |
st.stop()
|
| 23 |
|
| 24 |
# ==============================================================================
|
| 25 |
+
# ๐ [UI] ๋ค๊ตญ์ด ๋์
๋๋ฆฌ (Language Pack)
|
| 26 |
+
# ==============================================================================
|
| 27 |
+
UI_TEXT = {
|
| 28 |
+
"KR": {
|
| 29 |
+
"sidebar_title": "๐ง Pocket Quant AI",
|
| 30 |
+
"lang_label": "์ธ์ด ์ค์ (Language)",
|
| 31 |
+
"menu_search": "๐ AI ์ค๋งํธ ๊ฒ์",
|
| 32 |
+
"menu_scanner": "๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋",
|
| 33 |
+
"search_title": "๐ง ๋ค๊ตญ์ด AI ์ฃผ์ ๋น์",
|
| 34 |
+
"search_placeholder": "์: ๋ฒ ํธ๋จ ๋น๋๋ฐํฌ, ์ผ์ฑ์ ์...",
|
| 35 |
+
"btn_analyze": "๋ถ์ ์์",
|
| 36 |
+
"status_thinking": "๐ง AI๊ฐ ๋ถ์ ์ค์
๋๋ค...",
|
| 37 |
+
"info_target": "ํ๊ฒ",
|
| 38 |
+
"info_keywords": "๊ฒ์ ํค์๋",
|
| 39 |
+
"status_news": "๐ฐ ๋ด์ค ์์ง ์ค...",
|
| 40 |
+
"status_chart_fail": "โ ๏ธ ์ฐจํธ ์์ (์น ๊ฒ์ ๋ฐ์ดํฐ ์ฌ์ฉ)",
|
| 41 |
+
"status_data_fail": "โ ๋ฐ์ดํฐ ์์",
|
| 42 |
+
"metric_price": "ํ์ฌ๊ฐ",
|
| 43 |
+
"metric_source": "์ถ์ฒ",
|
| 44 |
+
"expander_news": "๐ฐ ๋ด์ค ์๋ฌธ ๋ณด๊ธฐ",
|
| 45 |
+
"insight_title": "๐ง AI ํฌ์ ๋ฆฌํฌํธ",
|
| 46 |
+
"scanner_title": "๐ก ๊ธ๋ก๋ฒ ์์ฅ ์ ๊ดํ",
|
| 47 |
+
"scanner_caption": "โป ์ฌ๋์ฒ๋ผ ์ฒ์ฒํ ์ ๋ฐ ๊ฒ์ํฉ๋๋ค. (์๋: ๋๋ฆผ)",
|
| 48 |
+
"btn_scan": "์ค์บ ์์",
|
| 49 |
+
"tab_gainers": "๐ฅ ๊ธ๋ฑ (Top Gainers)",
|
| 50 |
+
"tab_losers": "๐ง ๊ธ๋ฝ (Top Losers)",
|
| 51 |
+
"col_name": "๊ธฐ์
๋ช
",
|
| 52 |
+
"col_price": "๊ฐ๊ฒฉ",
|
| 53 |
+
"col_change": "๋ฑ๋ฝ๋ฅ ",
|
| 54 |
+
"col_source": "์ถ์ฒ",
|
| 55 |
+
"msg_fail": "๋ฐ์ดํฐ ์์ง ์คํจ",
|
| 56 |
+
"llm_lang_instruction": "Korean" # ํ๋กฌํํธ์ฉ
|
| 57 |
+
},
|
| 58 |
+
"EN": {
|
| 59 |
+
"sidebar_title": "๐ง Pocket Quant AI",
|
| 60 |
+
"lang_label": "Language Settings",
|
| 61 |
+
"menu_search": "๐ AI Smart Search",
|
| 62 |
+
"menu_scanner": "๐ก Global Market Scanner",
|
| 63 |
+
"search_title": "๐ง AI Stock Assistant",
|
| 64 |
+
"search_placeholder": "e.g. Vinamilk, Samsung Electronics...",
|
| 65 |
+
"btn_analyze": "Analyze",
|
| 66 |
+
"status_thinking": "๐ง AI is analyzing...",
|
| 67 |
+
"info_target": "Target",
|
| 68 |
+
"info_keywords": "Keywords",
|
| 69 |
+
"status_news": "๐ฐ Fetching news...",
|
| 70 |
+
"status_chart_fail": "โ ๏ธ No Chart (Using Web Data)",
|
| 71 |
+
"status_data_fail": "โ No Data Found",
|
| 72 |
+
"metric_price": "Price",
|
| 73 |
+
"metric_source": "Source",
|
| 74 |
+
"expander_news": "๐ฐ View Source News",
|
| 75 |
+
"insight_title": "๐ง AI Investment Report",
|
| 76 |
+
"scanner_title": "๐ก Global Market Scanner",
|
| 77 |
+
"scanner_caption": "โป Deep search with human-like delay. (Speed: Slow)",
|
| 78 |
+
"btn_scan": "Start Scan",
|
| 79 |
+
"tab_gainers": "๐ฅ Top Gainers",
|
| 80 |
+
"tab_losers": "๐ง Top Losers",
|
| 81 |
+
"col_name": "Company",
|
| 82 |
+
"col_price": "Price",
|
| 83 |
+
"col_change": "Change(%)",
|
| 84 |
+
"col_source": "Source",
|
| 85 |
+
"msg_fail": "Data collection failed",
|
| 86 |
+
"llm_lang_instruction": "English" # ํ๋กฌํํธ์ฉ
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
# ==============================================================================
|
| 91 |
+
# ๐ต๏ธ [์์ฅ์ ] ๊ฐ์ง ๋ช
ํจ
|
| 92 |
# ==============================================================================
|
| 93 |
FAKE_HEADERS = {
|
| 94 |
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
|
|
|
|
|
|
|
| 95 |
'Referer': 'https://www.google.com/'
|
| 96 |
}
|
| 97 |
|
| 98 |
# ==============================================================================
|
| 99 |
+
# ๐พ [๋ฐ์ดํฐ] ํฐ์ปค ๋งคํ
|
| 100 |
+
# ==============================================================================
|
| 101 |
+
TICKER_NAMES = {
|
| 102 |
+
"VIC.VN": "Vingroup", "VHM.VN": "Vinhomes", "VCB.VN": "Vietcombank", "VNM.VN": "Vinamilk",
|
| 103 |
+
"HPG.VN": "Hoa Phat", "MSN.VN": "Masan Group", "GAS.VN": "PV Gas",
|
| 104 |
+
"BBCA.JK": "BCA Bank", "BBRI.JK": "BRI Bank", "TLKM.JK": "Telkom Indo", "BMRI.JK": "Mandiri",
|
| 105 |
+
"ASII.JK": "Astra Intl", "GOTO.JK": "GoTo Group",
|
| 106 |
+
"005930.KS": "Samsung Elec", "000660.KS": "SK Hynix", "035420.KS": "NAVER", "035720.KS": "Kakao",
|
| 107 |
+
"005380.KS": "Hyundai Motor", "207940.KS": "Samsung Bio",
|
| 108 |
+
"AAPL": "Apple", "NVDA": "NVIDIA", "TSLA": "Tesla", "AMZN": "Amazon", "MSFT": "Microsoft",
|
| 109 |
+
"GOOGL": "Google", "META": "Meta", "AMD": "AMD",
|
| 110 |
+
"7203.T": "Toyota", "6758.T": "Sony", "9984.T": "SoftBank", "8035.T": "Tokyo Elec",
|
| 111 |
+
"6861.T": "Keyence", "7974.T": "Nintendo",
|
| 112 |
+
"9988.HK": "Alibaba", "0700.HK": "Tencent", "3690.HK": "Meituan", "1211.HK": "BYD", "1810.HK": "Xiaomi",
|
| 113 |
+
"2330.TW": "TSMC", "2454.TW": "MediaTek", "2317.TW": "Foxconn", "2308.TW": "Delta Elec",
|
| 114 |
+
"RELIANCE.NS": "Reliance Ind", "TCS.NS": "TCS", "HDFCBANK.NS": "HDFC Bank", "INFY.NS": "Infosys"
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
MARKET_SAMPLES = {
|
| 118 |
+
"๐ป๐ณ Vietnam": ["VIC.VN", "VHM.VN", "VCB.VN", "VNM.VN", "HPG.VN", "MSN.VN", "GAS.VN"],
|
| 119 |
+
"๐ฎ๐ฉ Indonesia": ["BBCA.JK", "BBRI.JK", "TLKM.JK", "BMRI.JK", "ASII.JK", "GOTO.JK"],
|
| 120 |
+
"๐ฐ๐ท Korea": ["005930.KS", "000660.KS", "035420.KS", "035720.KS", "005380.KS", "207940.KS"],
|
| 121 |
+
"๐บ๐ธ USA": ["AAPL", "NVDA", "TSLA", "AMZN", "MSFT", "GOOGL", "META", "AMD"],
|
| 122 |
+
"๐ฏ๐ต Japan": ["7203.T", "6758.T", "9984.T", "8035.T", "6861.T", "7974.T"],
|
| 123 |
+
"๐จ๐ณ China/HK": ["9988.HK", "0700.HK", "3690.HK", "1211.HK", "1810.HK"],
|
| 124 |
+
"๐น๐ผ Taiwan": ["2330.TW", "2454.TW", "2317.TW", "2308.TW"],
|
| 125 |
+
"๐ฎ๐ณ India": ["RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS"]
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
# ==============================================================================
|
| 129 |
+
# ๐ธ๏ธ [ํต์ฌ ์์ง] ๋ด์ค ์์ง
|
| 130 |
# ==============================================================================
|
| 131 |
def fetch_news_robust(keyword):
|
| 132 |
summary = ""
|
| 133 |
seen_urls = set()
|
| 134 |
try:
|
| 135 |
with DDGS() as ddgs:
|
|
|
|
| 136 |
results = list(ddgs.news(keyword, timelimit="m", max_results=3))
|
|
|
|
|
|
|
| 137 |
if not results:
|
| 138 |
+
time.sleep(random.uniform(0.5, 1.0))
|
| 139 |
results = list(ddgs.news(keyword, max_results=3))
|
|
|
|
|
|
|
| 140 |
if not results:
|
| 141 |
time.sleep(random.uniform(0.5, 1.0))
|
| 142 |
results = list(ddgs.text(f"{keyword} latest news", max_results=3))
|
|
|
|
| 146 |
if url not in seen_urls:
|
| 147 |
date = r.get('date', 'Unknown')
|
| 148 |
title = r.get('title', '')
|
| 149 |
+
summary += f"[{date}] {title}\n"
|
|
|
|
| 150 |
seen_urls.add(url)
|
|
|
|
| 151 |
except Exception as e: return f"News Error: {e}"
|
| 152 |
+
return summary if summary else "No news found."
|
| 153 |
|
| 154 |
# ==============================================================================
|
| 155 |
+
# ๐ ๏ธ [ํต์ฌ ์์ง] ๊ฐ๊ฒฉ ๋ฐ์ดํฐ ์์ง
|
| 156 |
# ==============================================================================
|
| 157 |
def scrape_price_from_web(name, ticker):
|
|
|
|
|
|
|
|
|
|
| 158 |
try:
|
| 159 |
+
time.sleep(random.uniform(1.0, 1.5))
|
|
|
|
|
|
|
| 160 |
with DDGS() as ddgs:
|
| 161 |
query = f"{name} {ticker} stock price quote today"
|
| 162 |
results = ddgs.text(query, max_results=2)
|
| 163 |
blob = " ".join([r['body'] for r in results])
|
|
|
|
|
|
|
| 164 |
match = re.search(r'(\d{1,3}(,\d{3})*(\.\d+)?)', blob)
|
| 165 |
if match:
|
| 166 |
price = float(match.group(0).replace(",", ""))
|
|
|
|
| 169 |
except: return None, None
|
| 170 |
|
| 171 |
def get_price_data_robust(ticker, name):
|
| 172 |
+
# 1. FDR
|
| 173 |
try:
|
| 174 |
fdr_symbol = ticker
|
| 175 |
if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
|
|
|
|
| 185 |
return curr, pct, "FDR"
|
| 186 |
except: pass
|
| 187 |
|
| 188 |
+
# 2. Yahoo
|
| 189 |
try:
|
| 190 |
stock = yf.Ticker(ticker)
|
| 191 |
price = stock.fast_info.last_price
|
|
|
|
| 195 |
return price, pct, "Yahoo"
|
| 196 |
except: pass
|
| 197 |
|
| 198 |
+
# 3. Web Search
|
| 199 |
price, pct = scrape_price_from_web(name, ticker)
|
| 200 |
+
if price is not None: return price, pct, "Web Search"
|
| 201 |
|
| 202 |
return None, None, "Fail"
|
| 203 |
|
| 204 |
+
def get_chart_data(ticker):
|
| 205 |
+
try:
|
| 206 |
+
fdr_symbol = ticker
|
| 207 |
+
if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
|
| 208 |
+
elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
|
| 209 |
+
elif ".T" in ticker: fdr_symbol = f"TSE:{ticker.split('.')[0]}"
|
| 210 |
+
start = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
|
| 211 |
+
hist = fdr.DataReader(fdr_symbol, start)
|
| 212 |
+
if not hist.empty: return hist.rename(columns={'Close':'Close', 'Open':'Open', 'High':'High', 'Low':'Low'}), "FDR"
|
| 213 |
+
except: pass
|
| 214 |
+
try:
|
| 215 |
+
hist = yf.Ticker(ticker).history(period="3mo")
|
| 216 |
+
if not hist.empty: return hist, "Yahoo"
|
| 217 |
+
except: pass
|
| 218 |
+
return pd.DataFrame(), "None"
|
| 219 |
+
|
| 220 |
# ==============================================================================
|
| 221 |
+
# ๐ง [์์ง] AI ๊ฒ์
|
| 222 |
# ==============================================================================
|
| 223 |
def identify_target_with_ai(user_query):
|
| 224 |
try:
|
|
|
|
| 243 |
for chunk in stream:
|
| 244 |
if chunk.choices: yield chunk.choices[0].delta.content or ""
|
| 245 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
# ์๊ฐํ
|
| 247 |
def plot_candle_chart(hist, title, source):
|
| 248 |
fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
|
| 249 |
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)')
|
| 250 |
return fig
|
| 251 |
|
| 252 |
+
def plot_bar_chart(df, lang_cols):
|
| 253 |
colors = ['#00FF00' if x > 0 else '#FF0000' for x in df['Change(%)']]
|
| 254 |
fig = go.Figure(go.Bar(x=df['Name'], y=df['Change(%)'], marker_color=colors, text=df['Change(%)'].apply(lambda x: f"{x:.2f}%")))
|
| 255 |
fig.update_layout(title="Market Heatmap", height=350, margin=dict(l=10, r=10, t=30, b=10), template="plotly_dark", paper_bgcolor='rgba(0,0,0,0)')
|
| 256 |
return fig
|
| 257 |
|
| 258 |
# ==============================================================================
|
| 259 |
+
# ๐ฅ๏ธ UI & Sidebar (๋ค๊ตญ์ด ์ ์ฉ)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
# ==============================================================================
|
| 261 |
with st.sidebar:
|
| 262 |
+
# 1. ์ธ์ด ์ ํ (Language Selector)
|
| 263 |
+
lang_code = st.selectbox("Language / ์ธ์ด", ["KR", "EN"])
|
| 264 |
+
|
| 265 |
+
# ํ
์คํธ ๋ก๋ฉ
|
| 266 |
+
T = UI_TEXT[lang_code]
|
| 267 |
+
|
| 268 |
+
st.title(T['sidebar_title'])
|
| 269 |
st.divider()
|
| 270 |
+
|
| 271 |
+
# ๋ฉ๋ด ์ด๋ฆ๋ ์ธ์ด์ ๋ฐ๋ผ ๋ณ๊ฒฝ
|
| 272 |
+
menu = st.radio("MENU", [T['menu_search'], T['menu_scanner']], index=0)
|
| 273 |
|
| 274 |
+
# ==============================================================================
|
| 275 |
+
# ๋ชจ๋ 1: AI ์ค๋งํธ ๊ฒ์
|
| 276 |
+
# ==============================================================================
|
| 277 |
+
if menu == T['menu_search']:
|
| 278 |
+
st.subheader(T['search_title'])
|
| 279 |
c1, c2 = st.columns([3, 1])
|
| 280 |
+
with c1: query = st.text_input("Query", placeholder=T['search_placeholder'], label_visibility="collapsed")
|
| 281 |
+
with c2: btn = st.button(T['btn_analyze'], use_container_width=True)
|
| 282 |
|
| 283 |
if btn:
|
| 284 |
+
with st.status(T['status_thinking'], expanded=True) as status:
|
| 285 |
info = identify_target_with_ai(query)
|
| 286 |
if info:
|
| 287 |
name, ticker = info.get('name'), info.get('ticker')
|
| 288 |
eng_key, native_key = info.get('eng_key'), info.get('native_key')
|
| 289 |
|
| 290 |
+
st.info(f"๐ก {T['info_target']}: **{name} ({ticker})**")
|
| 291 |
|
|
|
|
| 292 |
h, src = get_chart_data(ticker)
|
| 293 |
+
st.write(T['status_news'])
|
|
|
|
|
|
|
| 294 |
news_data = get_polyglot_news(eng_key, native_key)
|
| 295 |
|
| 296 |
curr, pct = "N/A", 0
|
|
|
|
| 299 |
if len(h) >= 2:
|
| 300 |
prev = h['Close'].iloc[-2]
|
| 301 |
if prev != 0: pct = ((curr - prev)/prev)*100
|
| 302 |
+
status.update(label="โ
OK", state="complete", expanded=False)
|
| 303 |
else:
|
| 304 |
c_web, p_web, s_web = get_price_data_robust(ticker, name)
|
| 305 |
if c_web:
|
| 306 |
curr, pct, src = c_web, p_web, s_web
|
| 307 |
+
status.update(label=T['status_chart_fail'], state="complete", expanded=False)
|
| 308 |
else:
|
| 309 |
+
status.update(label=T['status_data_fail'], state="complete", expanded=False)
|
| 310 |
|
| 311 |
st.divider()
|
| 312 |
m1, m2 = st.columns(2)
|
| 313 |
+
m1.metric(T['metric_price'], f"{curr:,.0f}" if isinstance(curr, (int, float)) else curr, f"{pct:.2f}%")
|
| 314 |
+
m2.metric(T['metric_source'], src)
|
| 315 |
|
| 316 |
if not h.empty: st.plotly_chart(plot_candle_chart(h, name, src), use_container_width=True)
|
| 317 |
+
else: st.warning(f"Chart N/A ({src})")
|
| 318 |
+
|
| 319 |
+
with st.expander(T['expander_news']): st.text(news_data)
|
| 320 |
+
|
| 321 |
+
st.subheader(T['insight_title'])
|
| 322 |
+
|
| 323 |
+
# [์ค์] ์ฌ์ฉ์๊ฐ ์ ํํ ์ธ์ด(T['llm_lang_instruction'])๋ฅผ ํ๋กฌํํธ์ ์ฃผ์
|
| 324 |
+
target_lang = T['llm_lang_instruction']
|
| 325 |
+
|
| 326 |
+
prompt = f"""
|
| 327 |
+
[ROLE] Global Investment Analyst.
|
| 328 |
+
[TARGET] {name} ({ticker})
|
| 329 |
+
[USER QUERY] "{query}"
|
| 330 |
+
[DATA] Price:{curr}, Trend:{pct:.2f}%.
|
| 331 |
+
[NEWS CONTEXT] {news_data}
|
| 332 |
|
| 333 |
+
[TASK]
|
| 334 |
+
1. Summarize situation.
|
| 335 |
+
2. Analyze sentiment.
|
| 336 |
+
3. Verdict (Buy/Hold/Sell).
|
| 337 |
|
| 338 |
+
[OUTPUT LANGUAGE] **{target_lang}** (Strictly output in {target_lang})
|
| 339 |
+
"""
|
| 340 |
msg = [{"role": "user", "content": prompt}]
|
| 341 |
stream = client.chat.completions.create(model="Qwen/Qwen2.5-72B-Instruct", messages=msg, stream=True)
|
| 342 |
st.write_stream(parse_stream(stream))
|
| 343 |
+
else: st.error("AI Error")
|
| 344 |
|
| 345 |
+
# ==============================================================================
|
| 346 |
+
# ๋ชจ๋ 2: ๊ธ๋ก๋ฒ ์์ฅ ์ค์บ๋
|
| 347 |
+
# ==============================================================================
|
| 348 |
+
elif menu == T['menu_scanner']:
|
| 349 |
+
st.subheader(T['scanner_title'])
|
| 350 |
+
st.caption(T['scanner_caption'])
|
| 351 |
+
|
| 352 |
c1, c2 = st.columns([3, 1])
|
| 353 |
+
with c1: target = st.selectbox("Market", list(MARKET_SAMPLES.keys()), label_visibility="collapsed")
|
| 354 |
+
with c2: scan = st.button(T['btn_scan'])
|
| 355 |
|
| 356 |
if scan:
|
| 357 |
tickers = MARKET_SAMPLES[target]
|
|
|
|
| 360 |
|
| 361 |
for i, t in enumerate(tickers):
|
| 362 |
name_display = TICKER_NAMES.get(t, t)
|
|
|
|
| 363 |
p, c, s = get_price_data_robust(t, name_display)
|
| 364 |
if p is not None:
|
| 365 |
+
results.append({
|
| 366 |
+
T['col_name']: name_display,
|
| 367 |
+
'Ticker': t,
|
| 368 |
+
T['col_price']: p,
|
| 369 |
+
'Change(%)': c,
|
| 370 |
+
T['col_source']: s
|
| 371 |
+
})
|
| 372 |
bar.progress((i+1)/len(tickers))
|
| 373 |
|
| 374 |
if results:
|
| 375 |
df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
|
| 376 |
+
st.plotly_chart(plot_bar_chart(df, T), use_container_width=True)
|
| 377 |
+
|
| 378 |
+
# ๋ค๊ตญ์ด ์ปฌ๋ผ๋ช
์ ์ฉ
|
| 379 |
+
disp_cols = [T['col_name'], 'Ticker', T['col_price'], 'Change(%)', T['col_source']]
|
| 380 |
|
|
|
|
| 381 |
c_up, c_down = st.columns(2)
|
| 382 |
with c_up:
|
| 383 |
+
st.success(T['tab_gainers'])
|
| 384 |
+
st.dataframe(df.head(10)[disp_cols].style.format({T['col_price']: "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
|
| 385 |
with c_down:
|
| 386 |
+
st.error(T['tab_losers'])
|
| 387 |
+
st.dataframe(df.tail(10)[disp_cols].sort_values('Change(%)').style.format({T['col_price']: "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
|
| 388 |
+
else: st.warning(T['msg_fail'])
|