Upload app_stock.py

#4
by BaoKhuong - opened
Files changed (1) hide show
  1. app_stock.py +274 -0
app_stock.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, json, time, random
2
+ from collections import defaultdict
3
+ from datetime import date, datetime, timedelta
4
+ import gradio as gr
5
+
6
+ import pandas as pd
7
+ import finnhub
8
+ from openai import OpenAI
9
+
10
+ from io import StringIO
11
+ import requests
12
+
13
+
14
+ # ---------- 0 CONFIG ---------------------------------------------------------
15
+
16
+ OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
17
+ FINNHUB_KEY = os.getenv("FINNHUB_API_KEY")
18
+ ALPHA_KEY = os.getenv("ALPHAVANTAGE_API_KEY")
19
+
20
+ if not FINNHUB_KEY:
21
+ raise RuntimeError("FINNHUB_API_KEY not set")
22
+
23
+ client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
24
+ finnhub_client = finnhub.Client(api_key=FINNHUB_KEY)
25
+
26
+
27
+ SYSTEM_PROMPT = (
28
+ "You are a seasoned stock-market analyst. "
29
+ "Given recent company news and optional basic financials, "
30
+ "return:\n"
31
+ "[Positive Developments] – 2-4 bullets\n"
32
+ "[Potential Concerns] – 2-4 bullets\n"
33
+ "[Prediction & Analysis] – a one-week price outlook with rationale."
34
+ )
35
+
36
+
37
+ # ---------- 1 DATE / UTILITY HELPERS ----------------------------------------
38
+
39
+ def today() -> str:
40
+ return date.today().strftime("%Y-%m-%d")
41
+
42
+ def n_weeks_before(date_string: str, n: int) -> str:
43
+ return (datetime.strptime(date_string, "%Y-%m-%d") -
44
+ timedelta(days=7 * n)).strftime("%Y-%m-%d")
45
+
46
+
47
+ # ---------- 2 DATA FETCHING --------------------------------------------------
48
+
49
+ def get_stock_data(symbol: str, steps: list[str]) -> pd.DataFrame:
50
+
51
+ if not ALPHA_KEY:
52
+ raise RuntimeError("ALPHAVANTAGE_API_KEY is Missing")
53
+
54
+ # 免费端点:TIME_SERIES_DAILY :contentReference[oaicite:8]{index=8}
55
+ url = (
56
+ "https://www.alphavantage.co/query"
57
+ "?function=TIME_SERIES_DAILY"
58
+ f"&symbol={symbol}"
59
+ f"&apikey={ALPHA_KEY}"
60
+ "&datatype=csv"
61
+ "&outputsize=full"
62
+ )
63
+
64
+ # 重试 3 次
65
+ text = None
66
+ for attempt in range(3):
67
+ resp = requests.get(url, timeout=10)
68
+ if not resp.ok:
69
+ time.sleep(1)
70
+ continue
71
+ text = resp.text.strip()
72
+ if text.startswith("{"):
73
+ info = resp.json()
74
+ msg = info.get("Note") or info.get("Error Message") or str(info)
75
+ raise RuntimeError(f"Alpha Vantage Return Error:{msg}")
76
+ break
77
+
78
+ if not text:
79
+ raise RuntimeError(f"Alpha Vantage Connection Error:{url}")
80
+
81
+ df = pd.read_csv(StringIO(text))
82
+ date_col = "timestamp" if "timestamp" in df.columns else df.columns[0]
83
+ df[date_col] = pd.to_datetime(df[date_col])
84
+ df = df.sort_values(date_col).set_index(date_col)
85
+
86
+ data = {"Start Date": [], "End Date": [], "Start Price": [], "End Price": []}
87
+ for i in range(len(steps) - 1):
88
+ s_date = pd.to_datetime(steps[i])
89
+ e_date = pd.to_datetime(steps[i+1])
90
+ seg = df.loc[s_date:e_date]
91
+ if seg.empty:
92
+ raise RuntimeError(
93
+ f"Alpha Vantage 无法获取 {symbol} 在 {steps[i]} – {steps[i+1]} 的数据"
94
+ )
95
+ data["Start Date"].append(seg.index[0])
96
+ data["Start Price"].append(seg["close"].iloc[0])
97
+ data["End Date"].append(seg.index[-1])
98
+ data["End Price"].append(seg["close"].iloc[-1])
99
+ # Limits:5 times/min
100
+ time.sleep(12)
101
+
102
+ return pd.DataFrame(data)
103
+
104
+ def current_basics(symbol: str, curday: str) -> dict:
105
+ raw = finnhub_client.company_basic_financials(symbol, "all")
106
+ if not raw["series"]:
107
+ return {}
108
+ merged = defaultdict(dict)
109
+ for metric, vals in raw["series"]["quarterly"].items():
110
+ for v in vals:
111
+ merged[v["period"]][metric] = v["v"]
112
+
113
+ latest = max((p for p in merged if p <= curday), default=None)
114
+ if latest is None:
115
+ return {}
116
+ d = dict(merged[latest])
117
+ d["period"] = latest
118
+ return d
119
+
120
+ def attach_news(symbol: str, df: pd.DataFrame) -> pd.DataFrame:
121
+ news_col = []
122
+ for _, row in df.iterrows():
123
+ start = row["Start Date"].strftime("%Y-%m-%d")
124
+ end = row["End Date"].strftime("%Y-%m-%d")
125
+ time.sleep(1) # Finnhub QPM guard
126
+ weekly = finnhub_client.company_news(symbol, _from=start, to=end)
127
+ weekly_fmt = [
128
+ {
129
+ "date" : datetime.fromtimestamp(n["datetime"]).strftime("%Y%m%d%H%M%S"),
130
+ "headline": n["headline"],
131
+ "summary" : n["summary"],
132
+ }
133
+ for n in weekly
134
+ ]
135
+ weekly_fmt.sort(key=lambda x: x["date"])
136
+ news_col.append(json.dumps(weekly_fmt))
137
+ df["News"] = news_col
138
+ return df
139
+
140
+
141
+ # ---------- 3 PROMPT CONSTRUCTION -------------------------------------------
142
+
143
+ def sample_news(news: list[str], k: int = 5) -> list[str]:
144
+ if len(news) <= k: return news
145
+ return [news[i] for i in sorted(random.sample(range(len(news)), k))]
146
+
147
+
148
+ def make_prompt(symbol: str, df: pd.DataFrame, curday: str, use_basics=False) -> str:
149
+ # Company profile
150
+ prof = finnhub_client.company_profile2(symbol=symbol)
151
+ company_blurb = (
152
+ f"[Company Introduction]:\n{prof['name']} operates in the "
153
+ f"{prof['finnhubIndustry']} sector ({prof['country']}). "
154
+ f"Founded {prof['ipo']}, market cap {prof['marketCapitalization']:.1f} "
155
+ f"{prof['currency']}; ticker {symbol} on {prof['exchange']}.\n"
156
+ )
157
+
158
+ # Past weeks block
159
+ past_block = ""
160
+ for _, row in df.iterrows():
161
+ term = "increased" if row["End Price"] > row["Start Price"] else "decreased"
162
+ head = (f"From {row['Start Date']:%Y-%m-%d} to {row['End Date']:%Y-%m-%d}, "
163
+ f"{symbol}'s stock price {term} from "
164
+ f"{row['Start Price']:.2f} to {row['End Price']:.2f}.")
165
+ news_items = json.loads(row["News"])
166
+ summaries = [
167
+ f"[Headline] {n['headline']}\n[Summary] {n['summary']}\n"
168
+ for n in news_items
169
+ if not n["summary"].startswith("Looking for stock market analysis")
170
+ ]
171
+ past_block += "\n" + head + "\n" + "".join(sample_news(summaries, 5))
172
+
173
+ # Optional basic financials
174
+ if use_basics:
175
+ basics = current_basics(symbol, curday)
176
+ if basics:
177
+ basics_txt = "\n".join(f"{k}: {v}" for k, v in basics.items() if k != "period")
178
+ basics_block = (f"\n[Basic Financials] (reported {basics['period']}):\n{basics_txt}\n")
179
+ else:
180
+ basics_block = "\n[Basic Financials]: not available\n"
181
+ else:
182
+ basics_block = "\n[Basic Financials]: not requested\n"
183
+
184
+ horizon = f"{curday} to {n_weeks_before(curday, -1)}"
185
+ final_user_msg = (
186
+ company_blurb
187
+ + past_block
188
+ + basics_block
189
+ + f"\nBased on all information before {curday}, analyse positive "
190
+ "developments and potential concerns for {symbol}, then predict its "
191
+ f"price movement for next week ({horizon})."
192
+ )
193
+ return final_user_msg
194
+
195
+
196
+ # ---------- 4 LLM CALL -------------------------------------------------------
197
+
198
+ def chat_completion(prompt: str,
199
+ model: str = OPENAI_MODEL,
200
+ temperature: float = 0.3,
201
+ stream: bool = False) -> str:
202
+
203
+ response = client.chat.completions.create(
204
+ model=model,
205
+ temperature=temperature,
206
+ stream=stream,
207
+ messages=[
208
+ {"role": "system", "content": SYSTEM_PROMPT},
209
+ {"role": "user", "content": prompt}
210
+ ],
211
+ )
212
+
213
+ if stream:
214
+ collected = []
215
+ for chunk in response:
216
+ delta = chunk.choices[0].delta.content or ""
217
+ print(delta, end="", flush=True)
218
+ collected.append(delta)
219
+ print()
220
+ return "".join(collected)
221
+
222
+ # without stream
223
+ return response.choices[0].message.content
224
+
225
+
226
+ # ---------- 5 MAIN ENTRY (CLI test) -----------------------------------------
227
+
228
+ def predict(symbol: str = "AAPL",
229
+ curday: str = today(),
230
+ n_weeks: int = 3,
231
+ use_basics: bool = False,
232
+ stream: bool = False) -> tuple[str, str]:
233
+ steps = [n_weeks_before(curday, n) for n in range(n_weeks + 1)][::-1]
234
+ df = get_stock_data(symbol, steps)
235
+ df = attach_news(symbol, df)
236
+
237
+ prompt_info = make_prompt(symbol, df, curday, use_basics)
238
+ answer = chat_completion(prompt_info, stream=stream)
239
+
240
+ return prompt_info, answer
241
+
242
+
243
+
244
+ # ---------- 6 SETUP HF -----------------------------------------
245
+
246
+
247
+ def hf_predict(symbol, n_weeks, use_basics):
248
+ # 1. get curday
249
+ curday = date.today().strftime("%Y-%m-%d")
250
+ # 2. call predict
251
+ prompt, answer = predict(
252
+ symbol=symbol.upper(),
253
+ curday=curday,
254
+ n_weeks=int(n_weeks),
255
+ use_basics=bool(use_basics),
256
+ stream=False
257
+ )
258
+ return prompt, answer
259
+
260
+ with gr.Blocks() as demo:
261
+ gr.Markdown("FinRobot_Forecaster")
262
+ with gr.Row():
263
+ symbol = gr.Textbox(label="Ticker(eg. AAPL)", value="AAPL")
264
+ n_weeks = gr.Slider(1, 6, value=3, step=1, label="Trace Back Weeks")
265
+ use_basics = gr.Checkbox(label="Add Basic Financials", value=False)
266
+ output_prompt = gr.Textbox(label="Model Prompt", lines=8)
267
+ output_answer = gr.Textbox(label="Model Output", lines=12)
268
+ btn = gr.Button("Run Forecaster")
269
+ btn.click(fn=hf_predict,
270
+ inputs=[symbol, n_weeks, use_basics],
271
+ outputs=[output_prompt, output_answer])
272
+
273
+ if __name__ == "__main__":
274
+ demo.launch()