Karthikeyen92 commited on
Commit
74a4847
1 Parent(s): 46e6632

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -48
app.py CHANGED
@@ -54,7 +54,14 @@ class StockAdviserUI:
54
  padding-right: 20px;
55
  padding-left: 20px;
56
  color: #E9EBED;
57
- margin-bottom: 2rem;
 
 
 
 
 
 
 
58
  }
59
  .main-header2 {
60
  text-align: left;
@@ -98,7 +105,8 @@ class StockAdviserUI:
98
  """, unsafe_allow_html=True)
99
 
100
  def _setup_header(self):
101
- st.markdown("<h1 class='main-header'>RAG Stock Analysis</h1>", unsafe_allow_html=True)
 
102
  with st.expander("Available Historical Demo Companies"):
103
  st.markdown("""
104
  For Demo purpose, historical data is available only for the below companies:
@@ -479,10 +487,10 @@ class StockAdviser:
479
  """, unsafe_allow_html=True)
480
 
481
  def _get_sentiment_analysis(self, context, cmp_tr, is_realtime=False):
482
- system_message = self._get_system_prompt(is_realtime)
483
  user_message = f"""
484
  ###Context
485
- Here are some documents that are relevant to the question mentioned below.
486
  {context}
487
 
488
  ###Question
@@ -500,7 +508,7 @@ class StockAdviser:
500
  )
501
  return response.choices[0].message.content.strip()
502
  except Exception as e:
503
- return f'Sorry, I encountered the following error: \n {e}'
504
 
505
  def _display_sentiment(self, prediction):
506
  sentiment = self._extract_between(prediction, "Overall Sentiment:", "Overall Justification:").strip()
@@ -539,59 +547,81 @@ class StockAdviser:
539
  Returns:
540
  str: The complete system prompt for the sentiment analysis
541
  """
542
- base_prompt = """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
543
  You are an assistant to a financial services firm who answers user queries on Stock Investments.
544
  User input will have the context required by you to answer user questions.
545
  This context will begin with the token: ###Context.
546
- The context contains references to specific portions of a document relevant to the user query.
 
547
 
548
  User questions will begin with the token: ###Question.
549
 
550
  First, find the 'nse company symbol' of the related company in the question provided.
551
- Your task is to perform sentiment analysis on the content part of each documents provided in the Context, which discuss a company identified by its 'nse company symbol'. The goal is to determine the overall sentiment expressed across all documents and provide an overall justification. Based on the sentiment analysis, give a recommendation on whether the company's stock should be purchased.
552
 
553
  Step-by-Step Instructions:
554
  1. See if the question is "NOTICKER". If so, give response and don't proceed.
555
  2. If the company in question is not found in the context, give the corresponding response and don't proceed.
556
- 3. Read the Context: Carefully read the content parts of each document provided in the list of Documents.
557
- 4. Determine Overall Sentiment: Analyze the sentiment across all documents and categorize the overall sentiment as Positive, Negative, or Neutral.
558
- 5. Provide Overall Justification: Summarize the key points from all documents to justify the overall sentiment.
559
  6. Stock Advice: Based on the overall sentiment and justification, provide a recommendation on whether the company's stock should be purchased.
560
-
 
561
  Example Analysis:
562
  Context:
563
  [Document(metadata={'platform': 'Moneycontrol', 'company': 'ASIANPAINT', 'ingestion_timestamp': '2024-10-25T17:13:42.970099', 'word_count': 134}, page_content="{'title': 'Asian Paints launches Neo Bharat Latex Paint to tap on booming demand', 'content': 'The company, which is the leading player in India, touts the new segment to being affordable, offering over 1000 shades for consumers.'}"), Document(metadata={'platform': 'MarketsMojo', 'company': 'ASIANPAINT', 'ingestion_timestamp': '2024-10-25T17:13:42.970099', 'word_count': 128}, page_content="{'title': 'Asian Paints Ltd. Stock Performance Shows Positive Trend, Outperforms Sector by 0.9%', 'content': 'Asian Paints Ltd., a leading player in the paints industry, has seen a positive trend in its stock performance on July 10, 2024.'}"), Document(metadata={'platform': 'Business Standard', 'company': 'ASIANPAINT', 'ingestion_timestamp': '2024-10-25T17:13:42.970099', 'word_count': 138}, page_content="{'title': 'Asian Paints, Indigo Paints, Kansai gain up to 5% on falling oil prices', 'content': 'Shares of paint companies were trading higher on Wednesday, rising up to 5 per cent on the BSE, on the back of a fall in crude oil prices.'}")]
564
  """
565
 
566
- if is_realtime:
567
- response_format = """
568
- Response Formats:
569
- Only If the Question is 'NOTICKER':
570
- No valid company in the query.
571
-
572
- Else, If the context does not have relevent data for the company:
573
- Respond "Company {Company name} {nse company symbol}({symbol}) details not found in the RealTime Data".
574
- """
575
- else:
576
- response_format = """
577
- Response Formats:
578
- If the Question value is "NOTICKER":
579
- No valid company in the query.
580
-
581
- If the context does not have relevent data for the company (Question value):
582
- Respond "Company {Company name} {nse company symbol}({symbol}) details not found in the Historical Data".
583
- """
584
-
585
- common_format = """
586
- else, If the content parts of context has relevent data:
587
- Overall Sentiment: [Positive/Negative/Neutral] <line break>
588
- Overall Justification: [Detailed analysis of why the sentiment was chosen, summarizing key points from the documents] <line break>
589
- Stock Advice: [Clear recommendation on whether to purchase the stock, based on the sentiment analysis and justification]
590
-
591
- Please follow the steps to analyze the sentiment of each document's content; and strictly follow exact structure illustrated in above example response to provide an overall sentiment, justification and give stock purchase advice. Provide only Overall response, don't provide documentwise response or any note. Decorate the response with html/css tags.
592
- """
593
 
594
- return base_prompt + response_format + common_format
595
 
596
 
597
  def main(hugg):
@@ -643,18 +673,18 @@ def main(hugg):
643
  col1, col2 = st.columns(2)
644
 
645
  with col1:
646
- st.markdown("<h2 class='column-header'>Historical Analysis</h2>", unsafe_allow_html=True)
647
- with st.container():
648
- if user_question:
649
  cmp_tr = adviser.process_historical_data(user_question, hugg)
650
 
651
  with col2:
652
- st.markdown("<h2 class='column-header'>Real-Time Analysis</h2>", unsafe_allow_html=True)
653
- with st.container():
654
- if user_question:
655
  sentiment_response = adviser.process_realtime_data(cmp_tr, hugg)
656
 
657
- if (str(cmp_tr) is not "NOTICKER"):
658
  with st.container():
659
  if user_question:
660
  adviser.display_charts(cmp_tr,sentiment_response)
@@ -663,5 +693,5 @@ def main(hugg):
663
  st.markdown("<p style='text-align: center; color: #666;'>© 2024 EY</p>", unsafe_allow_html=True)
664
 
665
  if __name__ == "__main__":
666
- hugg = True
667
  main(hugg)
 
54
  padding-right: 20px;
55
  padding-left: 20px;
56
  color: #E9EBED;
57
+ # margin-bottom: 2rem;
58
+ }
59
+ .little-header {
60
+ # text-align: center;
61
+ padding-right: 20px;
62
+ padding-left: 20px;
63
+ color: #E9EBED;
64
+ # margin-bottom: 2rem;
65
  }
66
  .main-header2 {
67
  text-align: left;
 
105
  """, unsafe_allow_html=True)
106
 
107
  def _setup_header(self):
108
+ st.markdown("<h1 class='main-header'>Stock Analysis with Generative AI</h1>", unsafe_allow_html=True)
109
+ st.markdown("<h3 class='main-header'>using RAG</h3>", unsafe_allow_html=True)
110
  with st.expander("Available Historical Demo Companies"):
111
  st.markdown("""
112
  For Demo purpose, historical data is available only for the below companies:
 
487
  """, unsafe_allow_html=True)
488
 
489
  def _get_sentiment_analysis(self, context, cmp_tr, is_realtime=False):
490
+ system_message, dcument = self._get_system_prompt(is_realtime)
491
  user_message = f"""
492
  ###Context
493
+ Here are some list of {dcument} that are relevant to the question mentioned below.
494
  {context}
495
 
496
  ###Question
 
508
  )
509
  return response.choices[0].message.content.strip()
510
  except Exception as e:
511
+ return f'Sorry, I encountered the following error: \n {e}', ""
512
 
513
  def _display_sentiment(self, prediction):
514
  sentiment = self._extract_between(prediction, "Overall Sentiment:", "Overall Justification:").strip()
 
547
  Returns:
548
  str: The complete system prompt for the sentiment analysis
549
  """
550
+
551
+ if is_realtime:
552
+ response_format = """
553
+ Response Formats:
554
+ Only If the Question is 'NOTICKER':
555
+ No valid company in the query.
556
+
557
+ Else, If the context does not have relevent data for the company:
558
+ Respond "Company {Company name} {nse company symbol}({symbol}) details not found in the RealTime Data".
559
+ """
560
+ citation_format = """
561
+ Citations: [Generate few citations based on the links provided. Mention Source ('platform') and Title('title'), linking them with url from corresponding 'link' ]
562
+ """
563
+ instr2 = """
564
+ Stricktly Never mention 'document'/'documents', not even once. Instead mention it as 'Real-Time Social media and News data'
565
+ """
566
+
567
+ dcument = "Real-Time Social media and News data"
568
+ dcuments = "List of 'Real-Time Social media and News data'"
569
+ else:
570
+ response_format = """
571
+ Response Formats:
572
+ If the Question value is "NOTICKER":
573
+ No valid company in the query.
574
+
575
+ If the context does not have relevent data for the company (Question value):
576
+ Respond "Company {Company name} {nse company symbol}({symbol}) details not found in the Historical Data".
577
+ """
578
+ citation_format = ""
579
+
580
+ instr2 = """
581
+ Never mention 'document'/'documents', not even once. Instead mention it as 'Historical Social media and News data'
582
+ """
583
+
584
+ dcument = "Historical Social media and News data"
585
+ dcuments = "List of 'Historical Social media and News data'"
586
+
587
+ instr = f"""
588
+ Please follow the steps to analyze the sentiment of each {dcument}'s content; and strictly follow exact structure illustrated in above example response to provide an overall sentiment, justification and give stock purchase advice. Provide only Overall response, don't provide documentwise response or any note. Decorate the response with html/css tags.
589
+ """
590
+ common_format = f"""
591
+ else, If the content parts of context has relevent data:
592
+ Overall Sentiment: [Positive/Negative/Neutral] <line break>
593
+ Overall Justification: [Detailed analysis of why the sentiment was chosen, summarizing key points from the {dcuments}] <line break>
594
+ Stock Advice: [Clear recommendation on whether to purchase the stock, based on the sentiment analysis and justification]
595
+ """
596
+
597
+ base_prompt = f"""
598
  You are an assistant to a financial services firm who answers user queries on Stock Investments.
599
  User input will have the context required by you to answer user questions.
600
  This context will begin with the token: ###Context.
601
+ The context contains references to specific portions of a {dcument} relevant to the user query.
602
+ Each document is a {dcument}.
603
 
604
  User questions will begin with the token: ###Question.
605
 
606
  First, find the 'nse company symbol' of the related company in the question provided.
607
+ Your task is to perform sentiment analysis on the content part of each {dcuments} provided in the Context, which discuss a company identified by its 'nse company symbol'. The goal is to determine the overall sentiment expressed across all {dcuments} and provide an overall justification. Based on the sentiment analysis, give a recommendation on whether the company's stock should be purchased.
608
 
609
  Step-by-Step Instructions:
610
  1. See if the question is "NOTICKER". If so, give response and don't proceed.
611
  2. If the company in question is not found in the context, give the corresponding response and don't proceed.
612
+ 3. Read the Context: Carefully read the content parts of each {dcument} provided in the list of {dcuments}.
613
+ 4. Determine Overall Sentiment: Analyze the sentiment across all {dcuments} and categorize the overall sentiment as Positive, Negative, or Neutral.
614
+ 5. Provide Overall Justification: Summarize the key points from all {dcuments} to justify the overall sentiment.
615
  6. Stock Advice: Based on the overall sentiment and justification, provide a recommendation on whether the company's stock should be purchased.
616
+ """
617
+ example_analysis = """
618
  Example Analysis:
619
  Context:
620
  [Document(metadata={'platform': 'Moneycontrol', 'company': 'ASIANPAINT', 'ingestion_timestamp': '2024-10-25T17:13:42.970099', 'word_count': 134}, page_content="{'title': 'Asian Paints launches Neo Bharat Latex Paint to tap on booming demand', 'content': 'The company, which is the leading player in India, touts the new segment to being affordable, offering over 1000 shades for consumers.'}"), Document(metadata={'platform': 'MarketsMojo', 'company': 'ASIANPAINT', 'ingestion_timestamp': '2024-10-25T17:13:42.970099', 'word_count': 128}, page_content="{'title': 'Asian Paints Ltd. Stock Performance Shows Positive Trend, Outperforms Sector by 0.9%', 'content': 'Asian Paints Ltd., a leading player in the paints industry, has seen a positive trend in its stock performance on July 10, 2024.'}"), Document(metadata={'platform': 'Business Standard', 'company': 'ASIANPAINT', 'ingestion_timestamp': '2024-10-25T17:13:42.970099', 'word_count': 138}, page_content="{'title': 'Asian Paints, Indigo Paints, Kansai gain up to 5% on falling oil prices', 'content': 'Shares of paint companies were trading higher on Wednesday, rising up to 5 per cent on the BSE, on the back of a fall in crude oil prices.'}")]
621
  """
622
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
 
624
+ return base_prompt + example_analysis + response_format + common_format + citation_format + instr + instr2, dcument
625
 
626
 
627
  def main(hugg):
 
673
  col1, col2 = st.columns(2)
674
 
675
  with col1:
676
+ if user_question:
677
+ st.markdown("<h3 class='little-header'>Historical Analysis</h3>", unsafe_allow_html=True)
678
+ with st.container():
679
  cmp_tr = adviser.process_historical_data(user_question, hugg)
680
 
681
  with col2:
682
+ if user_question:
683
+ st.markdown("<h3 class='little-header'>Real-Time Analysis</h3>", unsafe_allow_html=True)
684
+ with st.container():
685
  sentiment_response = adviser.process_realtime_data(cmp_tr, hugg)
686
 
687
+ if (str(cmp_tr) != "NOTICKER"):
688
  with st.container():
689
  if user_question:
690
  adviser.display_charts(cmp_tr,sentiment_response)
 
693
  st.markdown("<p style='text-align: center; color: #666;'>© 2024 EY</p>", unsafe_allow_html=True)
694
 
695
  if __name__ == "__main__":
696
+ hugg = False
697
  main(hugg)