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