Nazhar commited on
Commit
a023751
·
verified ·
1 Parent(s): fdc6557

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -66
app.py CHANGED
@@ -17,6 +17,14 @@ from langchain_community.llms import HuggingFaceHub
17
  from langchain_core.prompts import PromptTemplate
18
  from langchain.chains import RetrievalQA
19
 
 
 
 
 
 
 
 
 
20
 
21
  # Utils Functions
22
  def signals_to_plot(selected_indicator, num_signals, signal_column, data):
@@ -73,6 +81,25 @@ def convert_str_to_list(string):
73
 
74
 
75
  # Add Title and Logo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  title_container = st.container(border=False) # Create a container to hold the tile and logo
77
  col1, col2 = title_container.columns([0.2, 0.8], gap='medium') # Create columns to display logo and title side-by-side
78
  col1.image("logo.png") # Add logo to the 1st column
@@ -131,27 +158,36 @@ with market_analysis:
131
 
132
  # Plot buy/sell signals
133
  if num_signals != 'None':
134
- # get signal values using the signals_to_plot function
135
  strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
136
  selected_indicator=selected_indicator,
137
  num_signals=num_signals,
138
  signal_column='EMA9_Signal',
139
  data=data2)
140
-
141
- fig.add_scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['EMA 9'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong buy')
142
- fig.add_scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['EMA 9'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong sell')
 
 
 
 
 
 
143
  fig.update_xaxes(
144
- rangeslider_visible=True,
145
- rangeselector=dict(
146
- buttons=list([
147
- dict(count=1, label="1m", step="month", stepmode="backward"),
148
- dict(count=6, label="6m", step="month", stepmode="backward"),
149
- dict(count=1, label="YTD", step="year", stepmode="todate"),
150
- dict(count=1, label="1y", step="year", stepmode="backward"),
151
- dict(step="all")
152
- ])
 
153
  )
154
- )
 
 
155
  st.plotly_chart(fig)
156
 
157
  elif selected_indicator == 'EMA 55':
@@ -159,16 +195,24 @@ with market_analysis:
159
  fig = px.line(data2, x='Date', y=['Close Price', 'EMA 55'], title='Close Price vs EMA 55',
160
  labels={'Date': 'Date', 'value': 'Price in Rs.', 'variable': 'Type'})
161
  fig.update_traces(selector=dict(type='scatter'))
162
- # Plot ‘strong buy’ signals
 
163
  if num_signals != 'None':
 
164
  strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
165
  selected_indicator=selected_indicator,
166
  num_signals=num_signals,
167
  signal_column='EMA55_Signal',
168
  data=data2)
169
 
170
- fig.add_scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['EMA 55'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong buy')
171
- fig.add_scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['EMA 55'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong sell')
 
 
 
 
 
 
172
  fig.update_xaxes(
173
  rangeslider_visible=True,
174
  rangeselector=dict(
@@ -181,37 +225,51 @@ with market_analysis:
181
  ])
182
  )
183
  )
 
 
 
184
  st.plotly_chart(fig)
185
 
186
  elif selected_indicator == 'MACD':
187
  # Set up the figure and subplots
188
  fig = make_subplots(rows=2, cols=1)
189
- # fig = go.Figure()
190
  # Add subplot for Close Price and Signals
191
  fig.add_trace(go.Scatter(x=data2['Date'], y=data2['Close Price'], mode='lines', name='Close Price'),
192
  row=1, col=1)
 
 
193
  if num_signals != 'None':
 
194
  strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
195
  selected_indicator=selected_indicator,
196
  num_signals=num_signals,
197
  signal_column='MACD_Signals',
198
  data=data2)
199
- fig.add_trace(go.Scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['Close Price'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong Buy'), row=1, col=1)
200
- fig.add_trace(go.Scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['Close Price'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong Sell'), row=1, col=1)
201
- fig.add_trace(go.Scatter(x=strong_hold_dates['Date'], y=strong_hold_dates['Close Price'], mode='markers', marker=dict(symbol='circle', size=10, color='orange'), name='Hold'), row=1, col=1)
 
 
 
 
 
 
 
202
 
203
  # Add subplot for MACD
204
  # fig2 = go.Figure()
205
- fig.add_trace(go.Scatter(x=data2['Date'], y=data2['MACD_12_26_9'], mode='lines', name='MACD', yaxis='y2'), row=2, col=1)
206
- fig.add_trace(go.Scatter(x=data2['Date'], y=data2['MACDs_12_26_9'], mode='lines', name='Signal', yaxis='y2'), row=2, col=1)
207
- fig.add_trace(go.Bar(x=data2['Date'], y=data2['MACDh_12_26_9'], name='Histogram', yaxis='y2'), row=2, col=1)
208
-
209
- # # Update layout
210
- # fig.update_layout(title='Close Price vs MACD',
211
- # xaxis=dict(title='Date'),
212
- # yaxis=dict(title='Close Price', side='left', showgrid=False),
213
- # yaxis2=dict(title='MACD', side='right', overlaying='y', showgrid=False))
214
  fig.update_layout(title='Close Price vs MACD')
 
 
215
  fig.update_xaxes(
216
  rangeslider_visible=False,
217
  rangeselector=dict(
@@ -224,8 +282,11 @@ with market_analysis:
224
  ])
225
  )
226
  )
 
 
 
227
  st.plotly_chart(fig, use_container_width=True)
228
- # st.plotly_chart(fig2, use_container_width=True)
229
 
230
  elif selected_indicator == 'RSI':
231
  # Set up the figure
@@ -240,17 +301,26 @@ with market_analysis:
240
  fig.add_shape(type="line", x0=data2['Date'].min(), y0=overbought_strong, x1=data2['Date'].max(), y1=overbought_strong, line=dict(color="red", width=1, dash="dash"), name="Overbought")
241
  fig.add_shape(type="line", x0=data2['Date'].min(), y0=oversold_strong, x1=data2['Date'].max(), y1=oversold_strong, line=dict(color="green", width=1, dash="dash"), name="Oversold")
242
 
 
243
  if num_signals != 'None':
 
244
  strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
245
  selected_indicator=selected_indicator,
246
  num_signals=num_signals,
247
  signal_column='RSI_Signals',
248
  data=data2)
249
- fig.add_trace(go.Scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['RSI'], mode='markers', marker=dict(symbol='triangle-up', size=10, color='green'), name='Strong Buy'))
250
- fig.add_trace(go.Scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['RSI'], mode='markers', marker=dict(symbol='triangle-down', size=10, color='red'), name='Strong Sell'))
 
 
 
 
 
251
  # fig.add_trace(go.Scatter(x=strong_hold_dates['Date'], y=strong_hold_dates['RSI'], mode='markers', marker=dict(symbol='circle', size=10, color='orange'), name='Hold'))
252
 
253
  fig.update_layout(title='RSI Analysis', showlegend=True)
 
 
254
  fig.update_xaxes(
255
  rangeslider_visible=True,
256
  rangeselector=dict(
@@ -263,21 +333,19 @@ with market_analysis:
263
  ])
264
  )
265
  )
 
266
  st.plotly_chart(fig)
267
  # st.write(data2)
268
 
269
- st.markdown("""
270
- <div style='background-color:#b43c42; color:#ffffff; padding:8px; border-radius:3px; font-size:12px''>
271
- <strong>Disclaimer:</strong> For demo purpose, the tool is currently populated with 10 months (Nov 2020 - Aug 2021) news and historical data of oil sector from PSX.
272
- This data is intended to illustrate the tool's functionality and is not intended for actual investment decisions.
273
- </div>
274
- """, unsafe_allow_html=True)
275
 
276
  with news_analysis:
277
  st.header("News Analysis", help="This module provides news based event impact for the following day based on the current date.")
278
  # st.write("This module provides news based event impact for the following day based on the current date.")
279
 
280
- # Load data
281
  data_file_path = r"Events_SameDay.csv" # Update this with your file path
282
  events = pd.read_csv(data_file_path, encoding="ISO-8859-1", lineterminator='\n')
283
  print(events.columns)
@@ -429,12 +497,8 @@ with news_analysis:
429
  st.write(set(features))
430
 
431
 
432
- st.markdown("""
433
- <div style='background-color:#b43c42; color:#ffffff; padding:8px; border-radius:3px; font-size:12px''>
434
- <strong>Disclaimer:</strong> For demo purpose, the tool is currently populated with 10 months (Nov 2020 - Aug 2021) news and historical data of oil sector from PSX.
435
- This data is intended to illustrate the tool's functionality and is not intended for actual investment decisions.
436
- </div>
437
- """, unsafe_allow_html=True)
438
 
439
 
440
  with final_recs:
@@ -571,27 +635,28 @@ with final_recs:
571
  # Update y-axis to allow vertical scrolling and dragging
572
  figure.update_yaxes(fixedrange=False)
573
  st.plotly_chart(figure)
574
-
575
- st.markdown("""
576
- <div style='background-color:#b43c42; color:#ffffff; padding:8px; border-radius:3px; font-size:12px''>
577
- <strong>Disclaimer:</strong> For demo purpose, the tool is currently populated with 10 months (Nov 2020 - Aug 2021) news and historical data of oil sector from PSX.
578
- This data is intended to illustrate the tool's functionality and is not intended for actual investment decisions.
579
- </div>
580
- """, unsafe_allow_html=True)
581
-
582
 
583
- with chat:
 
584
 
585
 
 
586
  st.header("Chat with AI Stock Advisor")
587
 
588
- loader = CSVLoader("Events_SameDay.csv",encoding='iso-8859-1')
 
 
589
  embeddings = HuggingFaceInstructEmbeddings()
 
 
590
  persist_directory = 'FAISS_VectorStore'
591
- db2 = FAISS.load_local(persist_directory, embeddings, allow_dangerous_deserialization=True)
 
 
592
  repo_id = "mistralai/Mistral-7B-Instruct-v0.1"
593
  llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature": 0.1, "max_new_tokens": 1024})
594
-
 
595
  system_prompt = """You are a financial expert for stock market who can perform multiple tasks for the intended user including trading
596
  recommendations with reasoning, retrieving articles with their impact in the market, retrieving or enlisting features affecting market
597
  trends (could be positive or negative).However, if a user is asking for trading recommendation, then you need to generate trading signal
@@ -617,14 +682,16 @@ with chat:
617
  "\nHelpful Answer: \n"
618
  )
619
  sys_prompt = PromptTemplate(input_variables=["context", "question"], template=template)
620
-
 
621
  chain = RetrievalQA.from_chain_type(
622
- llm=llm,
623
  chain_type="stuff",
624
- retriever=db2.as_retriever(),
625
  input_key="question",
626
- chain_type_kwargs={"prompt": sys_prompt})
627
 
 
628
  chat_container = st.container(height = 300, border=False)
629
  with chat_container:
630
  # Initialize chat history
@@ -636,6 +703,8 @@ with chat:
636
  with st.chat_message(message["role"]):
637
  st.markdown(message["content"])
638
 
 
 
639
  # Accept user input
640
  if prompt := st.chat_input("Enter your query here.", key='input2'):
641
  # Add user message to chat history
@@ -644,12 +713,10 @@ with chat:
644
  with chat_container.chat_message("user"):
645
  st.markdown(prompt)
646
 
647
- # question = query
648
- print(f"User Question: {prompt}")
649
  response = chain({"question": prompt})
650
- print("Answer generated")
651
  result = get_answer(response['result'])
652
- print("helpful answer extracted")
653
 
654
  # Display assistant response in chat message container
655
  with chat_container.chat_message("assistant"):
 
17
  from langchain_core.prompts import PromptTemplate
18
  from langchain.chains import RetrievalQA
19
 
20
+ # Disclaimer to be dispalyed at the bottom of each tab
21
+ disclaimer = """
22
+ <div style='background-color:#b43c42; color:#ffffff; padding:8px; border-radius:3px; font-size:12px''>
23
+ <strong>Disclaimer:</strong> For demo purpose, the tool is currently populated with 10 months (Nov 2020 - Aug 2021) news
24
+ and historical data of oil sector from PSX. This data is intended to illustrate the tool's functionality and is not
25
+ intended for actual investment decisions.
26
+ </div>
27
+ """
28
 
29
  # Utils Functions
30
  def signals_to_plot(selected_indicator, num_signals, signal_column, data):
 
81
 
82
 
83
  # Add Title and Logo
84
+ def get_answer(text):
85
+ text = response['result']
86
+ helpful_answer_index = text.find('Helpful Answer:')
87
+ if helpful_answer_index != -1:
88
+ helpful_answer = text[helpful_answer_index + len('Helpful Answer:'):].strip()
89
+ print(helpful_answer)
90
+ else:
91
+ print("No helpful answer found.")
92
+ return helpful_answer
93
+
94
+ # Streamed response emulator
95
+ def response_generator(answer):
96
+ response = answer
97
+ for word in response.split():
98
+ yield word + " "
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
 
158
 
159
  # Plot buy/sell signals
160
  if num_signals != 'None':
161
+ # get signal values using the signals_to_plot utils function
162
  strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
163
  selected_indicator=selected_indicator,
164
  num_signals=num_signals,
165
  signal_column='EMA9_Signal',
166
  data=data2)
167
+
168
+ # Add Buy signals
169
+ fig.add_scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['EMA 9'], mode='markers',
170
+ marker=dict(symbol='triangle-up', size=10, color=cs.pos_impacts_color), name='Strong buy')
171
+ # Add Sell signals
172
+ fig.add_scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['EMA 9'], mode='markers',
173
+ marker=dict(symbol='triangle-down', size=10, color=cs.neg_impacts_color), name='Strong sell')
174
+
175
+ # Add date range selection buttons to chart
176
  fig.update_xaxes(
177
+ rangeslider_visible=True,
178
+ rangeselector=dict(
179
+ buttons=list([
180
+ dict(count=1, label="1m", step="month", stepmode="backward"),
181
+ dict(count=6, label="6m", step="month", stepmode="backward"),
182
+ dict(count=1, label="YTD", step="year", stepmode="todate"),
183
+ dict(count=1, label="1y", step="year", stepmode="backward"),
184
+ dict(step="all")
185
+ ])
186
+ )
187
  )
188
+ fig.update_yaxes(fixedrange=False)
189
+
190
+ # Show chart on WebApp
191
  st.plotly_chart(fig)
192
 
193
  elif selected_indicator == 'EMA 55':
 
195
  fig = px.line(data2, x='Date', y=['Close Price', 'EMA 55'], title='Close Price vs EMA 55',
196
  labels={'Date': 'Date', 'value': 'Price in Rs.', 'variable': 'Type'})
197
  fig.update_traces(selector=dict(type='scatter'))
198
+
199
+ # Plot buy/sell signals
200
  if num_signals != 'None':
201
+ # get signal values using the signals_to_plot utils function
202
  strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
203
  selected_indicator=selected_indicator,
204
  num_signals=num_signals,
205
  signal_column='EMA55_Signal',
206
  data=data2)
207
 
208
+ # Add Buy signals
209
+ fig.add_scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['EMA 55'], mode='markers',
210
+ marker=dict(symbol='triangle-up', size=10, color=cs.pos_impacts_color), name='Strong buy')
211
+ # Add Sell signals
212
+ fig.add_scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['EMA 55'], mode='markers',
213
+ marker=dict(symbol='triangle-down', size=10, color=cs.neg_impacts_color), name='Strong sell')
214
+
215
+ # Add date range selection buttons to chart
216
  fig.update_xaxes(
217
  rangeslider_visible=True,
218
  rangeselector=dict(
 
225
  ])
226
  )
227
  )
228
+ fig.update_yaxes(fixedrange=False)
229
+
230
+ # Show chart on WebApp
231
  st.plotly_chart(fig)
232
 
233
  elif selected_indicator == 'MACD':
234
  # Set up the figure and subplots
235
  fig = make_subplots(rows=2, cols=1)
236
+
237
  # Add subplot for Close Price and Signals
238
  fig.add_trace(go.Scatter(x=data2['Date'], y=data2['Close Price'], mode='lines', name='Close Price'),
239
  row=1, col=1)
240
+
241
+ # Plot buy/sell signals
242
  if num_signals != 'None':
243
+ # get signal values using the signals_to_plot utils function
244
  strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
245
  selected_indicator=selected_indicator,
246
  num_signals=num_signals,
247
  signal_column='MACD_Signals',
248
  data=data2)
249
+
250
+ # Add Buy signals
251
+ fig.add_trace(go.Scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['Close Price'], mode='markers',
252
+ marker=dict(symbol='triangle-up', size=10, color=cs.pos_impacts_color), name='Strong Buy'), row=1, col=1)
253
+ # Add Sell signals
254
+ fig.add_trace(go.Scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['Close Price'], mode='markers',
255
+ marker=dict(symbol='triangle-down', size=10, color='red'cs.neg_impacts_color), name='Strong Sell'), row=1, col=1)
256
+ # Add Hold signals
257
+ fig.add_trace(go.Scatter(x=strong_hold_dates['Date'], y=strong_hold_dates['Close Price'], mode='markers',
258
+ marker=dict(symbol='circle', size=10, color='orange'), name='Hold'), row=1, col=1)
259
 
260
  # Add subplot for MACD
261
  # fig2 = go.Figure()
262
+ fig.add_trace(go.Scatter(x=data2['Date'], y=data2['MACD_12_26_9'], mode='lines', name='MACD', yaxis='y2',
263
+ line=dict(dash='solid', color=cs.macd_color, width=2)), row=2, col=1)
264
+ fig.add_trace(go.Scatter(x=data2['Date'], y=data2['MACDs_12_26_9'], mode='lines', name='Signal', yaxis='y2',
265
+ line=dict(dash='solid', color=cs.macd_signal_color, width=2)), row=2, col=1)
266
+ fig.add_trace(go.Bar(x=data2['Date'], y=data2['MACDh_12_26_9'], name='Histogram', yaxis='y2',
267
+ marker=dict(color=cs.macd_hist)), row=2, col=1)
268
+
269
+ # Update layout
 
270
  fig.update_layout(title='Close Price vs MACD')
271
+
272
+ # Add date range selection buttons to chart
273
  fig.update_xaxes(
274
  rangeslider_visible=False,
275
  rangeselector=dict(
 
282
  ])
283
  )
284
  )
285
+ fig.update_yaxes(fixedrange=False)
286
+
287
+ # Show chart on WebApp
288
  st.plotly_chart(fig, use_container_width=True)
289
+
290
 
291
  elif selected_indicator == 'RSI':
292
  # Set up the figure
 
301
  fig.add_shape(type="line", x0=data2['Date'].min(), y0=overbought_strong, x1=data2['Date'].max(), y1=overbought_strong, line=dict(color="red", width=1, dash="dash"), name="Overbought")
302
  fig.add_shape(type="line", x0=data2['Date'].min(), y0=oversold_strong, x1=data2['Date'].max(), y1=oversold_strong, line=dict(color="green", width=1, dash="dash"), name="Oversold")
303
 
304
+ # Plot buy/sell signals
305
  if num_signals != 'None':
306
+ # get signal values using the signals_to_plot utils function
307
  strong_buy_dates, strong_sell_dates, strong_hold_dates = signals_to_plot(
308
  selected_indicator=selected_indicator,
309
  num_signals=num_signals,
310
  signal_column='RSI_Signals',
311
  data=data2)
312
+
313
+ # Add Buy signals
314
+ fig.add_trace(go.Scatter(x=strong_buy_dates['Date'], y=strong_buy_dates['RSI'], mode='markers',
315
+ marker=dict(symbol='triangle-up', size=10, color=cs.pos_impacts_color), name='Strong Buy'))
316
+ # Add Sell signals
317
+ fig.add_trace(go.Scatter(x=strong_sell_dates['Date'], y=strong_sell_dates['RSI'], mode='markers',
318
+ marker=dict(symbol='triangle-down', size=10, color=cs.neg_impacts_color), name='Strong Sell'))
319
  # fig.add_trace(go.Scatter(x=strong_hold_dates['Date'], y=strong_hold_dates['RSI'], mode='markers', marker=dict(symbol='circle', size=10, color='orange'), name='Hold'))
320
 
321
  fig.update_layout(title='RSI Analysis', showlegend=True)
322
+
323
+ # Add date range selection buttons to chart
324
  fig.update_xaxes(
325
  rangeslider_visible=True,
326
  rangeselector=dict(
 
333
  ])
334
  )
335
  )
336
+ fig.update_yaxes(fixedrange=False)
337
  st.plotly_chart(fig)
338
  # st.write(data2)
339
 
340
+
341
+ # Add discalimer
342
+ st.markdown(disclaimer, unsafe_allow_html=True)
 
 
 
343
 
344
  with news_analysis:
345
  st.header("News Analysis", help="This module provides news based event impact for the following day based on the current date.")
346
  # st.write("This module provides news based event impact for the following day based on the current date.")
347
 
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)
 
497
  st.write(set(features))
498
 
499
 
500
+ # Add Disclaimer
501
+ st.markdown(disclaimer, unsafe_allow_html=True)
 
 
 
 
502
 
503
 
504
  with final_recs:
 
635
  # Update y-axis to allow vertical scrolling and dragging
636
  figure.update_yaxes(fixedrange=False)
637
  st.plotly_chart(figure)
 
 
 
 
 
 
 
 
638
 
639
+ # Add Disclaimer
640
+ st.markdown(disclaimer, unsafe_allow_html=True)
641
 
642
 
643
+ with chat:
644
  st.header("Chat with AI Stock Advisor")
645
 
646
+ # loader = CSVLoader("Events_SameDay.csv",encoding='iso-8859-1')
647
+
648
+ # Initialize HuggingFace Instruct Embeddings
649
  embeddings = HuggingFaceInstructEmbeddings()
650
+
651
+ # Load saved Vector Store
652
  persist_directory = 'FAISS_VectorStore'
653
+ db = FAISS.load_local(persist_directory, embeddings, allow_dangerous_deserialization=True)
654
+
655
+ # Initialize GenAI LLM Model
656
  repo_id = "mistralai/Mistral-7B-Instruct-v0.1"
657
  llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature": 0.1, "max_new_tokens": 1024})
658
+
659
+ # Define Prompt Template
660
  system_prompt = """You are a financial expert for stock market who can perform multiple tasks for the intended user including trading
661
  recommendations with reasoning, retrieving articles with their impact in the market, retrieving or enlisting features affecting market
662
  trends (could be positive or negative).However, if a user is asking for trading recommendation, then you need to generate trading signal
 
682
  "\nHelpful Answer: \n"
683
  )
684
  sys_prompt = PromptTemplate(input_variables=["context", "question"], template=template)
685
+
686
+ # Create QA Chain
687
  chain = RetrievalQA.from_chain_type(
688
+ llm=llm, # Add LLM
689
  chain_type="stuff",
690
+ retriever=db.as_retriever(), # Add Vector Store
691
  input_key="question",
692
+ chain_type_kwargs={"prompt": sys_prompt}) # Add prompt template
693
 
694
+ # Add Container to display chat history
695
  chat_container = st.container(height = 300, border=False)
696
  with chat_container:
697
  # Initialize chat history
 
703
  with st.chat_message(message["role"]):
704
  st.markdown(message["content"])
705
 
706
+
707
+ st.divider() # Divider to separate chat history and chat input
708
  # Accept user input
709
  if prompt := st.chat_input("Enter your query here.", key='input2'):
710
  # Add user message to chat history
 
713
  with chat_container.chat_message("user"):
714
  st.markdown(prompt)
715
 
716
+ # Get Response to user query from LLM
 
717
  response = chain({"question": prompt})
718
+ # Extract the answer from the response
719
  result = get_answer(response['result'])
 
720
 
721
  # Display assistant response in chat message container
722
  with chat_container.chat_message("assistant"):