eagle0504 commited on
Commit
1975189
1 Parent(s): 2f2d8ff

llm agent added

Browse files
Files changed (2) hide show
  1. utils/helper.py +62 -2
  2. utils/ui_helper.py +16 -2
utils/helper.py CHANGED
@@ -1,9 +1,14 @@
1
  # helper.py
2
- import yfinance as yf
 
 
3
  import matplotlib.pyplot as plt
4
  import numpy as np
5
  import pandas as pd
6
- from typing import List, Tuple, Dict
 
 
 
7
 
8
 
9
  def download_stock_data(
@@ -283,3 +288,58 @@ def display_simulated_ef_with_random(
283
  min_vol_allocation.sum(axis=1), axis=0
284
  ),
285
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # helper.py
2
+ import os
3
+ from typing import Dict, List, Tuple
4
+
5
  import matplotlib.pyplot as plt
6
  import numpy as np
7
  import pandas as pd
8
+ import yfinance as yf
9
+ from langchain import LLMChain, PromptTemplate
10
+ from langchain.agents import initialize_agent, load_tools
11
+ from langchain.llms import OpenAI
12
 
13
 
14
  def download_stock_data(
 
288
  min_vol_allocation.sum(axis=1), axis=0
289
  ),
290
  }
291
+
292
+
293
+ OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
294
+
295
+
296
+ def run_langchain_agent_(
297
+ question: str = "What is your question?", interested_tickers: str = "AAPL, META"
298
+ ) -> str:
299
+ """
300
+ Executes a language chain agent to answer questions by using a series of tools.
301
+
302
+ This function creates an instance of an OpenAI model, sets up a prompt template, loads necessary tools,
303
+ initializes the agent, and runs the agent with the provided question. It returns the agent's output.
304
+
305
+ Parameters:
306
+ question (str): The question to be answered by the agent. Defaults to "What is your question?".
307
+
308
+ Returns:
309
+ str: The output response from the agent after processing the question.
310
+
311
+ """
312
+
313
+ # Instantiating an OpenAI language model with specific temperature setting
314
+ llm = OpenAI(
315
+ temperature=0.1
316
+ ) # model_name="text-davinci-003" implied but commented out
317
+
318
+ # Creating a prompt template that structures the input question and a step-by-step thinking format
319
+ template = """Question: {question};
320
+ Information given about interested stock tickers in the financial market: {interested_tickers}
321
+
322
+ You are a financial advisor and user has a question above regarding related tickers provided.
323
+
324
+ Let's think step by step.
325
+ Answer: """
326
+ prompt = PromptTemplate(
327
+ template=template, input_variables=["question", "interested_tickers"]
328
+ )
329
+
330
+ # Building a chain of language model actions based on the prompt template
331
+ llm_chain = LLMChain(prompt=prompt, llm=llm)
332
+
333
+ # Loading additional language model tools like Wikipedia and math modules
334
+ tools = load_tools(["wikipedia", "llm-math"], llm=llm)
335
+
336
+ # Initializing the agent with the loaded tools, the language model, default name, and verbosity
337
+ agent = initialize_agent(
338
+ tools, llm, agent="zero-shot-react-description", verbose=True
339
+ )
340
+
341
+ # Running the agent to process the input question and generate an output
342
+ output_ = agent.run(question)
343
+
344
+ # Return
345
+ return output_
utils/ui_helper.py CHANGED
@@ -171,7 +171,7 @@ def main_algo_trader():
171
  # Checkpoint: ask user whether they want portfolio weights
172
  if csv:
173
  recent_selected_stocks = df["portfolio_history"][-1]
174
- recent_selected_stocks = ', '.join(recent_selected_stocks)
175
  st.success(
176
  f"The algorithm suggests to hold the following stocks for the current month (equally weighted): {recent_selected_stocks}"
177
  )
@@ -185,6 +185,20 @@ def main_algo_trader():
185
  mime="text/csv",
186
  )
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
  # chinese
190
  def main_algo_trader_chinese():
@@ -348,7 +362,7 @@ def main_algo_trader_chinese():
348
  # Checkpoint: ask user whether they want portfolio weights
349
  if csv:
350
  recent_selected_stocks = df["portfolio_history"][-1]
351
- recent_selected_stocks = ', '.join(recent_selected_stocks)
352
  st.success(f"算法建议在本月持有以下股票(均仓位): {recent_selected_stocks}")
353
 
354
  with col2:
 
171
  # Checkpoint: ask user whether they want portfolio weights
172
  if csv:
173
  recent_selected_stocks = df["portfolio_history"][-1]
174
+ recent_selected_stocks = ", ".join(recent_selected_stocks)
175
  st.success(
176
  f"The algorithm suggests to hold the following stocks for the current month (equally weighted): {recent_selected_stocks}"
177
  )
 
185
  mime="text/csv",
186
  )
187
 
188
+ # Question-answering
189
+ if csv:
190
+ user_question = st.text_input(
191
+ "Enter your question:",
192
+ "Tell me about the company with stock ticker AAPL.",
193
+ )
194
+ st.write(f"Question entered: {user_question}")
195
+ with st.spinner("Running langchain agent with GPT3..."):
196
+ final_ans = run_langchain_agent_(
197
+ question=str(user_question),
198
+ interested_tickers=str(recent_selected_stocks),
199
+ )
200
+ st.markdown(final_ans)
201
+
202
 
203
  # chinese
204
  def main_algo_trader_chinese():
 
362
  # Checkpoint: ask user whether they want portfolio weights
363
  if csv:
364
  recent_selected_stocks = df["portfolio_history"][-1]
365
+ recent_selected_stocks = ", ".join(recent_selected_stocks)
366
  st.success(f"算法建议在本月持有以下股票(均仓位): {recent_selected_stocks}")
367
 
368
  with col2: