The Pydantic AI Stock Analyst Agent is a comprehensive stock analysis application powered by Pydantic AI and Groq's Llama3.1-8b-instant model. It leverages real-time financial data from Yahoo Finance to generate detailed analyst reports, including technical analysis, market insights, and ESG data.
This application is designed for informational purposes only and does not constitute financial advice. Please refer to the Disclaimer section for more details.
- Stock Data Retrieval: Fetches real-time stock data, including financials, recommendations, sustainability metrics, and market history.
- Technical Analysis: Generates price charts with 50-day and 200-day simple moving averages (SMA).
- News Summarization: Summarizes the latest news related to the queried stock.
- Sector Overview: Provides insights into the sector of the queried company.
- LLM-Powered Analysis: Uses Groq's Llama3.1-8b-instant model for generating executive summaries, investment theses, and recommendations.
- Pydantic AI Integration: Standardizes report outputs with schema-based validation.
- ESG Analysis: Highlights environmental, social, and governance metrics for sustainable investing.
- Interactive Interface: User-friendly interface powered by Gradio for seamless interaction.
Here is a demo where the model generates a report for Apple Inc (NASDAQ: AAPL)
- Python 3.10
- Libraries:
pydantic_ai
yfinance
gradio
matplotlib
pandas
dotenv
nest_asyncio
base64
- A valid
GROQ_API_KEY
stored in a.env
file.
-
Clone the Repository:
git clone https://github.com/yYorky/PydanticAI-Agent-Analyst.git cd pydantic-ai-stock-analyst
-
Install Dependencies:
pip install -r requirements.txt
-
Set Up Environment Variables:
- Create a
.env
file in the project root and add yourGROQ_API_KEY
:GROQ_API_KEY=your_groq_api_key
- Create a
-
Launch the Application:
python app4_3.py
-
Access the Interface:
- Open your browser and navigate to
http://127.0.0.1:7860/
.
- Open your browser and navigate to
-
Generate a Report:
- Enter a stock symbol (e.g.,
AAPL
) and click Generate Report to view a detailed analysis.
- Enter a stock symbol (e.g.,
The Pydantic AI library enhances the reliability and consistency of report outputs by leveraging schema-based validation. This ensures that the responses generated by the Groq's LLM strictly adhere to a predefined structure, minimizing errors and ambiguities.
-
Defining the Schema:
- The
AnalystReport
schema is created using Pydantic'sBaseModel
. It outlines all necessary fields, including their data types and structures, ensuring every report contains the same standardized sections.
Example:
class AnalystReport(BaseModel): symbol: str executive_summary: str company_overview: str industry_and_market_analysis: str investment_thesis: str financial_analysis: str risks_and_concerns: str catalysts: str technical_analysis: str esg_analysis: str recommendations: str appendices_and_disclosures: str
- The
-
Agent Framework:
- The Pydantic AI
Agent
integrates with the Groq model, combining advanced LLM capabilities with strict validation. This guarantees that any response generated by the LLM conforms to theAnalystReport
schema before it is presented to the user.
- The Pydantic AI
-
Validation Process:
- When the LLM generates a report, the Pydantic AI Agent automatically validates the response. If any field is missing or incorrectly formatted, the validation process raises an error, ensuring only accurate and complete reports are returned.
-
Consistent and Structured Output:
- The validated response ensures that all sections of the analyst report—such as Executive Summary, Financial Analysis, and ESG Insights—are consistently formatted and easy to interpret.
-
Error Handling:
- If the LLM fails to generate a valid response, the application catches the error and provides a meaningful message, ensuring a robust and user-friendly experience.
-
Stock Data Fetching:
- Uses
yfinance
to retrieve stock details, including price, historical data, and financial metrics.
- Uses
-
Data Formatting:
- Formats numerical and tabular data for better readability.
-
LLM Query with Pydantic AI Agent:
- Constructs a comprehensive system prompt to query Groq's Llama3.1-8b-instant model. The Pydantic AI Agent ensures that all LLM responses are validated against the
AnalystReport
schema.
- Constructs a comprehensive system prompt to query Groq's Llama3.1-8b-instant model. The Pydantic AI Agent ensures that all LLM responses are validated against the
-
Validation:
- The Pydantic AI Agent validates every response from the LLM for accuracy and completeness, ensuring standardized outputs.
-
Visualization:
- Generates and embeds technical analysis charts.
-
Input Stock Symbol:
- User inputs a stock symbol (e.g.,
AAPL
) into the Gradio interface.
- User inputs a stock symbol (e.g.,
-
Data Fetching:
- Retrieves financial data using
yfinance
and pre-processes it.
- Retrieves financial data using
-
Structured LLM Response:
- The LLM generates a detailed, structured report validated against the
AnalystReport
schema by the Pydantic AI Agent.
- The LLM generates a detailed, structured report validated against the
-
Report Generation:
- The validated and formatted response is displayed in the interface with visualizations and insights.
This application is intended for informational purposes only and does not constitute financial advice. The generated reports are based on publicly available data and model predictions, which may be incomplete or inaccurate. Use this tool at your own risk.