Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,12 +2,10 @@ import os
|
|
| 2 |
import nltk
|
| 3 |
import requests
|
| 4 |
import datetime
|
| 5 |
-
# Use a directory within the user's home directory
|
| 6 |
nltk_data_dir = os.path.expanduser("~/.nltk_data")
|
| 7 |
os.makedirs(nltk_data_dir, exist_ok=True)
|
| 8 |
nltk.data.path.append(nltk_data_dir)
|
| 9 |
|
| 10 |
-
# Download NLTK data
|
| 11 |
nltk.download('punkt', download_dir=nltk_data_dir, quiet=True)
|
| 12 |
import chainlit as cl
|
| 13 |
from llama_index.core import VectorStoreIndex, Document
|
|
@@ -21,15 +19,12 @@ import pandas as pd
|
|
| 21 |
|
| 22 |
load_dotenv()
|
| 23 |
|
| 24 |
-
# Fetch the API keys from environment variables
|
| 25 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 26 |
FMP_API_KEY = os.getenv("FMP_API_KEY")
|
| 27 |
|
| 28 |
-
# Initialize models
|
| 29 |
embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 30 |
llm = Groq(model="llama3-70b-8192", api_key=GROQ_API_KEY)
|
| 31 |
|
| 32 |
-
# Create service context
|
| 33 |
service_context = ServiceContext.from_defaults(
|
| 34 |
llm=llm,
|
| 35 |
embed_model=embed_model,
|
|
@@ -37,23 +32,12 @@ service_context = ServiceContext.from_defaults(
|
|
| 37 |
)
|
| 38 |
|
| 39 |
def fetch_annual_report_10k(symbol: str) -> str:
|
| 40 |
-
"""
|
| 41 |
-
Fetch the latest annual report on Form 10-K for a specific company.
|
| 42 |
-
|
| 43 |
-
Args:
|
| 44 |
-
- symbol (str): The stock ticker symbol (e.g., 'AAPL').
|
| 45 |
-
|
| 46 |
-
Returns:
|
| 47 |
-
- str: The entire JSON response as a string or an error message.
|
| 48 |
-
"""
|
| 49 |
current_year = datetime.datetime.now().year
|
| 50 |
url = f"https://financialmodelingprep.com/api/v4/financial-reports-json?symbol={symbol}&year={current_year}&period=FY&apikey={FMP_API_KEY}"
|
| 51 |
-
|
| 52 |
try:
|
| 53 |
response = requests.get(url, timeout=10)
|
| 54 |
response.raise_for_status()
|
| 55 |
-
return response.text
|
| 56 |
-
|
| 57 |
except requests.exceptions.HTTPError as http_err:
|
| 58 |
return f"HTTP error occurred: {http_err}"
|
| 59 |
except requests.exceptions.RequestException as req_err:
|
|
@@ -61,7 +45,6 @@ def fetch_annual_report_10k(symbol: str) -> str:
|
|
| 61 |
except Exception as err:
|
| 62 |
return f"An unexpected error occurred: {err}"
|
| 63 |
|
| 64 |
-
# Prompts
|
| 65 |
summary_prompt = (
|
| 66 |
"You are a world-class financial analyst with extensive experience analyzing annual reports. "
|
| 67 |
"Provide a comprehensive summary of the 10-K report. Focus on Strategic Insights, Key Financial Figures, and Risk Factors. "
|
|
@@ -86,49 +69,44 @@ async def on_chat_start():
|
|
| 86 |
)
|
| 87 |
).send()
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
ticker_symbol = ticker_response['content'].upper()
|
| 90 |
|
| 91 |
msg = cl.Message(content=f"Retrieving the latest 10-K report for {ticker_symbol}...")
|
| 92 |
await msg.send()
|
| 93 |
|
| 94 |
try:
|
| 95 |
-
# Fetch the 10-K report using the adjusted function
|
| 96 |
annual_report_text = fetch_annual_report_10k(ticker_symbol)
|
| 97 |
|
| 98 |
-
# Check if an error message was returned
|
| 99 |
if annual_report_text.startswith("HTTP error") or \
|
| 100 |
annual_report_text.startswith("Request error") or \
|
| 101 |
annual_report_text.startswith("An unexpected error occurred"):
|
| 102 |
await cl.Message(content=annual_report_text).send()
|
| 103 |
return
|
| 104 |
|
| 105 |
-
# Create a Document object with the raw JSON response
|
| 106 |
document = Document(text=annual_report_text, metadata={"company": ticker_symbol})
|
| 107 |
|
| 108 |
-
# Create index
|
| 109 |
index = VectorStoreIndex.from_documents(
|
| 110 |
[document], service_context=service_context
|
| 111 |
)
|
| 112 |
|
| 113 |
-
# Store the index in the user session
|
| 114 |
cl.user_session.set("index", index)
|
| 115 |
|
| 116 |
-
# Generate summary
|
| 117 |
query_engine = index.as_query_engine()
|
| 118 |
summary_response = await cl.make_async(query_engine.query)(summary_prompt)
|
| 119 |
await cl.Message(content=f"**Summary:**\n{summary_response}").send()
|
| 120 |
|
| 121 |
-
# Generate questions
|
| 122 |
questions_response = await cl.make_async(query_engine.query)(question_prompt)
|
| 123 |
questions_format = str(questions_response).split('\n')
|
| 124 |
relevant_questions = [question.strip() for question in questions_format if question.strip() and question.strip()[0].isdigit()]
|
| 125 |
|
| 126 |
-
# Display and answer questions
|
| 127 |
await cl.Message(content="Generated strategic questions and answers:").send()
|
| 128 |
for question in relevant_questions:
|
| 129 |
await cl.Message(content=f"**{question}**").send()
|
| 130 |
-
|
| 131 |
-
# Query the engine to get the answer for the question
|
| 132 |
answer = await cl.make_async(query_engine.query)(question)
|
| 133 |
await cl.Message(content=f"**Answer:**\n{answer}").send()
|
| 134 |
|
|
|
|
| 2 |
import nltk
|
| 3 |
import requests
|
| 4 |
import datetime
|
|
|
|
| 5 |
nltk_data_dir = os.path.expanduser("~/.nltk_data")
|
| 6 |
os.makedirs(nltk_data_dir, exist_ok=True)
|
| 7 |
nltk.data.path.append(nltk_data_dir)
|
| 8 |
|
|
|
|
| 9 |
nltk.download('punkt', download_dir=nltk_data_dir, quiet=True)
|
| 10 |
import chainlit as cl
|
| 11 |
from llama_index.core import VectorStoreIndex, Document
|
|
|
|
| 19 |
|
| 20 |
load_dotenv()
|
| 21 |
|
|
|
|
| 22 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 23 |
FMP_API_KEY = os.getenv("FMP_API_KEY")
|
| 24 |
|
|
|
|
| 25 |
embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 26 |
llm = Groq(model="llama3-70b-8192", api_key=GROQ_API_KEY)
|
| 27 |
|
|
|
|
| 28 |
service_context = ServiceContext.from_defaults(
|
| 29 |
llm=llm,
|
| 30 |
embed_model=embed_model,
|
|
|
|
| 32 |
)
|
| 33 |
|
| 34 |
def fetch_annual_report_10k(symbol: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
current_year = datetime.datetime.now().year
|
| 36 |
url = f"https://financialmodelingprep.com/api/v4/financial-reports-json?symbol={symbol}&year={current_year}&period=FY&apikey={FMP_API_KEY}"
|
|
|
|
| 37 |
try:
|
| 38 |
response = requests.get(url, timeout=10)
|
| 39 |
response.raise_for_status()
|
| 40 |
+
return response.text
|
|
|
|
| 41 |
except requests.exceptions.HTTPError as http_err:
|
| 42 |
return f"HTTP error occurred: {http_err}"
|
| 43 |
except requests.exceptions.RequestException as req_err:
|
|
|
|
| 45 |
except Exception as err:
|
| 46 |
return f"An unexpected error occurred: {err}"
|
| 47 |
|
|
|
|
| 48 |
summary_prompt = (
|
| 49 |
"You are a world-class financial analyst with extensive experience analyzing annual reports. "
|
| 50 |
"Provide a comprehensive summary of the 10-K report. Focus on Strategic Insights, Key Financial Figures, and Risk Factors. "
|
|
|
|
| 69 |
)
|
| 70 |
).send()
|
| 71 |
|
| 72 |
+
# Check if ticker_response is None or lacks 'content'
|
| 73 |
+
if ticker_response is None or 'content' not in ticker_response:
|
| 74 |
+
await cl.Message(content="No ticker symbol provided. Please enter a valid ticker symbol to proceed.").send()
|
| 75 |
+
return
|
| 76 |
+
|
| 77 |
ticker_symbol = ticker_response['content'].upper()
|
| 78 |
|
| 79 |
msg = cl.Message(content=f"Retrieving the latest 10-K report for {ticker_symbol}...")
|
| 80 |
await msg.send()
|
| 81 |
|
| 82 |
try:
|
|
|
|
| 83 |
annual_report_text = fetch_annual_report_10k(ticker_symbol)
|
| 84 |
|
|
|
|
| 85 |
if annual_report_text.startswith("HTTP error") or \
|
| 86 |
annual_report_text.startswith("Request error") or \
|
| 87 |
annual_report_text.startswith("An unexpected error occurred"):
|
| 88 |
await cl.Message(content=annual_report_text).send()
|
| 89 |
return
|
| 90 |
|
|
|
|
| 91 |
document = Document(text=annual_report_text, metadata={"company": ticker_symbol})
|
| 92 |
|
|
|
|
| 93 |
index = VectorStoreIndex.from_documents(
|
| 94 |
[document], service_context=service_context
|
| 95 |
)
|
| 96 |
|
|
|
|
| 97 |
cl.user_session.set("index", index)
|
| 98 |
|
|
|
|
| 99 |
query_engine = index.as_query_engine()
|
| 100 |
summary_response = await cl.make_async(query_engine.query)(summary_prompt)
|
| 101 |
await cl.Message(content=f"**Summary:**\n{summary_response}").send()
|
| 102 |
|
|
|
|
| 103 |
questions_response = await cl.make_async(query_engine.query)(question_prompt)
|
| 104 |
questions_format = str(questions_response).split('\n')
|
| 105 |
relevant_questions = [question.strip() for question in questions_format if question.strip() and question.strip()[0].isdigit()]
|
| 106 |
|
|
|
|
| 107 |
await cl.Message(content="Generated strategic questions and answers:").send()
|
| 108 |
for question in relevant_questions:
|
| 109 |
await cl.Message(content=f"**{question}**").send()
|
|
|
|
|
|
|
| 110 |
answer = await cl.make_async(query_engine.query)(question)
|
| 111 |
await cl.Message(content=f"**Answer:**\n{answer}").send()
|
| 112 |
|