ted163 commited on
Commit
58c9f71
1 Parent(s): 0bd3ef5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +330 -4
app.py CHANGED
@@ -1,7 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
1
+ # import gradio as gr
2
+
3
+ # def greet(name):
4
+ # return "Hello " + name + "!!"
5
+
6
+ # iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
+ # iface.launch()
8
+
9
+
10
+ import os
11
+ import re
12
+ import time
13
+ import json
14
+ import random
15
+ import finnhub
16
+ import torch
17
  import gradio as gr
18
+ import pandas as pd
19
+ import yfinance as yf
20
+ from pynvml import *
21
+ from peft import PeftModel
22
+ from collections import defaultdict
23
+ from datetime import date, datetime, timedelta
24
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
25
+
26
+
27
+ access_token = os.environ["HF_TOKEN"]
28
+ finnhub_client = finnhub.Client(api_key=os.environ["FINNHUB_API_KEY"])
29
+
30
+ base_model = AutoModelForCausalLM.from_pretrained(
31
+ 'meta-llama/Llama-2-7b-chat-hf',
32
+ token=access_token,
33
+ trust_remote_code=True,
34
+ device_map="auto",
35
+ torch_dtype=torch.float16,
36
+ offload_folder="offload/"
37
+ )
38
+ model = PeftModel.from_pretrained(
39
+ base_model,
40
+ 'FinGPT/fingpt-forecaster_dow30_llama2-7b_lora',
41
+ offload_folder="offload/"
42
+ )
43
+ model = model.eval()
44
+
45
+ tokenizer = AutoTokenizer.from_pretrained(
46
+ 'meta-llama/Llama-2-7b-chat-hf',
47
+ token=access_token
48
+ )
49
+
50
+ streamer = TextStreamer(tokenizer)
51
+
52
+ B_INST, E_INST = "[INST]", "[/INST]"
53
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
54
+
55
+ SYSTEM_PROMPT = "You are a seasoned stock market analyst. Your task is to list the positive developments and potential concerns for companies based on relevant news and basic financials from the past weeks, then provide an analysis and prediction for the companies' stock price movement for the upcoming week. " \
56
+ "Your answer format should be as follows:\n\n[Positive Developments]:\n1. ...\n\n[Potential Concerns]:\n1. ...\n\n[Prediction & Analysis]\nPrediction: ...\nAnalysis: ..."
57
+
58
+
59
+ def print_gpu_utilization():
60
+
61
+ nvmlInit()
62
+ handle = nvmlDeviceGetHandleByIndex(0)
63
+ info = nvmlDeviceGetMemoryInfo(handle)
64
+ print(f"GPU memory occupied: {info.used//1024**2} MB.")
65
+
66
+
67
+ def get_curday():
68
+
69
+ return date.today().strftime("%Y-%m-%d")
70
+
71
+
72
+ def n_weeks_before(date_string, n):
73
+
74
+ date = datetime.strptime(date_string, "%Y-%m-%d") - timedelta(days=7*n)
75
+
76
+ return date.strftime("%Y-%m-%d")
77
+
78
+
79
+ def get_stock_data(stock_symbol, steps):
80
+
81
+ stock_data = yf.download(stock_symbol, steps[0], steps[-1])
82
+ if len(stock_data) == 0:
83
+ raise gr.Error(f"Failed to download stock price data for symbol {stock_symbol} from yfinance!")
84
+
85
+ # print(stock_data)
86
+
87
+ dates, prices = [], []
88
+ available_dates = stock_data.index.format()
89
+
90
+ for date in steps[:-1]:
91
+ for i in range(len(stock_data)):
92
+ if available_dates[i] >= date:
93
+ prices.append(stock_data['Close'][i])
94
+ dates.append(datetime.strptime(available_dates[i], "%Y-%m-%d"))
95
+ break
96
+
97
+ dates.append(datetime.strptime(available_dates[-1], "%Y-%m-%d"))
98
+ prices.append(stock_data['Close'][-1])
99
+
100
+ return pd.DataFrame({
101
+ "Start Date": dates[:-1], "End Date": dates[1:],
102
+ "Start Price": prices[:-1], "End Price": prices[1:]
103
+ })
104
+
105
+
106
+ def get_news(symbol, data):
107
+
108
+ news_list = []
109
+
110
+ for end_date, row in data.iterrows():
111
+ start_date = row['Start Date'].strftime('%Y-%m-%d')
112
+ end_date = row['End Date'].strftime('%Y-%m-%d')
113
+ # print(symbol, ': ', start_date, ' - ', end_date)
114
+ time.sleep(1) # control qpm
115
+ weekly_news = finnhub_client.company_news(symbol, _from=start_date, to=end_date)
116
+ if len(weekly_news) == 0:
117
+ raise gr.Error(f"No company news found for symbol {symbol} from finnhub!")
118
+ weekly_news = [
119
+ {
120
+ "date": datetime.fromtimestamp(n['datetime']).strftime('%Y%m%d%H%M%S'),
121
+ "headline": n['headline'],
122
+ "summary": n['summary'],
123
+ } for n in weekly_news
124
+ ]
125
+ weekly_news.sort(key=lambda x: x['date'])
126
+ news_list.append(json.dumps(weekly_news))
127
+
128
+ data['News'] = news_list
129
+
130
+ return data
131
+
132
+
133
+ def get_company_prompt(symbol):
134
+
135
+ profile = finnhub_client.company_profile2(symbol=symbol)
136
+ if not profile:
137
+ raise gr.Error(f"Failed to find company profile for symbol {symbol} from finnhub!")
138
+
139
+ company_template = "[Company Introduction]:\n\n{name} is a leading entity in the {finnhubIndustry} sector. Incorporated and publicly traded since {ipo}, the company has established its reputation as one of the key players in the market. As of today, {name} has a market capitalization of {marketCapitalization:.2f} in {currency}, with {shareOutstanding:.2f} shares outstanding." \
140
+ "\n\n{name} operates primarily in the {country}, trading under the ticker {ticker} on the {exchange}. As a dominant force in the {finnhubIndustry} space, the company continues to innovate and drive progress within the industry."
141
+
142
+ formatted_str = company_template.format(**profile)
143
+
144
+ return formatted_str
145
+
146
+
147
+ def get_prompt_by_row(symbol, row):
148
+
149
+ start_date = row['Start Date'] if isinstance(row['Start Date'], str) else row['Start Date'].strftime('%Y-%m-%d')
150
+ end_date = row['End Date'] if isinstance(row['End Date'], str) else row['End Date'].strftime('%Y-%m-%d')
151
+ term = 'increased' if row['End Price'] > row['Start Price'] else 'decreased'
152
+ head = "From {} to {}, {}'s stock price {} from {:.2f} to {:.2f}. Company news during this period are listed below:\n\n".format(
153
+ start_date, end_date, symbol, term, row['Start Price'], row['End Price'])
154
+
155
+ news = json.loads(row["News"])
156
+ news = ["[Headline]: {}\n[Summary]: {}\n".format(
157
+ n['headline'], n['summary']) for n in news if n['date'][:8] <= end_date.replace('-', '') and \
158
+ not n['summary'].startswith("Looking for stock market analysis and research with proves results?")]
159
+
160
+ basics = json.loads(row['Basics'])
161
+ if basics:
162
+ basics = "Some recent basic financials of {}, reported at {}, are presented below:\n\n[Basic Financials]:\n\n".format(
163
+ symbol, basics['period']) + "\n".join(f"{k}: {v}" for k, v in basics.items() if k != 'period')
164
+ else:
165
+ basics = "[Basic Financials]:\n\nNo basic financial reported."
166
+
167
+ return head, news, basics
168
+
169
+
170
+ def sample_news(news, k=5):
171
+
172
+ return [news[i] for i in sorted(random.sample(range(len(news)), k))]
173
+
174
+
175
+ def get_current_basics(symbol, curday):
176
+
177
+ basic_financials = finnhub_client.company_basic_financials(symbol, 'all')
178
+ if not basic_financials['series']:
179
+ raise gr.Error(f"Failed to find basic financials for symbol {symbol} from finnhub!")
180
+
181
+ final_basics, basic_list, basic_dict = [], [], defaultdict(dict)
182
+
183
+ for metric, value_list in basic_financials['series']['quarterly'].items():
184
+ for value in value_list:
185
+ basic_dict[value['period']].update({metric: value['v']})
186
+
187
+ for k, v in basic_dict.items():
188
+ v.update({'period': k})
189
+ basic_list.append(v)
190
+
191
+ basic_list.sort(key=lambda x: x['period'])
192
+
193
+ for basic in basic_list[::-1]:
194
+ if basic['period'] <= curday:
195
+ break
196
+
197
+ return basic
198
+
199
+
200
+ def get_all_prompts_online(symbol, data, curday, with_basics=True):
201
+
202
+ company_prompt = get_company_prompt(symbol)
203
+
204
+ prev_rows = []
205
+
206
+ for row_idx, row in data.iterrows():
207
+ head, news, _ = get_prompt_by_row(symbol, row)
208
+ prev_rows.append((head, news, None))
209
+
210
+ prompt = ""
211
+ for i in range(-len(prev_rows), 0):
212
+ prompt += "\n" + prev_rows[i][0]
213
+ sampled_news = sample_news(
214
+ prev_rows[i][1],
215
+ min(5, len(prev_rows[i][1]))
216
+ )
217
+ if sampled_news:
218
+ prompt += "\n".join(sampled_news)
219
+ else:
220
+ prompt += "No relative news reported."
221
+
222
+ period = "{} to {}".format(curday, n_weeks_before(curday, -1))
223
+
224
+ if with_basics:
225
+ basics = get_current_basics(symbol, curday)
226
+ basics = "Some recent basic financials of {}, reported at {}, are presented below:\n\n[Basic Financials]:\n\n".format(
227
+ symbol, basics['period']) + "\n".join(f"{k}: {v}" for k, v in basics.items() if k != 'period')
228
+ else:
229
+ basics = "[Basic Financials]:\n\nNo basic financial reported."
230
+
231
+ info = company_prompt + '\n' + prompt + '\n' + basics
232
+ prompt = info + f"\n\nBased on all the information before {curday}, let's first analyze the positive developments and potential concerns for {symbol}. Come up with 2-4 most important factors respectively and keep them concise. Most factors should be inferred from company related news. " \
233
+ f"Then make your prediction of the {symbol} stock price movement for next week ({period}). Provide a summary analysis to support your prediction."
234
+
235
+ return info, prompt
236
+
237
+
238
+ def construct_prompt(ticker, curday, n_weeks, use_basics):
239
+
240
+ try:
241
+ steps = [n_weeks_before(curday, n) for n in range(n_weeks + 1)][::-1]
242
+ except Exception:
243
+ raise gr.Error(f"Invalid date {curday}!")
244
+
245
+ data = get_stock_data(ticker, steps)
246
+ data = get_news(ticker, data)
247
+ data['Basics'] = [json.dumps({})] * len(data)
248
+ # print(data)
249
+
250
+ info, prompt = get_all_prompts_online(ticker, data, curday, use_basics)
251
+
252
+ prompt = B_INST + B_SYS + SYSTEM_PROMPT + E_SYS + prompt + E_INST
253
+ # print(prompt)
254
+
255
+ return info, prompt
256
+
257
+
258
+ def predict(ticker, date, n_weeks, use_basics):
259
+
260
+ print_gpu_utilization()
261
+
262
+ info, prompt = construct_prompt(ticker, date, n_weeks, use_basics)
263
+
264
+ inputs = tokenizer(
265
+ prompt, return_tensors='pt', padding=False
266
+ )
267
+ inputs = {key: value.to(model.device) for key, value in inputs.items()}
268
+
269
+ print("Inputs loaded onto devices.")
270
+
271
+ res = model.generate(
272
+ **inputs, max_length=4096, do_sample=True,
273
+ eos_token_id=tokenizer.eos_token_id,
274
+ use_cache=True, streamer=streamer
275
+ )
276
+ output = tokenizer.decode(res[0], skip_special_tokens=True)
277
+ answer = re.sub(r'.*\[/INST\]\s*', '', output, flags=re.DOTALL)
278
+
279
+ torch.cuda.empty_cache()
280
+
281
+ return info, answer
282
+
283
+
284
+ demo = gr.Interface(
285
+ predict,
286
+ inputs=[
287
+ gr.Textbox(
288
+ label="Ticker",
289
+ value="AAPL",
290
+ info="Companys from Dow-30 are recommended"
291
+ ),
292
+ gr.Textbox(
293
+ label="Date",
294
+ value=get_curday,
295
+ info="Date from which the prediction is made, use format yyyy-mm-dd"
296
+ ),
297
+ gr.Slider(
298
+ minimum=1,
299
+ maximum=4,
300
+ value=3,
301
+ step=1,
302
+ label="n_weeks",
303
+ info="Information of the past n weeks will be utilized, choose between 1 and 4"
304
+ ),
305
+ gr.Checkbox(
306
+ label="Use Latest Basic Financials",
307
+ value=False,
308
+ info="If checked, the latest quarterly reported basic financials of the company is taken into account."
309
+ )
310
+ ],
311
+ outputs=[
312
+ gr.Textbox(
313
+ label="Information"
314
+ ),
315
+ gr.Textbox(
316
+ label="Response"
317
+ )
318
+ ],
319
+ title="FinGPT-Forecaster",
320
+ description="""FinGPT-Forecaster takes random market news and optional basic financials related to the specified company from the past few weeks as input and responds with the company's **positive developments** and **potential concerns**. Then it gives out a **prediction** of stock price movement for the coming week and its **analysis** summary.
321
+ This model is finetuned on Llama2-7b-chat-hf with LoRA on the past year's DOW30 market data. Inference in this demo uses fp16 and **welcomes any ticker symbol**.
322
+ Company profile & Market news & Basic financials & Stock prices are retrieved using **yfinance & finnhub**.
323
+ For more detailed and customized implementation, refer to our FinGPT project: <https://github.com/AI4Finance-Foundation/FinGPT>
324
+ ⚠️Warning: This is just a demo showing what this model is capable of. During each individual inference, company news is **randomly sampled** from all the news from designated weeks, which might result in **different predictions for the same time period**.
325
+ We suggest users deploy the [original model](https://huggingface.co/FinGPT/fingpt-forecaster_dow30_llama2-7b_lora) or clone this space and inference with more carefully selected news in their own favorable ways.
326
+ Setting do_sample=False or modifying the temperature during the generation process also helps stabilize the prediction result.
327
+ **Disclaimer: Nothing herein is financial advice, and NOT a recommendation to trade real money. Please use common sense and always first consult a professional before trading or investing.**
328
+ """
329
+ )
330
+
331
+ demo.launch()
332
 
 
 
333