dlflannery commited on
Commit
62eeda6
·
verified ·
1 Parent(s): 3fe3655

Update app.py

Browse files

added stock history plot

Files changed (1) hide show
  1. app.py +68 -24
app.py CHANGED
@@ -63,12 +63,38 @@ class MathReasoning(BaseModel):
63
  def Client():
64
  return OpenAI(api_key = key)
65
 
 
 
 
 
 
 
 
66
  def etz_now():
67
  eastern = pytz.timezone('US/Eastern')
68
  ltime = datetime.now(eastern)
69
  return ltime
70
 
71
- def get_stock_report():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  try:
73
  stock_data = {}
74
  global stock_data_path
@@ -82,28 +108,35 @@ def get_stock_report():
82
  shares = shares.strip()
83
  stock_data[symbol] = {"symbol": symbol, "name": name, "shares": shares, "closing": '0'}
84
  for symbol in stock_data.keys():
85
- (closing_price, closing_date) = get_last_closing(symbol)
86
  if closing_price == 0:
87
  error_msg += f'Error getting closing for {symbol}\n'
88
  stock_data[symbol]['closing'] = f'{closing_price:.2f}'
89
  total_value = 0.0
90
- rv = f'At closing on {closing_date}:\n'
91
- for item in stock_data.values():
92
- rv += str(item) + '\n'
93
- total_value += float(item['closing']) * float(item['shares'])
94
- rv += (f'\nTotal value = {total_value:.2f}\n')
95
- if len(error_msg) > 0:
96
- rv += error_msg
97
- rv += f'Eastern time is: {etz_now()}'
 
 
 
 
 
98
  except:
99
  rv = 'Error getting stock report'
100
  return rv
101
 
102
- def get_last_closing(symbol, timeout=10):
103
  try:
104
  etime = etz_now()
105
  if etime.hour >= 16:
106
  etime = etime + timedelta(days=1)
 
 
107
  five_days_ago = etime - timedelta(days=6)
108
  end = etime.strftime('%Y-%m-%d')
109
  start = five_days_ago.strftime('%Y-%m-%d')
@@ -293,7 +326,8 @@ def new_conversation(user):
293
  for fpath in flist:
294
  if os.path.exists(fpath):
295
  os.remove(fpath)
296
- return [None, [], None, gr.Image(visible=False, value=None), gr.Image(visible=False, value=None), '']
 
297
 
298
  def updatePassword(txt):
299
  password = txt.lower().strip()
@@ -317,18 +351,19 @@ def updatePassword(txt):
317
  # ref = len(txt[ref:loc]) + len(frag)
318
  # return txt
319
 
320
- def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_image_file=''):
321
  image_gen_model = 'gpt-4o-2024-08-06'
322
  user_window = user_window.lower().strip()
323
  isBoss = False
 
324
  if user_window == unames[0] and pwd_window == pwdList[0]:
325
  isBoss = True
326
  if prompt == 'stats':
327
  response = genUsageStats()
328
- return [past, response, None, gptModel, uploaded_image_file]
329
  if prompt == 'reset':
330
  response = genUsageStats(True)
331
- return [past, response, None, gptModel, uploaded_image_file]
332
  if prompt.startswith('gpt4'):
333
  gptModel = 'gpt-4o-2024-08-06'
334
  prompt = prompt[5:]
@@ -336,17 +371,24 @@ def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_ima
336
  user = prompt[6:]
337
  response = f'cleaned all .wav and .b64 files for {user}'
338
  final_clean_up(user, True)
339
- return [past, response, None, gptModel, uploaded_image_file]
340
  if prompt.startswith('files'):
341
  (log_cnt, wav_cnt, other_cnt, others, log_list) = list_permanent_files()
342
  response = f'{log_cnt} log files\n{wav_cnt} .wav files\n{other_cnt} Other files:\n{others}\nlogs: {str(log_list)}'
343
- return [past, response, None, gptModel, uploaded_image_file]
344
  if prompt.startswith('stocks'):
345
  response = get_stock_report()
346
- return [past, response, None, gptModel, uploaded_image_file]
 
 
 
 
 
 
 
347
  if prompt.startswith('stockload'):
348
  create_stock_data_file(prompt[9:].lstrip())
349
- return [past, 'Stock data file created', None, gptModel, uploaded_image_file]
350
  if user_window in unames and pwd_window == pwdList[unames.index(user_window)]:
351
  chatType = 'normal'
352
  prompt = prompt.strip()
@@ -370,7 +412,7 @@ def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_ima
370
  uploaded_image_file= ''
371
  reporting_model = image_gen_model
372
  if not msg == 'ok':
373
- return [past, msg, None, gptModel, uploaded_image_file]
374
  if not chatType in special_chat_types:
375
  reply = completion.choices[0].message.content
376
  tokens_in = completion.usage.prompt_tokens
@@ -397,9 +439,9 @@ def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_ima
397
  sleep(3)
398
  if not accessOk:
399
  response += f"\nDATA LOG FAILED, path = {dataFile}"
400
- return [past, response , None, gptModel, uploaded_image_file]
401
  else:
402
- return [[], "User name and/or password are incorrect", prompt, gptModel, uploaded_image_file]
403
 
404
  def new_func(user):
405
  dataFile = dataDir + user + '_log.txt'
@@ -787,11 +829,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
787
  image_window2 = gr.Image(visible=False, interactive=True, label='Image to Analyze', type='filepath')
788
  with gr.Column():
789
  image_window = gr.Image(visible=False, label='Generated Image')
 
 
790
  submit_button.click(chat,
791
  inputs=[prompt_window, user_window, password, history, output_window, model, uploaded_image_file],
792
- outputs=[history, output_window, prompt_window, model, uploaded_image_file])
793
  clear_button.click(fn=new_conversation, inputs=user_window,
794
- outputs=[prompt_window, history, output_window, image_window, image_window2, uploaded_image_file])
795
  audio_widget.stop_recording(fn=transcribe, inputs=[user_window, password, audio_widget],
796
  outputs=[prompt_window])
797
  audio_widget.pause_recording(fn=pause_message, outputs=[prompt_window])
 
63
  def Client():
64
  return OpenAI(api_key = key)
65
 
66
+ def test_plot_df():
67
+ data = {
68
+ "month": ['2024-01','2024-02','2024-03'],
69
+ "value": [22.4, 30.1, 25.6]
70
+ }
71
+ return pd.DataFrame(data)
72
+
73
  def etz_now():
74
  eastern = pytz.timezone('US/Eastern')
75
  ltime = datetime.now(eastern)
76
  return ltime
77
 
78
+ def stock_history_df(num_weeks):
79
+ values = []
80
+ dates = []
81
+ xmax = 0
82
+ for offset in range(num_weeks+1):
83
+ (value, date) = get_stock_report(False, offset)
84
+ date = date[5:]
85
+ values.append(value)
86
+ dates.append(date)
87
+ if float(value) > xmax:
88
+ xmax = float(value)
89
+ values.reverse()
90
+ dates.reverse()
91
+ data = {
92
+ "date": dates,
93
+ "value" : values
94
+ }
95
+ return (pd.DataFrame(data), f'{int(xmax + 10000)}')
96
+
97
+ def get_stock_report(verbose = True, offset = 0):
98
  try:
99
  stock_data = {}
100
  global stock_data_path
 
108
  shares = shares.strip()
109
  stock_data[symbol] = {"symbol": symbol, "name": name, "shares": shares, "closing": '0'}
110
  for symbol in stock_data.keys():
111
+ (closing_price, closing_date) = get_last_closing(symbol, offset)
112
  if closing_price == 0:
113
  error_msg += f'Error getting closing for {symbol}\n'
114
  stock_data[symbol]['closing'] = f'{closing_price:.2f}'
115
  total_value = 0.0
116
+ if verbose:
117
+ rv = f'At closing on {closing_date}:\n'
118
+ for item in stock_data.values():
119
+ rv += str(item) + '\n'
120
+ total_value += float(item['closing']) * float(item['shares'])
121
+ rv += (f'\nTotal value = {total_value:.2f}\n')
122
+ if len(error_msg) > 0:
123
+ rv += error_msg
124
+ rv += f'Eastern time is: {etz_now()}'
125
+ else:
126
+ for item in stock_data.values():
127
+ total_value += float(item['closing']) * float(item['shares'])
128
+ return (total_value, closing_date)
129
  except:
130
  rv = 'Error getting stock report'
131
  return rv
132
 
133
+ def get_last_closing(symbol, offset=0, timeout=10):
134
  try:
135
  etime = etz_now()
136
  if etime.hour >= 16:
137
  etime = etime + timedelta(days=1)
138
+ if offset > 0:
139
+ etime = etime - timedelta(weeks=offset)
140
  five_days_ago = etime - timedelta(days=6)
141
  end = etime.strftime('%Y-%m-%d')
142
  start = five_days_ago.strftime('%Y-%m-%d')
 
326
  for fpath in flist:
327
  if os.path.exists(fpath):
328
  os.remove(fpath)
329
+ return [None, [], None, gr.Image(visible=False, value=None), gr.Image(visible=False, value=None), '',
330
+ gr.LinePlot(visible=False)]
331
 
332
  def updatePassword(txt):
333
  password = txt.lower().strip()
 
351
  # ref = len(txt[ref:loc]) + len(frag)
352
  # return txt
353
 
354
+ def chat(prompt, user_window, pwd_window, past, response, gptModel, uploaded_image_file='', plot=None):
355
  image_gen_model = 'gpt-4o-2024-08-06'
356
  user_window = user_window.lower().strip()
357
  isBoss = False
358
+ plot = gr.LinePlot(visible=False)
359
  if user_window == unames[0] and pwd_window == pwdList[0]:
360
  isBoss = True
361
  if prompt == 'stats':
362
  response = genUsageStats()
363
+ return [past, response, None, gptModel, uploaded_image_file, plot]
364
  if prompt == 'reset':
365
  response = genUsageStats(True)
366
+ return [past, response, None, gptModel, uploaded_image_file, plot]
367
  if prompt.startswith('gpt4'):
368
  gptModel = 'gpt-4o-2024-08-06'
369
  prompt = prompt[5:]
 
371
  user = prompt[6:]
372
  response = f'cleaned all .wav and .b64 files for {user}'
373
  final_clean_up(user, True)
374
+ return [past, response, None, gptModel, uploaded_image_file, plot]
375
  if prompt.startswith('files'):
376
  (log_cnt, wav_cnt, other_cnt, others, log_list) = list_permanent_files()
377
  response = f'{log_cnt} log files\n{wav_cnt} .wav files\n{other_cnt} Other files:\n{others}\nlogs: {str(log_list)}'
378
+ return [past, response, None, gptModel, uploaded_image_file, plot]
379
  if prompt.startswith('stocks'):
380
  response = get_stock_report()
381
+ if 'history' in prompt:
382
+ (plot_df, ymax) = stock_history_df(12)
383
+ ymax = float(ymax)
384
+ return [past, response, None, gptModel, uploaded_image_file,
385
+ gr.LinePlot(plot_df, x="date", y="value", visible=True,
386
+ y_lim=[500000, 700000], label="Portfolio Value History")]
387
+ else:
388
+ return [past, response, None, gptModel, uploaded_image_file, plot]
389
  if prompt.startswith('stockload'):
390
  create_stock_data_file(prompt[9:].lstrip())
391
+ return [past, 'Stock data file created', None, gptModel, uploaded_image_file, plot]
392
  if user_window in unames and pwd_window == pwdList[unames.index(user_window)]:
393
  chatType = 'normal'
394
  prompt = prompt.strip()
 
412
  uploaded_image_file= ''
413
  reporting_model = image_gen_model
414
  if not msg == 'ok':
415
+ return [past, msg, None, gptModel, uploaded_image_file, plot]
416
  if not chatType in special_chat_types:
417
  reply = completion.choices[0].message.content
418
  tokens_in = completion.usage.prompt_tokens
 
439
  sleep(3)
440
  if not accessOk:
441
  response += f"\nDATA LOG FAILED, path = {dataFile}"
442
+ return [past, response , None, gptModel, uploaded_image_file, plot]
443
  else:
444
+ return [[], "User name and/or password are incorrect", prompt, gptModel, uploaded_image_file, plot]
445
 
446
  def new_func(user):
447
  dataFile = dataDir + user + '_log.txt'
 
829
  image_window2 = gr.Image(visible=False, interactive=True, label='Image to Analyze', type='filepath')
830
  with gr.Column():
831
  image_window = gr.Image(visible=False, label='Generated Image')
832
+ with gr.Row():
833
+ plot = gr.LinePlot(test_plot_df(), x="month", y="value", visible=False, label="Portfolio Value History")
834
  submit_button.click(chat,
835
  inputs=[prompt_window, user_window, password, history, output_window, model, uploaded_image_file],
836
+ outputs=[history, output_window, prompt_window, model, uploaded_image_file, plot])
837
  clear_button.click(fn=new_conversation, inputs=user_window,
838
+ outputs=[prompt_window, history, output_window, image_window, image_window2, uploaded_image_file, plot])
839
  audio_widget.stop_recording(fn=transcribe, inputs=[user_window, password, audio_widget],
840
  outputs=[prompt_window])
841
  audio_widget.pause_recording(fn=pause_message, outputs=[prompt_window])