Spaces:
Sleeping
Sleeping
Update streamlit_app.py
Browse files- streamlit_app.py +23 -58
streamlit_app.py
CHANGED
|
@@ -22,12 +22,11 @@ else:
|
|
| 22 |
st.stop()
|
| 23 |
|
| 24 |
# ==============================================================================
|
| 25 |
-
# π [UI] λ€κ΅μ΄ λμ
λ리
|
| 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 μ£Όμ λΉμ",
|
|
@@ -35,7 +34,6 @@ UI_TEXT = {
|
|
| 35 |
"btn_analyze": "λΆμ μμ",
|
| 36 |
"status_thinking": "π§ AIκ° λΆμ μ€μ
λλ€...",
|
| 37 |
"info_target": "νκ²",
|
| 38 |
-
"info_keywords": "κ²μ ν€μλ",
|
| 39 |
"status_news": "π° λ΄μ€ μμ§ μ€...",
|
| 40 |
"status_chart_fail": "β οΈ μ°¨νΈ μμ (μΉ κ²μ λ°μ΄ν° μ¬μ©)",
|
| 41 |
"status_data_fail": "β λ°μ΄ν° μμ",
|
|
@@ -53,11 +51,10 @@ UI_TEXT = {
|
|
| 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",
|
|
@@ -65,7 +62,6 @@ UI_TEXT = {
|
|
| 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",
|
|
@@ -83,18 +79,10 @@ UI_TEXT = {
|
|
| 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 |
# ==============================================================================
|
|
@@ -126,7 +114,7 @@ MARKET_SAMPLES = {
|
|
| 126 |
}
|
| 127 |
|
| 128 |
# ==============================================================================
|
| 129 |
-
# πΈοΈ [
|
| 130 |
# ==============================================================================
|
| 131 |
def fetch_news_robust(keyword):
|
| 132 |
summary = ""
|
|
@@ -151,9 +139,6 @@ def fetch_news_robust(keyword):
|
|
| 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))
|
|
@@ -169,13 +154,11 @@ def scrape_price_from_web(name, ticker):
|
|
| 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]
|
| 176 |
elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
|
| 177 |
elif ".KS" in ticker or ".KQ" in ticker: fdr_symbol = ticker.split('.')[0]
|
| 178 |
-
|
| 179 |
hist = fdr.DataReader(fdr_symbol, start=(datetime.datetime.now() - datetime.timedelta(days=10)))
|
| 180 |
if not hist.empty:
|
| 181 |
curr = hist['Close'].iloc[-1]
|
|
@@ -185,7 +168,6 @@ def get_price_data_robust(ticker, name):
|
|
| 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,10 +177,8 @@ def get_price_data_robust(ticker, name):
|
|
| 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):
|
|
@@ -217,9 +197,6 @@ def get_chart_data(ticker):
|
|
| 217 |
except: pass
|
| 218 |
return pd.DataFrame(), "None"
|
| 219 |
|
| 220 |
-
# ==============================================================================
|
| 221 |
-
# π§ [μμ§] AI κ²μ
|
| 222 |
-
# ==============================================================================
|
| 223 |
def identify_target_with_ai(user_query):
|
| 224 |
try:
|
| 225 |
prompt = f"""
|
|
@@ -243,37 +220,38 @@ def parse_stream(stream):
|
|
| 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,
|
|
|
|
|
|
|
|
|
|
| 253 |
colors = ['#00FF00' if x > 0 else '#FF0000' for x in df['Change(%)']]
|
| 254 |
-
fig = go.Figure(go.Bar(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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])
|
|
@@ -319,22 +297,11 @@ if menu == T['menu_search']:
|
|
| 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]
|
| 328 |
-
[
|
| 329 |
-
[
|
| 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}]
|
|
@@ -342,9 +309,6 @@ if menu == T['menu_search']:
|
|
| 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'])
|
|
@@ -373,9 +337,10 @@ elif menu == T['menu_scanner']:
|
|
| 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)
|
|
|
|
| 22 |
st.stop()
|
| 23 |
|
| 24 |
# ==============================================================================
|
| 25 |
+
# π [UI] λ€κ΅μ΄ λμ
λ리
|
| 26 |
# ==============================================================================
|
| 27 |
UI_TEXT = {
|
| 28 |
"KR": {
|
| 29 |
"sidebar_title": "π§ Pocket Quant AI",
|
|
|
|
| 30 |
"menu_search": "π AI μ€λ§νΈ κ²μ",
|
| 31 |
"menu_scanner": "π‘ κΈλ‘λ² μμ₯ μ€μΊλ",
|
| 32 |
"search_title": "π§ λ€κ΅μ΄ AI μ£Όμ λΉμ",
|
|
|
|
| 34 |
"btn_analyze": "λΆμ μμ",
|
| 35 |
"status_thinking": "π§ AIκ° λΆμ μ€μ
λλ€...",
|
| 36 |
"info_target": "νκ²",
|
|
|
|
| 37 |
"status_news": "π° λ΄μ€ μμ§ μ€...",
|
| 38 |
"status_chart_fail": "β οΈ μ°¨νΈ μμ (μΉ κ²μ λ°μ΄ν° μ¬μ©)",
|
| 39 |
"status_data_fail": "β λ°μ΄ν° μμ",
|
|
|
|
| 51 |
"col_change": "λ±λ½λ₯ ",
|
| 52 |
"col_source": "μΆμ²",
|
| 53 |
"msg_fail": "λ°μ΄ν° μμ§ μ€ν¨",
|
| 54 |
+
"llm_lang_instruction": "Korean"
|
| 55 |
},
|
| 56 |
"EN": {
|
| 57 |
"sidebar_title": "π§ Pocket Quant AI",
|
|
|
|
| 58 |
"menu_search": "π AI Smart Search",
|
| 59 |
"menu_scanner": "π‘ Global Market Scanner",
|
| 60 |
"search_title": "π§ AI Stock Assistant",
|
|
|
|
| 62 |
"btn_analyze": "Analyze",
|
| 63 |
"status_thinking": "π§ AI is analyzing...",
|
| 64 |
"info_target": "Target",
|
|
|
|
| 65 |
"status_news": "π° Fetching news...",
|
| 66 |
"status_chart_fail": "β οΈ No Chart (Using Web Data)",
|
| 67 |
"status_data_fail": "β No Data Found",
|
|
|
|
| 79 |
"col_change": "Change(%)",
|
| 80 |
"col_source": "Source",
|
| 81 |
"msg_fail": "Data collection failed",
|
| 82 |
+
"llm_lang_instruction": "English"
|
| 83 |
}
|
| 84 |
}
|
| 85 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
# ==============================================================================
|
| 87 |
# πΎ [λ°μ΄ν°] ν°μ»€ λ§€ν
|
| 88 |
# ==============================================================================
|
|
|
|
| 114 |
}
|
| 115 |
|
| 116 |
# ==============================================================================
|
| 117 |
+
# πΈοΈ [μμ§] λ΄μ€ λ° λ°μ΄ν° μμ§
|
| 118 |
# ==============================================================================
|
| 119 |
def fetch_news_robust(keyword):
|
| 120 |
summary = ""
|
|
|
|
| 139 |
except Exception as e: return f"News Error: {e}"
|
| 140 |
return summary if summary else "No news found."
|
| 141 |
|
|
|
|
|
|
|
|
|
|
| 142 |
def scrape_price_from_web(name, ticker):
|
| 143 |
try:
|
| 144 |
time.sleep(random.uniform(1.0, 1.5))
|
|
|
|
| 154 |
except: return None, None
|
| 155 |
|
| 156 |
def get_price_data_robust(ticker, name):
|
|
|
|
| 157 |
try:
|
| 158 |
fdr_symbol = ticker
|
| 159 |
if ".VN" in ticker: fdr_symbol = ticker.split('.')[0]
|
| 160 |
elif ".JK" in ticker: fdr_symbol = f"IDX:{ticker.split('.')[0]}"
|
| 161 |
elif ".KS" in ticker or ".KQ" in ticker: fdr_symbol = ticker.split('.')[0]
|
|
|
|
| 162 |
hist = fdr.DataReader(fdr_symbol, start=(datetime.datetime.now() - datetime.timedelta(days=10)))
|
| 163 |
if not hist.empty:
|
| 164 |
curr = hist['Close'].iloc[-1]
|
|
|
|
| 168 |
return curr, pct, "FDR"
|
| 169 |
except: pass
|
| 170 |
|
|
|
|
| 171 |
try:
|
| 172 |
stock = yf.Ticker(ticker)
|
| 173 |
price = stock.fast_info.last_price
|
|
|
|
| 177 |
return price, pct, "Yahoo"
|
| 178 |
except: pass
|
| 179 |
|
|
|
|
| 180 |
price, pct = scrape_price_from_web(name, ticker)
|
| 181 |
if price is not None: return price, pct, "Web Search"
|
|
|
|
| 182 |
return None, None, "Fail"
|
| 183 |
|
| 184 |
def get_chart_data(ticker):
|
|
|
|
| 197 |
except: pass
|
| 198 |
return pd.DataFrame(), "None"
|
| 199 |
|
|
|
|
|
|
|
|
|
|
| 200 |
def identify_target_with_ai(user_query):
|
| 201 |
try:
|
| 202 |
prompt = f"""
|
|
|
|
| 220 |
for chunk in stream:
|
| 221 |
if chunk.choices: yield chunk.choices[0].delta.content or ""
|
| 222 |
|
| 223 |
+
# ==============================================================================
|
| 224 |
+
# π [μκ°ν] μ°¨νΈ ν¨μ (λ²κ·Έ μμ λ¨)
|
| 225 |
+
# ==============================================================================
|
| 226 |
def plot_candle_chart(hist, title, source):
|
| 227 |
fig = go.Figure(data=[go.Candlestick(x=hist.index, open=hist['Open'], high=hist['High'], low=hist['Low'], close=hist['Close'], name="Price")])
|
| 228 |
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)')
|
| 229 |
return fig
|
| 230 |
|
| 231 |
+
def plot_bar_chart(df, lang_data):
|
| 232 |
+
# [μμ ] df['Name'] λμ νμ¬ μΈμ΄ μ€μ μ λ§λ 컬λΌ(lang_data['col_name']) μ¬μ©
|
| 233 |
+
target_col = lang_data['col_name']
|
| 234 |
+
|
| 235 |
colors = ['#00FF00' if x > 0 else '#FF0000' for x in df['Change(%)']]
|
| 236 |
+
fig = go.Figure(go.Bar(
|
| 237 |
+
x=df[target_col], # <--- μ¬κΈ°μ μλ¬κ° λ¬μμ΅λλ€. λμ 컬λΌλͺ
μ¬μ©!
|
| 238 |
+
y=df['Change(%)'],
|
| 239 |
+
marker_color=colors,
|
| 240 |
+
text=df['Change(%)'].apply(lambda x: f"{x:.2f}%")
|
| 241 |
+
))
|
| 242 |
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)')
|
| 243 |
return fig
|
| 244 |
|
| 245 |
# ==============================================================================
|
| 246 |
+
# π₯οΈ UI & Sidebar
|
| 247 |
# ==============================================================================
|
| 248 |
with st.sidebar:
|
|
|
|
| 249 |
lang_code = st.selectbox("Language / μΈμ΄", ["KR", "EN"])
|
|
|
|
|
|
|
| 250 |
T = UI_TEXT[lang_code]
|
|
|
|
| 251 |
st.title(T['sidebar_title'])
|
| 252 |
st.divider()
|
|
|
|
|
|
|
| 253 |
menu = st.radio("MENU", [T['menu_search'], T['menu_scanner']], index=0)
|
| 254 |
|
|
|
|
|
|
|
|
|
|
| 255 |
if menu == T['menu_search']:
|
| 256 |
st.subheader(T['search_title'])
|
| 257 |
c1, c2 = st.columns([3, 1])
|
|
|
|
| 297 |
with st.expander(T['expander_news']): st.text(news_data)
|
| 298 |
|
| 299 |
st.subheader(T['insight_title'])
|
|
|
|
|
|
|
| 300 |
target_lang = T['llm_lang_instruction']
|
|
|
|
| 301 |
prompt = f"""
|
| 302 |
+
[ROLE] Analyst. [TARGET] {name} ({ticker}). [QUERY] "{query}"
|
| 303 |
+
[DATA] Price:{curr}, Trend:{pct:.2f}%. [NEWS] {news_data}
|
| 304 |
+
[TASK] Summarize, Sentiment, Verdict.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
[OUTPUT LANGUAGE] **{target_lang}** (Strictly output in {target_lang})
|
| 306 |
"""
|
| 307 |
msg = [{"role": "user", "content": prompt}]
|
|
|
|
| 309 |
st.write_stream(parse_stream(stream))
|
| 310 |
else: st.error("AI Error")
|
| 311 |
|
|
|
|
|
|
|
|
|
|
| 312 |
elif menu == T['menu_scanner']:
|
| 313 |
st.subheader(T['scanner_title'])
|
| 314 |
st.caption(T['scanner_caption'])
|
|
|
|
| 337 |
|
| 338 |
if results:
|
| 339 |
df = pd.DataFrame(results).sort_values('Change(%)', ascending=False)
|
| 340 |
+
|
| 341 |
+
# [μμ ] μ°¨νΈ ν¨μμ νμ¬ μΈμ΄μ€μ (T)μ μ λ¬
|
| 342 |
st.plotly_chart(plot_bar_chart(df, T), use_container_width=True)
|
| 343 |
|
|
|
|
| 344 |
disp_cols = [T['col_name'], 'Ticker', T['col_price'], 'Change(%)', T['col_source']]
|
| 345 |
|
| 346 |
c_up, c_down = st.columns(2)
|