benjamin5607 commited on
Commit
528fc1b
ยท
verified ยท
1 Parent(s): b4977db

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +40 -33
streamlit_app.py CHANGED
@@ -20,6 +20,9 @@ st.markdown("""
20
  [data-testid="stMetricValue"] {
21
  font-size: 24px;
22
  }
 
 
 
23
  .st-emotion-cache-1r6slb0 {
24
  border: 1px solid #333;
25
  border-radius: 10px;
@@ -35,7 +38,7 @@ else:
35
  st.error("๐Ÿšจ ์„ค์ • ์˜ค๋ฅ˜: Secrets์— 'HF_TOKEN'์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.")
36
  st.stop()
37
 
38
- # --- ๋ฐ์ดํ„ฐ & ์กฑ๋ณด (์ด์ „๊ณผ ๋™์ผ) ---
39
  GLOBAL_TICKER_MAP = {
40
  "TSMC": "2330.TW", "MEDIATEK": "2454.TW", "FOXCONN": "2317.TW",
41
  "ALIBABA": "9988.HK", "TENCENT": "0700.HK", "BYD": "1211.HK",
@@ -99,20 +102,41 @@ def parse_stream(stream):
99
  if hasattr(delta, 'content') and delta.content:
100
  yield delta.content.replace("```markdown", "").replace("```", "")
101
 
102
- # --- [์‹ ๊ทœ ๊ธฐ๋Šฅ] ํ”„๋กœํŽ˜์…”๋„ ์บ”๋“ค ์ฐจํŠธ ๊ทธ๋ฆฌ๊ธฐ ---
103
  def plot_candle_chart(hist, title):
104
  fig = go.Figure(data=[go.Candlestick(
105
  x=hist.index,
106
  open=hist['Open'], high=hist['High'],
107
  low=hist['Low'], close=hist['Close'],
108
- name=title
109
  )])
110
  fig.update_layout(
111
- title=dict(text=f"{title} Price Chart", x=0, font=dict(size=14)),
112
- height=350, margin=dict(l=20, r=20, t=40, b=20),
113
- xaxis_rangeslider_visible=False, # ํ•˜๋‹จ ์Šฌ๋ผ์ด๋” ์ œ๊ฑฐ (๊น”๋”ํ•˜๊ฒŒ)
114
- template="plotly_dark", # ๋‹คํฌ ๋ชจ๋“œ ํ…Œ๋งˆ
115
- paper_bgcolor='rgba(0,0,0,0)', # ๋ฐฐ๊ฒฝ ํˆฌ๋ช…
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  plot_bgcolor='rgba(0,0,0,0)'
117
  )
118
  return fig
@@ -124,13 +148,9 @@ with st.sidebar:
124
  st.header("๐ŸŒ Pocket Quant Pro")
125
  st.write("AI Powered Global Investment")
126
  st.divider()
127
-
128
- # ๋ฉ”๋‰ด ์„ ํƒ
129
  menu = st.radio("MENU", ["๐Ÿ” ์ข…๋ชฉ ๋ถ„์„ (AI Analysis)", "๐Ÿ“ก ์‹œ์žฅ ์Šค์บ๋„ˆ (Market Watch)"], index=0)
130
-
131
  st.divider()
132
  st.caption("Powered by Qwen-2.5-72B")
133
- st.caption("Data: Yahoo Finance & Naver")
134
 
135
  # ==============================================================================
136
  # 1. ์ข…๋ชฉ ๋ถ„์„ ๋ชจ๋“œ
@@ -138,10 +158,9 @@ with st.sidebar:
138
  if "์ข…๋ชฉ ๋ถ„์„" in menu:
139
  st.subheader("๐Ÿ” AI Investment Analyst")
140
 
141
- # ์ž…๋ ฅ์ฐฝ๊ณผ ๋ฒ„ํŠผ์„ ๋‚˜๋ž€ํžˆ ๋ฐฐ์น˜ (๋ชจ๋ฐ”์ผ ์นœํ™”์ )
142
  c1, c2 = st.columns([3, 1])
143
  with c1:
144
- user_input = st.text_input("Ticker or Name", "TSMC", label_visibility="collapsed", placeholder="์ข…๋ชฉ๋ช… ์ž…๋ ฅ (์˜ˆ: ์‚ผ์„ฑ์ „์ž, Tesla)")
145
  with c2:
146
  analyze_btn = st.button("Analysis", use_container_width=True)
147
 
@@ -151,18 +170,15 @@ if "์ข…๋ชฉ ๋ถ„์„" in menu:
151
 
152
  if ticker:
153
  try:
154
- # ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘
155
  stock = yf.Ticker(ticker)
156
  hist = stock.history(period="3mo")
157
 
158
  if not hist.empty:
159
- # ๊ธฐ๋ณธ ๋ฐ์ดํ„ฐ ๊ณ„์‚ฐ
160
  curr = hist['Close'].iloc[-1]
161
  prev = hist['Close'].iloc[-2]
162
  change_pct = ((curr - prev) / prev) * 100
163
  vol = hist['Volume'].iloc[-1]
164
 
165
- # ์ •๋ณด ์ˆ˜์ง‘
166
  info = stock.info
167
  if ".KS" in ticker or ".KQ" in ticker:
168
  info.update(get_naver_stock_info(ticker))
@@ -171,20 +187,17 @@ if "์ข…๋ชฉ ๋ถ„์„" in menu:
171
  pbr = info.get('priceToBook', 'N/A')
172
  currency = info.get('currency', '')
173
 
174
- status.update(label="โœ… Data Ready! Rendering...", state="complete", expanded=False)
175
 
176
- # --- [UI ๋””์ž์ธ] ๋ฉ”ํŠธ๋ฆญ ๋Œ€์‹œ๋ณด๋“œ ---
177
  st.divider()
178
  m1, m2, m3, m4 = st.columns(4)
179
- m1.metric("Current Price", f"{curr:,.2f} {currency}", f"{change_pct:.2f}%")
180
  m2.metric("PER", f"{per}")
181
  m3.metric("PBR", f"{pbr}")
182
- m4.metric("Volume", f"{vol:,.0f}")
183
 
184
- # --- [UI ๋””์ž์ธ] ์บ”๋“ค ์ฐจํŠธ (Plotly) ---
185
  st.plotly_chart(plot_candle_chart(hist, ticker), use_container_width=True)
186
 
187
- # --- AI ๋ฆฌํฌํŠธ ---
188
  st.subheader(f"๐Ÿง  AI Insight: {user_input}")
189
  prompt = f"""
190
  [ROLE] Global Analyst.
@@ -193,19 +206,15 @@ if "์ข…๋ชฉ ๋ถ„์„" in menu:
193
  [LANG] Reply in user's language.
194
  [OUT] Markdown. No Code blocks. 1.Summary 2.Valuation 3.Strategy
195
  """
196
-
197
  messages = [{"role": "user", "content": prompt}]
198
  stream = client.chat.completions.create(
199
  model="Qwen/Qwen2.5-72B-Instruct", messages=messages, stream=True
200
  )
201
-
202
- # ๋ฆฌํฌํŠธ ๋ฐ•์Šค ๋””์ž์ธ
203
  with st.container(border=True):
204
  st.write_stream(parse_stream(stream))
205
-
206
  else:
207
  status.update(label="โŒ No Data", state="error")
208
- st.error("๋ฐ์ดํ„ฐ๋ฅผ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")
209
  except Exception as e:
210
  status.update(label="โŒ Error", state="error")
211
  st.error(f"Error: {e}")
@@ -219,7 +228,6 @@ if "์ข…๋ชฉ ๋ถ„์„" in menu:
219
  elif "์‹œ์žฅ ์Šค์บ๋„ˆ" in menu:
220
  st.subheader("๐Ÿ“ก Global Market Watch")
221
 
222
- # ์ปจํŠธ๋กค ํŒจ๋„
223
  col_sel, col_btn = st.columns([3, 1])
224
  with col_sel:
225
  target_market = st.selectbox("Select Market", list(MARKET_SAMPLES.keys()), label_visibility="collapsed")
@@ -239,13 +247,12 @@ elif "์‹œ์žฅ ์Šค์บ๋„ˆ" in menu:
239
  df = pd.DataFrame({'Price': last, 'Change(%)': pct})
240
  df = df.dropna().sort_values('Change(%)', ascending=False)
241
 
242
- # ์‹œ๊ฐํ™” (์ปฌ๋Ÿผ ๋ถ„ํ• )
243
- st.markdown("##### ๐Ÿ”ฅ Market Heatmap")
244
- st.bar_chart(df['Change(%)'], color=["#00FF00" if x > 0 else "#FF0000" for x in df['Change(%)']])
245
 
246
  c1, c2 = st.columns(2)
247
  with c1:
248
- st.info("๐Ÿš€ Top Gainers")
249
  st.dataframe(df.head(3).style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
250
  with c2:
251
  st.error("๐Ÿ“‰ Top Losers")
 
20
  [data-testid="stMetricValue"] {
21
  font-size: 24px;
22
  }
23
+ div[data-testid="stStatusWidget"] div button {
24
+ display: none;
25
+ }
26
  .st-emotion-cache-1r6slb0 {
27
  border: 1px solid #333;
28
  border-radius: 10px;
 
38
  st.error("๐Ÿšจ ์„ค์ • ์˜ค๋ฅ˜: Secrets์— 'HF_TOKEN'์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.")
39
  st.stop()
40
 
41
+ # --- ๋ฐ์ดํ„ฐ & ์กฑ๋ณด ---
42
  GLOBAL_TICKER_MAP = {
43
  "TSMC": "2330.TW", "MEDIATEK": "2454.TW", "FOXCONN": "2317.TW",
44
  "ALIBABA": "9988.HK", "TENCENT": "0700.HK", "BYD": "1211.HK",
 
102
  if hasattr(delta, 'content') and delta.content:
103
  yield delta.content.replace("```markdown", "").replace("```", "")
104
 
105
+ # --- [์ฐจํŠธ ๊ทธ๋ฆฌ๊ธฐ] ์บ”๋“ค ์ฐจํŠธ ---
106
  def plot_candle_chart(hist, title):
107
  fig = go.Figure(data=[go.Candlestick(
108
  x=hist.index,
109
  open=hist['Open'], high=hist['High'],
110
  low=hist['Low'], close=hist['Close'],
111
+ name="Price"
112
  )])
113
  fig.update_layout(
114
+ title=dict(text=f"{title} Trend", x=0),
115
+ height=350, margin=dict(l=10, r=10, t=40, b=10),
116
+ xaxis_rangeslider_visible=False,
117
+ template="plotly_dark",
118
+ paper_bgcolor='rgba(0,0,0,0)',
119
+ plot_bgcolor='rgba(0,0,0,0)'
120
+ )
121
+ return fig
122
+
123
+ # --- [์ฐจํŠธ ๊ทธ๋ฆฌ๊ธฐ] ๋ง‰๋Œ€ ์ฐจํŠธ (์ปฌ๋Ÿฌ ์—๋Ÿฌ ์ˆ˜์ •๋จ) ---
124
+ def plot_bar_chart(df):
125
+ # ์ƒ์Šน(Green), ํ•˜๋ฝ(Red) ์ƒ‰์ƒ ์ง€์ •
126
+ colors = ['#00FF00' if x > 0 else '#FF0000' for x in df['Change(%)']]
127
+
128
+ fig = go.Figure(go.Bar(
129
+ x=df.index,
130
+ y=df['Change(%)'],
131
+ marker_color=colors, # ์—ฌ๊ธฐ๊ฐ€ ์ˆ˜์ •๋œ ํฌ์ธํŠธ!
132
+ text=df['Change(%)'].apply(lambda x: f"{x:.2f}%"),
133
+ textposition='auto'
134
+ ))
135
+ fig.update_layout(
136
+ title="Market Heatmap (Change %)",
137
+ height=300, margin=dict(l=10, r=10, t=40, b=10),
138
+ template="plotly_dark",
139
+ paper_bgcolor='rgba(0,0,0,0)',
140
  plot_bgcolor='rgba(0,0,0,0)'
141
  )
142
  return fig
 
148
  st.header("๐ŸŒ Pocket Quant Pro")
149
  st.write("AI Powered Global Investment")
150
  st.divider()
 
 
151
  menu = st.radio("MENU", ["๐Ÿ” ์ข…๋ชฉ ๋ถ„์„ (AI Analysis)", "๐Ÿ“ก ์‹œ์žฅ ์Šค์บ๋„ˆ (Market Watch)"], index=0)
 
152
  st.divider()
153
  st.caption("Powered by Qwen-2.5-72B")
 
154
 
155
  # ==============================================================================
156
  # 1. ์ข…๋ชฉ ๋ถ„์„ ๋ชจ๋“œ
 
158
  if "์ข…๋ชฉ ๋ถ„์„" in menu:
159
  st.subheader("๐Ÿ” AI Investment Analyst")
160
 
 
161
  c1, c2 = st.columns([3, 1])
162
  with c1:
163
+ user_input = st.text_input("Ticker or Name", "TSMC", label_visibility="collapsed", placeholder="์ข…๋ชฉ๋ช…")
164
  with c2:
165
  analyze_btn = st.button("Analysis", use_container_width=True)
166
 
 
170
 
171
  if ticker:
172
  try:
 
173
  stock = yf.Ticker(ticker)
174
  hist = stock.history(period="3mo")
175
 
176
  if not hist.empty:
 
177
  curr = hist['Close'].iloc[-1]
178
  prev = hist['Close'].iloc[-2]
179
  change_pct = ((curr - prev) / prev) * 100
180
  vol = hist['Volume'].iloc[-1]
181
 
 
182
  info = stock.info
183
  if ".KS" in ticker or ".KQ" in ticker:
184
  info.update(get_naver_stock_info(ticker))
 
187
  pbr = info.get('priceToBook', 'N/A')
188
  currency = info.get('currency', '')
189
 
190
+ status.update(label="โœ… Rendering...", state="complete", expanded=False)
191
 
 
192
  st.divider()
193
  m1, m2, m3, m4 = st.columns(4)
194
+ m1.metric("Current", f"{curr:,.2f} {currency}", f"{change_pct:.2f}%")
195
  m2.metric("PER", f"{per}")
196
  m3.metric("PBR", f"{pbr}")
197
+ m4.metric("Vol", f"{vol:,.0f}")
198
 
 
199
  st.plotly_chart(plot_candle_chart(hist, ticker), use_container_width=True)
200
 
 
201
  st.subheader(f"๐Ÿง  AI Insight: {user_input}")
202
  prompt = f"""
203
  [ROLE] Global Analyst.
 
206
  [LANG] Reply in user's language.
207
  [OUT] Markdown. No Code blocks. 1.Summary 2.Valuation 3.Strategy
208
  """
 
209
  messages = [{"role": "user", "content": prompt}]
210
  stream = client.chat.completions.create(
211
  model="Qwen/Qwen2.5-72B-Instruct", messages=messages, stream=True
212
  )
 
 
213
  with st.container(border=True):
214
  st.write_stream(parse_stream(stream))
 
215
  else:
216
  status.update(label="โŒ No Data", state="error")
217
+ st.error("๋ฐ์ดํ„ฐ ์—†์Œ")
218
  except Exception as e:
219
  status.update(label="โŒ Error", state="error")
220
  st.error(f"Error: {e}")
 
228
  elif "์‹œ์žฅ ์Šค์บ๋„ˆ" in menu:
229
  st.subheader("๐Ÿ“ก Global Market Watch")
230
 
 
231
  col_sel, col_btn = st.columns([3, 1])
232
  with col_sel:
233
  target_market = st.selectbox("Select Market", list(MARKET_SAMPLES.keys()), label_visibility="collapsed")
 
247
  df = pd.DataFrame({'Price': last, 'Change(%)': pct})
248
  df = df.dropna().sort_values('Change(%)', ascending=False)
249
 
250
+ # [์ˆ˜์ •๋จ] Plotly Bar Chart ์‚ฌ์šฉ (์—๋Ÿฌ ํ•ด๊ฒฐ)
251
+ st.plotly_chart(plot_bar_chart(df), use_container_width=True)
 
252
 
253
  c1, c2 = st.columns(2)
254
  with c1:
255
+ st.success("๐Ÿš€ Top Gainers")
256
  st.dataframe(df.head(3).style.format({"Price": "{:,.2f}", "Change(%)": "{:,.2f}%"}), use_container_width=True)
257
  with c2:
258
  st.error("๐Ÿ“‰ Top Losers")