No1r97 commited on
Commit
9251391
1 Parent(s): 835cde3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -21
app.py CHANGED
@@ -1,12 +1,20 @@
1
  import re
 
 
 
 
2
  import gradio as gr
 
 
3
  from transformers import AutoTokenizer, AutoModelForCausalLM
4
  from peft import PeftModel
5
- from datetime import date
6
 
7
 
8
  access_token = "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"
9
 
 
 
10
  base_model = AutoModelForCausalLM.from_pretrained(
11
  'meta-llama/Llama-2-7b-chat-hf',
12
  token=access_token,
@@ -27,9 +35,12 @@ tokenizer = AutoTokenizer.from_pretrained(
27
  )
28
 
29
 
30
- def construct_prompt(ticker, date, n_weeks):
31
-
32
- return ", ".join([ticker, date, str(n_weeks)])
 
 
 
33
 
34
 
35
  def get_curday():
@@ -37,27 +48,198 @@ def get_curday():
37
  return date.today().strftime("%Y-%m-%d")
38
 
39
 
40
- def predict(ticker, date, n_weeks):
41
 
42
- prompt = construct_prompt(ticker, date, n_weeks)
43
-
44
- # inputs = tokenizer(
45
- # prompt, return_tensors='pt',
46
- # padding=False, max_length=4096
47
- # )
48
- # inputs = {key: value.to(model.device) for key, value in inputs.items()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- # res = model.generate(
51
- # **inputs, max_length=4096, do_sample=True,
52
- # eos_token_id=tokenizer.eos_token_id,
53
- # use_cache=True
54
- # )
55
- # output = tokenizer.decode(res[0], skip_special_tokens=True)
56
- # answer = re.sub(r'.*\[/INST\]\s*', '', output, flags=re.DOTALL)
 
 
 
 
 
 
 
57
 
58
- answer = prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- return answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
 
63
  demo = gr.Interface(
@@ -80,9 +262,17 @@ demo = gr.Interface(
80
  step=1,
81
  label="n_weeks",
82
  info="Information of the past n weeks will be utilized, choose between 1 and 4"
 
 
 
 
 
83
  )
84
  ],
85
  outputs=[
 
 
 
86
  gr.Textbox(
87
  label="Response"
88
  )
 
1
  import re
2
+ import time
3
+ import json
4
+ import random
5
+ import finnhub
6
  import gradio as gr
7
+ import pandas as pd
8
+ import yfinance as yf
9
  from transformers import AutoTokenizer, AutoModelForCausalLM
10
  from peft import PeftModel
11
+ from datetime import date, datetime, timedelta
12
 
13
 
14
  access_token = "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"
15
 
16
+ finnhub_client = finnhub.Client(api_key="ckrn2mpr01qiu0ijr9hgckrn2mpr01qiu0ijr9i0")
17
+
18
  base_model = AutoModelForCausalLM.from_pretrained(
19
  'meta-llama/Llama-2-7b-chat-hf',
20
  token=access_token,
 
35
  )
36
 
37
 
38
+ B_INST, E_INST = "[INST]", "[/INST]"
39
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
40
+
41
+ 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. " \
42
+ "Your answer format should be as follows:\n\n[Positive Developments]:\n1. ...\n\n[Potential Concerns]:\n1. ...\n\n[Prediction & Analysis]\nPrediction: ...\nAnalysis: ..."
43
+
44
 
45
 
46
  def get_curday():
 
48
  return date.today().strftime("%Y-%m-%d")
49
 
50
 
51
+ def n_weeks_before(date_string, n):
52
 
53
+ date = datetime.strptime(date_string, "%Y-%m-%d") - timedelta(days=7*n)
54
+
55
+ return date.strftime("%Y-%m-%d")
56
+
57
+
58
+ def get_stock_data(stock_symbol, steps):
59
+
60
+ stock_data = yf.download(stock_symbol, steps[0], steps[-1])
61
+
62
+ # print(stock_data)
63
+
64
+ dates, prices = [], []
65
+ available_dates = stock_data.index.format()
66
+
67
+ for date in steps[:-1]:
68
+ for i in range(len(stock_data)):
69
+ if available_dates[i] >= date:
70
+ prices.append(stock_data['Close'][i])
71
+ dates.append(datetime.strptime(available_dates[i], "%Y-%m-%d"))
72
+ break
73
+
74
+ dates.append(datetime.strptime(available_dates[-1], "%Y-%m-%d"))
75
+ prices.append(stock_data['Close'][-1])
76
+
77
+ return pd.DataFrame({
78
+ "Start Date": dates[:-1], "End Date": dates[1:],
79
+ "Start Price": prices[:-1], "End Price": prices[1:]
80
+ })
81
+
82
+
83
+ def get_news(symbol, data):
84
+
85
+ news_list = []
86
+
87
+ for end_date, row in data.iterrows():
88
+ start_date = row['Start Date'].strftime('%Y-%m-%d')
89
+ end_date = row['End Date'].strftime('%Y-%m-%d')
90
+ # print(symbol, ': ', start_date, ' - ', end_date)
91
+ time.sleep(1) # control qpm
92
+ weekly_news = finnhub_client.company_news(symbol, _from=start_date, to=end_date)
93
+ weekly_news = [
94
+ {
95
+ "date": datetime.fromtimestamp(n['datetime']).strftime('%Y%m%d%H%M%S'),
96
+ "headline": n['headline'],
97
+ "summary": n['summary'],
98
+ } for n in weekly_news
99
+ ]
100
+ weekly_news.sort(key=lambda x: x['date'])
101
+ news_list.append(json.dumps(weekly_news))
102
+
103
+ data['News'] = news_list
104
+
105
+ return data
106
+
107
+
108
+ def get_company_prompt(symbol):
109
+
110
+ profile = finnhub_client.company_profile2(symbol=symbol)
111
+
112
+ 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." \
113
+ "\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."
114
+
115
+ formatted_str = company_template.format(**profile)
116
+
117
+ return formatted_str
118
+
119
+
120
+ def get_prompt_by_row(symbol, row):
121
+
122
+ start_date = row['Start Date'] if isinstance(row['Start Date'], str) else row['Start Date'].strftime('%Y-%m-%d')
123
+ end_date = row['End Date'] if isinstance(row['End Date'], str) else row['End Date'].strftime('%Y-%m-%d')
124
+ term = 'increased' if row['End Price'] > row['Start Price'] else 'decreased'
125
+ head = "From {} to {}, {}'s stock price {} from {:.2f} to {:.2f}. Company news during this period are listed below:\n\n".format(
126
+ start_date, end_date, symbol, term, row['Start Price'], row['End Price'])
127
+
128
+ news = json.loads(row["News"])
129
+ news = ["[Headline]: {}\n[Summary]: {}\n".format(
130
+ n['headline'], n['summary']) for n in news if n['date'][:8] <= end_date.replace('-', '') and \
131
+ not n['summary'].startswith("Looking for stock market analysis and research with proves results?")]
132
+
133
+ basics = json.loads(row['Basics'])
134
+ if basics:
135
+ basics = "Some recent basic financials of {}, reported at {}, are presented below:\n\n[Basic Financials]:\n\n".format(
136
+ symbol, basics['period']) + "\n".join(f"{k}: {v}" for k, v in basics.items() if k != 'period')
137
+ else:
138
+ basics = "[Basic Financials]:\n\nNo basic financial reported."
139
+
140
+ return head, news, basics
141
+
142
+
143
+ def sample_news(news, k=5):
144
+
145
+ return [news[i] for i in sorted(random.sample(range(len(news)), k))]
146
+
147
+
148
+ def get_current_basics(symbol, curday):
149
+
150
+ basic_financials = finnhub_client.company_basic_financials(symbol, 'all')
151
+
152
+ final_basics, basic_list, basic_dict = [], [], defaultdict(dict)
153
+
154
+ for metric, value_list in basic_financials['series']['quarterly'].items():
155
+ for value in value_list:
156
+ basic_dict[value['period']].update({metric: value['v']})
157
+
158
+ for k, v in basic_dict.items():
159
+ v.update({'period': k})
160
+ basic_list.append(v)
161
 
162
+ basic_list.sort(key=lambda x: x['period'])
163
+
164
+ for basic in basic_list[::-1]:
165
+ if basic['period'] <= curday:
166
+ break
167
+
168
+ return basic
169
+
170
+
171
+ def get_all_prompts_online(symbol, data, curday, with_basics=True):
172
+
173
+ company_prompt = get_company_prompt(symbol)
174
+
175
+ prev_rows = []
176
 
177
+ for row_idx, row in data.iterrows():
178
+ head, news, _ = get_prompt_by_row(symbol, row)
179
+ prev_rows.append((head, news, None))
180
+
181
+ prompt = ""
182
+ for i in range(-len(prev_rows), 0):
183
+ prompt += "\n" + prev_rows[i][0]
184
+ sampled_news = sample_news(
185
+ prev_rows[i][1],
186
+ min(5, len(prev_rows[i][1]))
187
+ )
188
+ if sampled_news:
189
+ prompt += "\n".join(sampled_news)
190
+ else:
191
+ prompt += "No relative news reported."
192
+
193
+ period = "{} to {}".format(curday, n_weeks_before(curday, -1))
194
 
195
+ if with_basics:
196
+ basics = get_current_basics(symbol, curday)
197
+ basics = "Some recent basic financials of {}, reported at {}, are presented below:\n\n[Basic Financials]:\n\n".format(
198
+ symbol, basics['period']) + "\n".join(f"{k}: {v}" for k, v in basics.items() if k != 'period')
199
+ else:
200
+ basics = "[Basic Financials]:\n\nNo basic financial reported."
201
+
202
+ info = company_prompt + '\n' + prompt + '\n' + basics
203
+ 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. " \
204
+ f"Then make your prediction of the {symbol} stock price movement for next week ({period}). Provide a summary analysis to support your prediction."
205
+
206
+ return info, prompt
207
+
208
+
209
+ def construct_prompt(ticker, date, n_weeks, use_basics):
210
+
211
+ curday = get_curday()
212
+ steps = [n_weeks_before(curday, n) for n in range(n_weeks + 1)][::-1]
213
+ data = get_stock_data(ticker, steps)
214
+ data = get_news(ticker, data)
215
+ data['Basics'] = [json.dumps({})] * len(data)
216
+
217
+ info, prompt = get_all_prompts_online(ticker, data, curday, use_basics)
218
+
219
+ prompt = B_INST + B_SYS + SYSTEM_PROMPT + E_SYS + prompt + E_INST
220
+
221
+ return info, prompt
222
+
223
+
224
+ def predict(ticker, date, n_weeks, use_basics):
225
+
226
+ info, prompt = construct_prompt(ticker, date, n_weeks, use_basics)
227
+
228
+ inputs = tokenizer(
229
+ prompt, return_tensors='pt',
230
+ padding=False, max_length=4096
231
+ )
232
+ inputs = {key: value.to(model.device) for key, value in inputs.items()}
233
+
234
+ res = model.generate(
235
+ **inputs, max_length=4096, do_sample=True,
236
+ eos_token_id=tokenizer.eos_token_id,
237
+ use_cache=True
238
+ )
239
+ output = tokenizer.decode(res[0], skip_special_tokens=True)
240
+ answer = re.sub(r'.*\[/INST\]\s*', '', output, flags=re.DOTALL)
241
+
242
+ return info, answer
243
 
244
 
245
  demo = gr.Interface(
 
262
  step=1,
263
  label="n_weeks",
264
  info="Information of the past n weeks will be utilized, choose between 1 and 4"
265
+ ),
266
+ gradio.Checkbox(
267
+ label="Use Latest Financial Basics",
268
+ value=False,
269
+ info="If checked, the latest quarterly reported financial basics of the company is taken into account."
270
  )
271
  ],
272
  outputs=[
273
+ gr.Textbox(
274
+ label="Information"
275
+ ),
276
  gr.Textbox(
277
  label="Response"
278
  )