submit_ai_overview = st.button(f'{ticker} AI Overview')
if submit_ai_overview:
try:
if ticker == '':
st.warning('Please enter a ticker symbol')
else:
yf_ticker = yf.Ticker(ticker)
info = yf_ticker.info
metrics = {
'Current Price': info.get('regularMarketPrice'),
'Previous Close': info.get('previousClose'),
'Open': info.get('open'),
'Days Low': info.get('dayLow'),
'Days High': info.get('dayHigh'),
'Fifty Two Week Low': info.get('fiftyTwoWeekLow'),
'Fifty Two Week High': info.get('fiftyTwoWeekHigh'),
'Volume': info.get('volume'),
'Average Volume': info.get('averageVolume'),
'Market Cap': info.get('marketCap'),
'Beta': info.get('beta'),
'PE Ratio': info.get('trailingPE'),
'EPS': info.get('trailingEps'),
'Target Price': info.get('targetMeanPrice'),
}
def format_value(val):
if val is None:
return 'N/A'
if isinstance(val, (int, float)):
return f"{val:,.2f}"
if isinstance(val, datetime):
return val.strftime('%b %d, %Y')
return str(val)
metrics_formatted = {k: format_value(v) for k, v in metrics.items()}
prompt = f"""
You are a financial analyst. I will provide you with the stock ticker and a set of key financial metrics.
Your task is to write a clear, detailed, and professional summary of the company's current financial condition and performance, followed by an in-depth investment analysis.
Base your response only on the provided data. If any important data is missing, clearly state the limitation.
Ticker Symbol: {ticker}
Key Financial Metrics:
{metrics_formatted}
Instructions for your analysis:
1. **Company Overview** — Briefly describe what the company does (if identifiable from the ticker symbol).
2. **Financial Health** — Discuss profitability, liquidity, leverage, and efficiency based on the metrics.
3. **Growth & Trends** — Identify trends from the given values and note whether the company appears to be growing, stable, or declining.
4. **Valuation** — If valuation metrics are included (like P/E ratio, Price/Sales), analyze if the stock might be overvalued or undervalued.
5. **Risks & Concerns** — Highlight any red flags or concerning financial ratios.
6. **Investment Outlook** — Provide a reasoned outlook for the stock based on the metrics.
Write in full sentences, and keep your tone objective and data-driven.
"""
try:
# noinspection PyTypeChecker
response = groq_client.chat.completions.create(
model="llama3-8b-8192",
messages=[
{"role": "system",
"content": """You are a financial analyst. I will provide you with the stock ticker and a set of key financial metrics.
Your task is to write a clear, detailed, and professional summary of the company's current financial condition and performance, followed by an in-depth investment analysis.
Base your response only on the provided data. If any important data is missing, clearly state the limitation."""},
{"role": "user", "content": prompt}
],
temperature=0
)
answer = response.choices[0].message.content.strip()
st.markdown(f"**AI Analysis:** {answer}")
except Exception as e:
st.error(f"AI request failed: {e}")
Here’s a snippet of code from yesterday that consistently brought up the issue. Currently by switching from using metrics_formatted to multiple variables containing smaller amounts of data I’ve gotten it to work about 99% of the time (and when it does have concatenation issues its only a word or two). I’m currently using model llama3-8b-8192.