This tutorial demonstrates how you can build an AI agent workflow in Python that simulates a financial hedge fund, using LangChain and the Perplexity Sonar API. Most agentic AI workflows rely on external tool calls for web browsing, but the Perplexity Sonar Reasoning model incorporates real-time internet access in its boosted DeepSeek-R1 model. AI agent building cheat code!
We’ll create a modular AI pipeline where specialized AI agents retrieve real-time market data, analyze sentiment, assess macroeconomic trends, develop a trading strategy, and evaluate risk.
This workflow is just the beginning. You can expand it by incorporating alternative data sources, specify an investment thesis, and add additional AI agents that mimic other types of financial analysts. You could also automate this code to quickly gather investment strategies for an entire portfolio of stocks.
Full Code Below the Video
Important Note: This video is not financial or investing advice. It is an educational tutorial on how to automate financial data collection and use AI/LLM models in Python. Also, don't blindly trust the results of LLM model results without critical thinking or subject matter expertise 🧠. LLM's are still experimental technology that have high error rates.
Environment
# Example Environment Creation using Conda
# Create a new Conda environment with Python 3.9
conda create --name ai_hedge_fund python=3.9 -y
# Activate the environment
conda activate ai_hedge_fund
# Install required packages
pip install langchain==0.3.19 langchain-community==0.3.18 openai==1.65.2 ipykernel==6.29.5
Full Code
# -------------------- Libraries and Modules -------------
from langchain import PromptTemplate, LLMChain
from langchain_community.chat_models.perplexity import ChatPerplexity
from langchain.chains import SequentialChain
# -------------------- Initialization --------------------
# API key and model initialization
PPLX_API_KEY = "API KEY GOES HERE"
llm = ChatPerplexity(model="sonar-reasoning",
temperature=0.5,
pplx_api_key=PPLX_API_KEY)
# -------------------- Chain Definitions --------------------
# 1. Market Data Analyst: Retrieve financial data
market_data_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["ticker"],
template=(
"📈 For {ticker}, provide detailed and up-to-date financial data. Include current stock price, "
"volume, key financial ratios (e.g., P/E, P/B, dividend yield), recent price trends, and relevant market indicators."
)
),
output_key="market_data"
)
# 2. Sentiment Analyst: Analyze news and social media sentiment
sentiment_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["ticker"],
template=(
"📰 For {ticker}, analyze recent news articles, social media posts, and expert commentary. "
"Summarize the prevailing sentiment, highlight any key events, and note emerging trends that may impact the stock."
)
),
output_key="sentiment_analysis"
)
# 3. Macro-Economic Analyst: Evaluate macro-economic conditions
macro_analysis_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["ticker"],
template=(
"🌐 For {ticker}, analyze the current macro-economic environment. "
"Include key indicators such as GDP growth, inflation rates, interest rates, unemployment trends, "
"and central bank policies. Summarize how these factors could impact the overall market and the asset."
)
),
output_key="macro_analysis"
)
# 4. Quantitative Strategist: Develop a trading strategy
strategy_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["market_data", "sentiment_analysis", "macro_analysis"],
template=(
"📊 Using the detailed market data:\n{market_data}\n"
"the sentiment analysis:\n{sentiment_analysis}\n"
"and the macro-economic analysis:\n{macro_analysis}\n"
"develop a sophisticated trading strategy. Outline a clear asset allocation, specify entry and exit points, "
"detail risk management measures, and provide estimated expected returns. If applicable, incorporate algorithmic signals."
)
),
output_key="strategy"
)
# 5. Risk Manager: Assess the strategy's risk
risk_chain = LLMChain(
llm=llm,
prompt=PromptTemplate(
input_variables=["strategy"],
template=(
"⚠️ Evaluate the following trading strategy:\n{strategy}\n"
"Identify potential risks such as market volatility, liquidity issues, or unexpected market events. "
"Summarize your risk assessment in 4 concise bullet points, and state in the final bullet point whether the strategy meets an acceptable risk tolerance."
)
),
output_key="risk_assessment"
)
# -------------------- Sequential Orchestration --------------------
sequential_agent = SequentialChain(
chains=[market_data_chain, sentiment_chain, macro_analysis_chain, strategy_chain, risk_chain],
input_variables=["ticker"],
output_variables=["market_data", "sentiment_analysis", "macro_analysis", "strategy", "risk_assessment"],
verbose=True
)
# -------------------- Run the Analysis --------------------
def run_ai_hedge_fund(ticker: str) -> None:
result = sequential_agent({"ticker": ticker})
print("\n======== AI Hedge Fund Analysis Results ========\n")
print("📈 Market Data Retrieved:")
print("--------------------------------------------------")
print(result["market_data"], "\n")
print("📰 Market Sentiment Analysis:")
print("--------------------------------------------------")
print(result["sentiment_analysis"], "\n")
print("🌐 Macro-Economic Analysis:")
print("--------------------------------------------------")
print(result["macro_analysis"], "\n")
print("📊 Developed Trading Strategy:")
print("--------------------------------------------------")
print(result["strategy"], "\n")
print("⚠️ Risk Assessment:")
print("--------------------------------------------------")
print(result["risk_assessment"], "\n")
print("==============================================\n")
# Run the analysis for a given ticker (e.g., "MSFT")
run_ai_hedge_fund("MSFT")
Subscribe to the Deep Charts YouTube Channel for more informative AI and Machine Learning Tutorials.
is it possible to n8n it to a telegram or whatsapp bot to make the front end and reporting more like conversations with a real hedge fund analyst?
This is absolutely beautiful! I’d love to see a replication with Wetrocloud.com
No need for LangChain or handling indexing and data storage in another db. The heavy lifting is taken care of.