FinSight / utils /agentic.py
YasirAhmad0810's picture
Upload 2 files
2b6c882 verified
"""
FinancialInsights.py
A single-file, modular-style agentic workflow for financial news insights.
This file can be imported by a main application (e.g., a FastAPI server)
to run the crew.
"""
import os
from crewai import Agent, Task, Crew, Process, LLM
from crewai_tools import SerperDevTool
# --- 1. Configuration ---
# Using a placeholder for the model name as per your original script.
# Replace with a valid model identifier if needed.
LLM_MODEL = "gemini/gemini-2.5-flash-lite"
LLM_TEMPERATURE = 0.7
SERPER_SEARCH_URL = "https://google.serper.dev/search"
SERPER_N_RESULTS = 5 # Increased results for better financial context
# --- 2. LLM & Tool Initialization ---
# Initialize the LLM instance
llm = LLM(
model=LLM_MODEL,
temperature=LLM_TEMPERATURE,
)
# Initialize the search tool
search_tool = SerperDevTool(
search_url=SERPER_SEARCH_URL,
n_results=SERPER_N_RESULTS,
)
# --- 3. Agent Definitions ---
def create_financial_researcher():
"""Creates the Financial Researcher agent."""
return Agent(
role="Financial Researcher",
goal="Gather the latest news, market sentiment, and key developments "
"for the given list of financial topics, companies, and cryptocurrencies. "
"Use the Serper tool to find relevant articles, reports, and discussions.",
backstory=(
"You are an expert financial researcher, skilled at digging through "
"market news, press releases, and financial forums to find the most "
"relevant and timely information for an investor."
),
tools=[search_tool],
verbose=True,
memory=True,
llm=llm,
)
def create_financial_analyst():
"""Creates the Financial Analyst agent."""
return Agent(
role="Financial Analyst",
goal="Analyze the raw research findings and synthesize them into a "
"consolidated, easy-to-read investor insight report. "
"Identify key trends, potential risks, and opportunities. "
"The final output must be a professional report for an investor.",
backstory=(
"You are a seasoned financial analyst with a talent for "
"cutting through the noise. You can take a pile of raw data and "
"news snippets and distill them into actionable insights and "
"concise summaries for busy investors."
),
tools=[], # No external tools needed; analyzes data from the researcher
verbose=True,
memory=True,
allow_delegation=False,
llm=llm,
)
# --- 4. Task Definitions ---
def create_research_task(agent):
"""Creates the research task for the given agent."""
return Task(
description=(
"For each topic in the provided list {interests}, search for the "
"latest news, market analysis, and significant events from the past 48 hours. "
"Gather key snippets, sources, and general sentiment."
),
expected_output=(
"A structured report with sections for each topic, each containing:\n"
"Topic: <topic name>\n"
"Key News Snippets:\n- [Source]: <snippet>...\n"
"Market Sentiment:\n- <Summary of general sentiment (e.g., bullish, bearish, neutral)>\n"
"Recent Developments:\n- <Bulleted list of key events or changes>"
),
agent=agent,
tools=[search_tool],
)
def create_analysis_task(agent):
"""Creates the analysis and reporting task for the given agent."""
return Task(
description=(
"Take the researcher's raw findings for all {interests}. "
"Analyze and synthesize this information into a consolidated 'Investor Insight' report. "
"Start with a high-level executive summary, then provide a detailed "
"breakdown for each topic. Focus on what this information *means* "
"for an investor, highlighting key insights, risks, and potential opportunities."
),
expected_output=(
"A comprehensive investor report in markdown format.\n\n"
"## Executive Summary\n"
"<Brief overview of all topics and major market movements.>\n\n"
"## Detailed Insights\n\n"
"### [Topic 1 Name]\n"
"- **Key Insight:** <What is the most important takeaway?>\n"
"- **Recent News:** <Summary of the most impactful news.>\n"
"- **Potential Risk:** <Identify a potential risk.>\n"
"- **Potential Opportunity:** <Identify a potential opportunity.>\n\n"
"### [Topic 2 Name]\n"
"- **Key Insight:** <...>\n"
"- **Recent News:** <...>\n"
"- **Potential Risk:** <...>\n"
"- **Potential Opportunity:** <...>\n"
"(...and so on for all topics)"
),
agent=agent,
)
# --- 5. Crew Definition & Workflow Function ---
def run_financial_crew(interest_list):
"""
Initializes and kicks off the financial insights crew with a given list of interests.
This is the main function to be imported and called by an external app.
Args:
interest_list (list): A list of financial topics (strings) to research.
Returns:
str: The final result from the crew's execution (the investor report).
"""
# 1. Create Agents
financial_researcher = create_financial_researcher()
financial_analyst = create_financial_analyst()
# 2. Create Tasks
research_task = create_research_task(financial_researcher)
analysis_task = create_analysis_task(financial_analyst)
# 3. Create Crew
financial_crew = Crew(
agents=[financial_researcher, financial_analyst],
tasks=[research_task, analysis_task],
process=Process.sequential, # Sequential: Researcher -> Analyst
)
# 4. Prepare Inputs
inputs = {"interests": interest_list}
# 5. Run Crew
print(f"Starting crew for financial interests: {interest_list}...")
result = financial_crew.kickoff(inputs=inputs)
return result
# --- 6. Independent Run (for testing) ---
if __name__ == "__main__":
"""
This block allows the script to be run directly for testing purposes.
It will not execute when the file is imported as a module.
"""
# Define the list of financial interests to research
interests = ["NVIDIA stock", "US inflation rate"]
# Run the crew workflow
result = run_financial_crew(interests)
# Print the final output
print("\n=== Final Investor Insight Report ===\n")
print(result)