YongjiangChen commited on
Commit
b89fc2c
1 Parent(s): 68946f5

Add application file

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