dlflannery commited on
Commit
ee17b4a
·
verified ·
1 Parent(s): d891f63

Update app.py

Browse files

Stock plots 40 days

Files changed (1) hide show
  1. app.py +97 -12
app.py CHANGED
@@ -21,6 +21,7 @@ import pandas as pd
21
  import yfinance as yf
22
  from datetime import datetime, timedelta
23
  import pytz
 
24
 
25
 
26
  load_dotenv(override=True)
@@ -96,16 +97,20 @@ def stock_list():
96
  rv += f'{symbol} {name}\n'
97
  return rv
98
 
99
- def get_stock_news(search_symbol):
100
  stock_list = {}
101
- fuzzy = True
102
- have_symbol = False
103
- search_symbol = search_symbol.strip().upper()
104
  with open(stock_data_path, 'rt') as fp:
105
  lines = fp.readlines()
106
  for line in lines:
107
  (name, symbol, shares) = line.rstrip().split(',')
108
- stock_list[symbol.strip()] = name.strip()
 
 
 
 
 
 
 
109
  search_term = search_symbol
110
  if search_symbol in stock_list.keys():
111
  have_symbol = True
@@ -155,7 +160,7 @@ def stock_week_df(symbol):
155
  etime = etz_now()
156
  if etime.hour >= 16:
157
  etime = etime + timedelta(days=1)
158
- week_ago = etime - timedelta(days=8)
159
  end = etime.strftime('%Y-%m-%d')
160
  start = week_ago.strftime('%Y-%m-%d')
161
  df = yf.download(symbol.upper(),
@@ -169,12 +174,12 @@ def stock_week_df(symbol):
169
  for i in range(numDays):
170
  valsTxt.append(vals2d[i][0])
171
  for val in valsTxt:
172
- v = float(val)
173
  values.append(v)
174
  if v > ymax:
175
  ymax = v
176
  for row in df.index:
177
- dates.append(row.strftime('%Y-%m-%d'))
178
  data = {
179
  "date": dates,
180
  "value" : values
@@ -263,6 +268,85 @@ def get_last_closing(symbol, offset=0, timeout=10):
263
  except:
264
  return (0.0, "0000-00-00")
265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  def create_stock_data_file(txt):
267
  with open(stock_data_path, 'wt') as fp:
268
  fp.write(txt)
@@ -496,7 +580,7 @@ def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_ima
496
  if args[1] == 'value':
497
  return [past, md(response), None, gptModel, uploaded_image_file, plot]
498
  elif args[1] == 'history':
499
- (plot_df, ymax) = stock_history_df(12)
500
  # ymax = float(ymax)
501
  return [past, md(response), None, gptModel, uploaded_image_file,
502
  gr.LinePlot(plot_df, x="date", y="value", visible=True,
@@ -506,12 +590,13 @@ def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_ima
506
  symbol = ' '.join(args[2:])
507
  (response, plot_df, ymax) = get_stock_news(symbol)
508
  ymax *= 1.1
 
509
  if plot_df.empty:
510
- return [past, md(response), None, gptModel, uploaded_image_file, plot]
511
  else:
512
- return [past, md(response), None, gptModel, uploaded_image_file,
513
  gr.LinePlot(plot_df, x="date", y="value", visible=True,
514
- y_lim=[0, ymax],label=f"{symbol} Recent Prices")]
515
  # elif arg[1] == 'history':
516
  # symbol = arg[2]
517
  # response = 'ok' # get_
 
21
  import yfinance as yf
22
  from datetime import datetime, timedelta
23
  import pytz
24
+ import math
25
 
26
 
27
  load_dotenv(override=True)
 
97
  rv += f'{symbol} {name}\n'
98
  return rv
99
 
100
+ def get_stock_list():
101
  stock_list = {}
 
 
 
102
  with open(stock_data_path, 'rt') as fp:
103
  lines = fp.readlines()
104
  for line in lines:
105
  (name, symbol, shares) = line.rstrip().split(',')
106
+ stock_list[symbol.strip()] = (name.strip(),shares.strip())
107
+ return stock_list
108
+
109
+ def get_stock_news(search_symbol):
110
+ fuzzy = True
111
+ have_symbol = False
112
+ search_symbol = search_symbol.strip().upper()
113
+ stock_list = get_stock_list()
114
  search_term = search_symbol
115
  if search_symbol in stock_list.keys():
116
  have_symbol = True
 
160
  etime = etz_now()
161
  if etime.hour >= 16:
162
  etime = etime + timedelta(days=1)
163
+ week_ago = etime - timedelta(days=40) # was 8
164
  end = etime.strftime('%Y-%m-%d')
165
  start = week_ago.strftime('%Y-%m-%d')
166
  df = yf.download(symbol.upper(),
 
174
  for i in range(numDays):
175
  valsTxt.append(vals2d[i][0])
176
  for val in valsTxt:
177
+ v = round(float(val),2)
178
  values.append(v)
179
  if v > ymax:
180
  ymax = v
181
  for row in df.index:
182
+ dates.append(row.strftime('%m-%d'))
183
  data = {
184
  "date": dates,
185
  "value" : values
 
268
  except:
269
  return (0.0, "0000-00-00")
270
 
271
+ def get_total_daily_closing_sequence(num_days):
272
+ try:
273
+ first_loop = True
274
+ max_val = 0.0
275
+ stock_list = get_stock_list()
276
+ symbols = [s for s in stock_list.keys()]
277
+ # symbols = symbols[8:10]
278
+ etime = etz_now()
279
+ if etime.hour >= 16:
280
+ etime = etime + timedelta(days=1)
281
+ end = etime.strftime('%Y-%m-%d')
282
+ start_time = etime - timedelta(days = num_days)
283
+ start = start_time.strftime('%Y-%m-%d')
284
+ df = yf.download(symbols,
285
+ start = start,
286
+ end = end,
287
+ progress = False,
288
+ )
289
+ # val2d = df.values.tolist()
290
+ dates = []
291
+ for row in df.index:
292
+ dates.append(row.strftime('%m-%d'))
293
+ # columns = list(df.columns.values)
294
+ # cvals = df[columns[0]].tolist()
295
+
296
+ for sym in symbols:
297
+ (name, shares) = stock_list[sym]
298
+ values = df[('Close', sym)].tolist()
299
+ n = len(values)
300
+ for i in range(n):
301
+ if math.isnan(float(values[i])):
302
+ if i == 0:
303
+ values[0] = values[1]
304
+ else:
305
+ values[i] = values[i-1]
306
+ if first_loop:
307
+ first_loop = False
308
+ total_values = values.copy()
309
+ for i in range(n):
310
+ total_values[i] = float(total_values[i]) * float(shares)
311
+ else:
312
+ for i in range(n):
313
+ total_values[i] += (float(values[i]) * float(shares))
314
+ for i in range(n):
315
+ total_values[i] = round(total_values[i], 2)
316
+ if total_values[i] > max_val:
317
+ max_val = total_values[i]
318
+ data = {
319
+ "date": dates,
320
+ "value" : total_values
321
+ }
322
+ return (pd.DataFrame(data), max_val)
323
+ except:
324
+ return (pd.DataFrame(), 0.0)
325
+
326
+ def get_daily_closing_sequence(symbol, num_days):
327
+ try:
328
+ dates = []
329
+ values = []
330
+ etime = etz_now()
331
+ if etime.hour >= 16:
332
+ etime = etime + timedelta(days=1)
333
+ end = etime.strftime('%Y-%m-%d')
334
+ start_time = etime - timedelta(days = num_days)
335
+ start = start_time.strftime('%Y-%m-%d')
336
+ df = yf.download(symbol,
337
+ start = start,
338
+ end = end,
339
+ progress = False,
340
+ )
341
+ vals2d = df.values.tolist()
342
+ valsTxt = []
343
+ values = [round(float(vals2d[i][0]),2) for i in range(len(vals2d))]
344
+ for row in df.index:
345
+ dates.append(row.strftime('%Y-%m-%d'))
346
+ return(dates, values)
347
+ except:
348
+ return([],[])
349
+
350
  def create_stock_data_file(txt):
351
  with open(stock_data_path, 'wt') as fp:
352
  fp.write(txt)
 
580
  if args[1] == 'value':
581
  return [past, md(response), None, gptModel, uploaded_image_file, plot]
582
  elif args[1] == 'history':
583
+ (plot_df, ymax) = get_total_daily_closing_sequence(40) #stock_history_df(12)
584
  # ymax = float(ymax)
585
  return [past, md(response), None, gptModel, uploaded_image_file,
586
  gr.LinePlot(plot_df, x="date", y="value", visible=True,
 
590
  symbol = ' '.join(args[2:])
591
  (response, plot_df, ymax) = get_stock_news(symbol)
592
  ymax *= 1.1
593
+ mdtxt = md(f'News for {symbol}:\n\n' + response)
594
  if plot_df.empty:
595
+ return [past, mdtxt, None, gptModel, uploaded_image_file, plot]
596
  else:
597
+ return [past, mdtxt, None, gptModel, uploaded_image_file,
598
  gr.LinePlot(plot_df, x="date", y="value", visible=True,
599
+ y_lim=[0, ymax],label=f"{symbol.upper()} Recent Prices")]
600
  # elif arg[1] == 'history':
601
  # symbol = arg[2]
602
  # response = 'ok' # get_