Nazhar commited on
Commit
e699adc
·
verified ·
1 Parent(s): c406238

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -37
app.py CHANGED
@@ -80,7 +80,7 @@ def convert_str_to_list(string):
80
  return string
81
 
82
 
83
- # Add Title and Logo
84
  def get_answer(text):
85
  text = response['result']
86
  helpful_answer_index = text.find('Helpful Answer:')
@@ -99,7 +99,8 @@ def response_generator(answer):
99
  time.sleep(0.05)
100
 
101
 
102
- # WebApp
 
103
  title_container = st.container(border=False) # Create a container to hold the tile and logo
104
  col1, col2 = title_container.columns([0.2, 0.8], gap='medium') # Create columns to display logo and title side-by-side
105
  col1.image("logo.png") # Add logo to the 1st column
@@ -185,6 +186,7 @@ with market_analysis:
185
  ])
186
  )
187
  )
 
188
  fig.update_yaxes(fixedrange=False)
189
 
190
  # Show chart on WebApp
@@ -225,6 +227,7 @@ with market_analysis:
225
  ])
226
  )
227
  )
 
228
  fig.update_yaxes(fixedrange=False)
229
 
230
  # Show chart on WebApp
@@ -282,6 +285,7 @@ with market_analysis:
282
  ])
283
  )
284
  )
 
285
  fig.update_yaxes(fixedrange=False)
286
 
287
  # Show chart on WebApp
@@ -333,6 +337,7 @@ with market_analysis:
333
  ])
334
  )
335
  )
 
336
  fig.update_yaxes(fixedrange=False)
337
  st.plotly_chart(fig)
338
  # st.write(data2)
@@ -348,17 +353,21 @@ with news_analysis:
348
  # Load News Events data
349
  data_file_path = r"Events_SameDay.csv" # Update this with your file path
350
  events = pd.read_csv(data_file_path, encoding="ISO-8859-1", lineterminator='\n')
351
- print(events.columns)
352
 
353
  # Convert 'Date' column to datetime format
354
  events['Date'] = pd.to_datetime(events['Date'])
 
 
355
  events = events[(events['Date'] >= start_date) & (events['Date'] <= end_date)]
356
- print(events.shape, events.columns)
357
 
 
358
  cols = ['Raw_Headline', 'Bold_KW', 'Feature', 'Raw_News', 'Sources', 'Urls']
359
  for col in cols:
360
  events[col] = events[col].apply(convert_str_to_list)
361
-
 
 
 
362
  # Add a new column for positive values of column A
363
  events['Positive_Impacts'] = events[events['Events_Impact'] >= 4.7]['Events_Impact']
364
 
@@ -368,24 +377,17 @@ with news_analysis:
368
  # Fill NaN values in the new columns with 0
369
  events['Positive_Impacts'].fillna("", inplace=True)
370
  events['Negative_Impacts'].fillna("", inplace=True)
 
 
371
  plot_sub_pos = events[events['Positive_Impacts']!='']
372
  plot_sub_neg = events[events['Negative_Impacts']!='']
373
- def get_set(list_value):
374
- set_value = set(list_value)
375
- return str(set_value)
376
-
377
- plot_sub_pos['SetFeature'] = plot_sub_pos['Feature'].apply(get_set)
378
- plot_sub_neg['SetFeature'] = plot_sub_neg['Feature'].apply(get_set)
379
  # Create the line trace for stock prices
380
  line_stock = go.Scatter(x=events['Date'], y=events['Price'], mode='lines', name='OGDCL Close Price',
381
  line=dict(dash='solid', color=cs.close_line_color, width=2),
382
- # text=events['Cleaned_Headline'],
383
- # hovertext=events['FeatureSentiment'],
384
- customdata=events['Feature'],
385
  hovertemplate='%{x}<br>Close: %{y}<br>Feature: %{customdata}<br>',
386
- # hoverlabel=dict(font=dict(color=events
387
- # ['FeatureSentiment'].apply(lambda x: 'red' if x == 'Negative' else 'blue' if x == 'Neutral' else 'green'))), # Customize the line style, color, and width
388
- )
389
  title = 'OGDCL Close Price vs News Impact'
390
  layout = go.Layout(
391
  title=title,
@@ -405,14 +407,17 @@ with news_analysis:
405
  )
406
 
407
  # Add all traces to the figure
408
-
409
  figure = go.Figure(data=[line_stock], layout=layout)
 
410
  figure.add_scatter(x=plot_sub_pos['Date'], y=plot_sub_pos['Price'], mode='markers',
411
  marker=dict(symbol='triangle-up', size=10, color=cs.pos_impacts_color), name='Positive Impact',
412
  customdata=plot_sub_pos['SetFeature'], hovertemplate='%{x}<br>Close: %{y}<br>Feature: %{customdata}<br>')
 
413
  figure.add_scatter(x=plot_sub_neg['Date'], y=plot_sub_neg['Price'], mode='markers',
414
  marker=dict(symbol='triangle-down', size=10, color=cs.neg_impacts_color), name='Negative Impact',
415
  customdata=plot_sub_neg['SetFeature'], hovertemplate='%{x}<br>Close: %{y}<br>Feature: %{customdata}<br>',)
 
 
416
  figure.update_layout(
417
  title={
418
  'text': title,
@@ -425,8 +430,8 @@ with news_analysis:
425
  hovermode='closest',
426
  margin=dict(l=40, r=40, t=80, b=40),
427
  modebar_add="togglespikelines",
428
- # scrollZoom=True,
429
  )
 
430
  figure.update_xaxes(
431
  rangeslider_visible=True,
432
  rangeselector=dict(
@@ -471,7 +476,7 @@ with news_analysis:
471
  st.write(f'<span style="font-size: large;"><b>Date:</b> <u>{date}</u></span>', unsafe_allow_html=True)
472
  filtered_news = news[news['Date'] == date]
473
  print(filtered_news.shape)
474
- features = filtered_news['Feature'].sum()
475
  headlines = filtered_news['Raw_Headline'].sum()
476
  news_list = filtered_news['Raw_News'].sum()
477
  sources = filtered_news['Sources'].sum()
@@ -526,8 +531,7 @@ with final_recs:
526
  fp[d] = following_price
527
 
528
  fp[rec_dates[-1]] = 'Not Available'
529
- # date_value = pd.to_datetime('2021-08-12')
530
- # pred_date = st.date_input("Pick Test Date", value=date_value, min_value=date_value, max_value=date_limit)
531
  role = st.radio(
532
  "Show recommendation summary as:",
533
  ["Active Trader", "Equity Analyst"], horizontal=True)
@@ -543,20 +547,7 @@ with final_recs:
543
  # Convert back to Dictionaries from strings
544
  trade_recs['Recommendations_Equity_Analyst'] = trade_recs['Recommendations_Equity_Analyst'].apply(convert_str_to_list)
545
  trade_recs.rename(columns={'Recommendations_Equity_Analyst': 'Recommendations'}, inplace=True)
546
- # if 'Trading_Recommendations\r' in events.columns:
547
- # events.rename(columns={'Trading_Recommendations\r': 'Trading_Recommendations'}, inplace=True)
548
 
549
- # print(events.columns)
550
-
551
- # # Extract date component from the datetime column
552
- # trade_recs['Date'] = trade_recs['Date'].dt.date
553
-
554
- # dates = list(trade_recs['Date'].unique())
555
- # dates = np.sort(dates)
556
- # # Reverse the array to have the latest date at index 0
557
- # dates = dates[::-1]
558
- # num_dates = len(dates)
559
- # st.subheader("GenAI Recommendations")
560
  trade_recs.reset_index(inplace=True, drop=True)
561
  genrec_container = st.container(border=False)
562
  rec_col1, rec_col2, rec_col3 = genrec_container.columns(3, gap='medium')
@@ -565,9 +556,8 @@ with final_recs:
565
  rec_col1.write(f'<span style="font-size: large;"><b>Current Date:</b> <u>{pred_date}</u></span>', unsafe_allow_html=True)
566
  rec_col2.write(f'<span style="font-size: large;"><b>Current Close Price:</b> {current_price}</span>', unsafe_allow_html=True)
567
  rec_col3.write(f'<span style="font-size: large;"><b>Following Close Price:</b> {fp[pred_date]}</span>', unsafe_allow_html=True)
 
568
  genrec_container.subheader("Generated Recommendation")
569
- # genrec_container.divider()
570
- # genrec = 'Recommendation for following day will go here.'
571
  genrec_container.write(trade_recs['Recommendations'][0])
572
 
573
  # Create the line trace for stock prices
 
80
  return string
81
 
82
 
83
+ # Extract Answer from LLM response
84
  def get_answer(text):
85
  text = response['result']
86
  helpful_answer_index = text.find('Helpful Answer:')
 
99
  time.sleep(0.05)
100
 
101
 
102
+ # ---- WebApp ----
103
+ # Add Title and Logo
104
  title_container = st.container(border=False) # Create a container to hold the tile and logo
105
  col1, col2 = title_container.columns([0.2, 0.8], gap='medium') # Create columns to display logo and title side-by-side
106
  col1.image("logo.png") # Add logo to the 1st column
 
186
  ])
187
  )
188
  )
189
+ # Update y-axis to allow vertical scrolling and dragging
190
  fig.update_yaxes(fixedrange=False)
191
 
192
  # Show chart on WebApp
 
227
  ])
228
  )
229
  )
230
+ # Update y-axis to allow vertical scrolling and dragging
231
  fig.update_yaxes(fixedrange=False)
232
 
233
  # Show chart on WebApp
 
285
  ])
286
  )
287
  )
288
+ # Update y-axis to allow vertical scrolling and dragging
289
  fig.update_yaxes(fixedrange=False)
290
 
291
  # Show chart on WebApp
 
337
  ])
338
  )
339
  )
340
+ # Update y-axis to allow vertical scrolling and dragging
341
  fig.update_yaxes(fixedrange=False)
342
  st.plotly_chart(fig)
343
  # st.write(data2)
 
353
  # Load News Events data
354
  data_file_path = r"Events_SameDay.csv" # Update this with your file path
355
  events = pd.read_csv(data_file_path, encoding="ISO-8859-1", lineterminator='\n')
 
356
 
357
  # Convert 'Date' column to datetime format
358
  events['Date'] = pd.to_datetime(events['Date'])
359
+
360
+ # Filter data based on the date selected by the user
361
  events = events[(events['Date'] >= start_date) & (events['Date'] <= end_date)]
 
362
 
363
+ # Use convert_str_to_list utils function to restore list value data type
364
  cols = ['Raw_Headline', 'Bold_KW', 'Feature', 'Raw_News', 'Sources', 'Urls']
365
  for col in cols:
366
  events[col] = events[col].apply(convert_str_to_list)
367
+
368
+ # Get unique features
369
+ events['SetFeature'] = events['Feature'].apply(lambda x: str(set(x)))
370
+
371
  # Add a new column for positive values of column A
372
  events['Positive_Impacts'] = events[events['Events_Impact'] >= 4.7]['Events_Impact']
373
 
 
377
  # Fill NaN values in the new columns with 0
378
  events['Positive_Impacts'].fillna("", inplace=True)
379
  events['Negative_Impacts'].fillna("", inplace=True)
380
+
381
+ # Filter out subset dataframes to plot positive & negative impacts
382
  plot_sub_pos = events[events['Positive_Impacts']!='']
383
  plot_sub_neg = events[events['Negative_Impacts']!='']
384
+
 
 
 
 
 
385
  # Create the line trace for stock prices
386
  line_stock = go.Scatter(x=events['Date'], y=events['Price'], mode='lines', name='OGDCL Close Price',
387
  line=dict(dash='solid', color=cs.close_line_color, width=2),
388
+ customdata=events['SetFeature'],
 
 
389
  hovertemplate='%{x}<br>Close: %{y}<br>Feature: %{customdata}<br>',
390
+ )
 
 
391
  title = 'OGDCL Close Price vs News Impact'
392
  layout = go.Layout(
393
  title=title,
 
407
  )
408
 
409
  # Add all traces to the figure
 
410
  figure = go.Figure(data=[line_stock], layout=layout)
411
+ # Add Positive impacts
412
  figure.add_scatter(x=plot_sub_pos['Date'], y=plot_sub_pos['Price'], mode='markers',
413
  marker=dict(symbol='triangle-up', size=10, color=cs.pos_impacts_color), name='Positive Impact',
414
  customdata=plot_sub_pos['SetFeature'], hovertemplate='%{x}<br>Close: %{y}<br>Feature: %{customdata}<br>')
415
+ # Add Negative impacts
416
  figure.add_scatter(x=plot_sub_neg['Date'], y=plot_sub_neg['Price'], mode='markers',
417
  marker=dict(symbol='triangle-down', size=10, color=cs.neg_impacts_color), name='Negative Impact',
418
  customdata=plot_sub_neg['SetFeature'], hovertemplate='%{x}<br>Close: %{y}<br>Feature: %{customdata}<br>',)
419
+
420
+ # Update Layout
421
  figure.update_layout(
422
  title={
423
  'text': title,
 
430
  hovermode='closest',
431
  margin=dict(l=40, r=40, t=80, b=40),
432
  modebar_add="togglespikelines",
 
433
  )
434
+ # Add date range selection buttons to chart
435
  figure.update_xaxes(
436
  rangeslider_visible=True,
437
  rangeselector=dict(
 
476
  st.write(f'<span style="font-size: large;"><b>Date:</b> <u>{date}</u></span>', unsafe_allow_html=True)
477
  filtered_news = news[news['Date'] == date]
478
  print(filtered_news.shape)
479
+ features = filtered_news['SetFeature'].sum()
480
  headlines = filtered_news['Raw_Headline'].sum()
481
  news_list = filtered_news['Raw_News'].sum()
482
  sources = filtered_news['Sources'].sum()
 
531
  fp[d] = following_price
532
 
533
  fp[rec_dates[-1]] = 'Not Available'
534
+
 
535
  role = st.radio(
536
  "Show recommendation summary as:",
537
  ["Active Trader", "Equity Analyst"], horizontal=True)
 
547
  # Convert back to Dictionaries from strings
548
  trade_recs['Recommendations_Equity_Analyst'] = trade_recs['Recommendations_Equity_Analyst'].apply(convert_str_to_list)
549
  trade_recs.rename(columns={'Recommendations_Equity_Analyst': 'Recommendations'}, inplace=True)
 
 
550
 
 
 
 
 
 
 
 
 
 
 
 
551
  trade_recs.reset_index(inplace=True, drop=True)
552
  genrec_container = st.container(border=False)
553
  rec_col1, rec_col2, rec_col3 = genrec_container.columns(3, gap='medium')
 
556
  rec_col1.write(f'<span style="font-size: large;"><b>Current Date:</b> <u>{pred_date}</u></span>', unsafe_allow_html=True)
557
  rec_col2.write(f'<span style="font-size: large;"><b>Current Close Price:</b> {current_price}</span>', unsafe_allow_html=True)
558
  rec_col3.write(f'<span style="font-size: large;"><b>Following Close Price:</b> {fp[pred_date]}</span>', unsafe_allow_html=True)
559
+
560
  genrec_container.subheader("Generated Recommendation")
 
 
561
  genrec_container.write(trade_recs['Recommendations'][0])
562
 
563
  # Create the line trace for stock prices