(圖片來自浪鏈部落格 | CrewAI:人工智慧代理團隊的未來)
MongoDB 聚合管道為我們提供了分析所需的資料。您從原始數據中提取有意義的見解的速度越快,您的投資決策就會越好。 CrewAI 與 MongoDB Atlas 的強大功能相結合,提供了一種獨特的方法,超越基本的數字運算,提供真正可行的分析。
對於此範例,我們將建立一個投資研究員代理。該代理是我們的專家,擅長使用搜尋引擎等工具來尋找有價值的數據。它旨在尋找金融趨勢、公司新聞和分析師見解。要了解有關使用 CrewAI 創建代理的更多信息,請單擊此處
釋放人工智慧協作的力量:代理、任務和工具
從本質上講,CrewAI 代理、任務和工具的強大組合使您能夠:
在我們開始之前
要繼續操作,您需要:
MongoDB Atlas Cluster:建立免費叢集並載入範例資料集。範例分析資料集中的交易資料提供了一個真實的資料集,允許使用者磨練資料分析、查詢和聚合方面的技能,特別是在財務資料背景下。
LLM 資源: CrewAI 支援各種 LLM 連接,包括本地模型 (Ollama)、Azure 等 API 以及用於可自訂 AI 解決方案的所有 LangChain LLM 元件。按此處了解有關 CrewAI LLM 支援的更多信息
接下來,我們設定與 Azure OpenAI 的連線。 Azure OpenAI 可以取代為您首選的法學碩士。
from langchain_openai import AzureChatOpenAI
AZURE_OPENAI_ENDPOINT = "https://__DEMO__.openai.azure.com"
AZURE_OPENAI_API_KEY = "__AZURE_OPENAI_API_KEY__"
deployment_name = "gpt-4-32k" # The name of your model deployment
default_llm = AzureChatOpenAI (
openai_api_version = os . environ . get ( "AZURE_OPENAI_VERSION" , "2023-07-01-preview" ),
azure_deployment = deployment_name ,
azure_endpoint = AZURE_OPENAI_ENDPOINT ,
api_key = AZURE_OPENAI_API_KEY
)
然後,我們將代理角色和代理目標設定為變量,以便可以在整個腳本中存取它。
# Initial Setup
AGENT_ROLE = "Investment Researcher"
AGENT_GOAL = """
Research stock market trends, company news, and analyst reports to identify potential investment opportunities.
"""
在此範例中,我們將使用 DuckDuckGo 搜尋 Langchain 整合。 DuckDuckGo 搜尋是一個允許用戶使用 DuckDuckGo 搜尋網路的元件。您可以使用您選擇的搜尋 API 來實現您的搜尋工具 - 它不一定是 DuckDuckGo。
# Web Search Setup
from langchain . tools import tool
from langchain_community . tools import DuckDuckGoSearchResults
duck_duck_go = DuckDuckGoSearchResults ( backend = "news" )
# Search Tool - Web Search
@ tool
def search_tool ( query : str ):
"""
Perform online research on a particular stock.
"""
return duck_duck_go . run ( query )
我們將使用 CrewAI 來管理我們的代理人和任務。在這種情況下,我們有一個代理 - 一名研究人員,其任務是分析數據並提供可行的見解。
# Research Agent Setup
from crewai import Crew , Process , Task , Agent
researcher = Agent (
role = 'Investment Researcher' ,
goal = """
Research market trends, company news, and analyst reports to identify potential investment opportunities.
""" ,
verbose = True ,
llm = default_llm ,
backstory = 'Expert in using search engines to uncover relevant financial data, news articles, and industry analysis.' ,
tools = [ search_tool ]
)
analysis_task = Task (
description = """
Using the following information:
[VERIFIED DATA]
{agg_data}
*note*
The data represents the average price of each stock symbol for each transaction type (buy/sell),
and the total amount of transactions for each type. This would give us insight into the average costs and proceeds from each stock,
as well as the volume of transactions for each stock.
[END VERIFIED DATA]
[TASK]
- Provide a financial summary of the VERIFIED DATA
- Research current events and trends, and provide actionable insights and recommendations
""" ,
agent = researcher ,
expected_output = 'concise markdown financial summary and list of actionable insights and recommendations' ,
tools = [ search_tool ],
)
tech_crew = Crew (
agents = [ researcher ],
tasks = [ analysis_task ],
process = Process . sequential
)
接下來,我們定義 MongoDB 聚合管道。此管道用於處理我們的交易數據並計算每個股票代碼的投資回報。
# MongoDB Aggregation Pipeline
pipeline = [
{
"$unwind" : "$transactions" # Deconstruct the transactions array into separate documents
},
{
"$group" : { # Group documents by stock symbol
"_id" : "$transactions.symbol" , # Use symbol as the grouping key
"buyValue" : { # Calculate total buy value
"$sum" : {
"$cond" : [ # Conditional sum based on transaction type
{ "$eq" : [ "$transactions.transaction_code" , "buy" ] }, # Check for "buy" transactions
{ "$toDouble" : "$transactions.total" }, # Convert total to double for sum
0 # Default value for non-buy transactions
]
}
},
"sellValue" : { # Calculate total sell value (similar to buyValue)
"$sum" : {
"$cond" : [
{ "$eq" : [ "$transactions.transaction_code" , "sell" ] },
{ "$toDouble" : "$transactions.total" },
0
]
}
}
}
},
{
"$project" : { # Project desired fields (renaming and calculating net gain)
"_id" : 0 , # Exclude original _id field
"symbol" : "$_id" , # Rename _id to symbol for clarity
"netGain" : { "$subtract" : [ "$sellValue" , "$buyValue" ] } # Calculate net gain
}
},
{
"$sort" : { "netGain" : - 1 } # Sort results by net gain (descending)
},
{ "$limit" : 3 } # Limit results to top 3 stocks
]
results = list ( collection . aggregate ( pipeline ))
client . close ()
print ( "MongoDB Aggregation Pipeline Results:" )
print ( results )
以下是 MongoDB 管道功能的詳細說明:
展開事務:首先,它使用$unwind
運算子來解壓縮每個文件中名為「transactions」的陣列欄位。想像一下,每個文件都包含多種股票購買和銷售的資訊。展開將這些交易分成單獨的文檔,使計算更加容易。
按符號分組:接下來, $group
運算子接手。它根據“transactions.symbol”欄位中的值對展開的文件進行分組。這實質上將特定股票(由 符號表示)的所有交易合併到一個群組中。
計算買入和賣出值:在每個交易品種組中,管道計算兩個關鍵值:
$sum
累加器以及條件語句 ( $cond
)。 $cond
檢查「transactions」物件中的「transaction_code」是否為「buy」。如果是,它會使用$toDouble
將「總計」欄位(交易金額)轉換為雙精確度值,並將其加到 buyValue 的運行總計中。如果不是購買交易,則不會對總和產生任何貢獻 (0)。這有效地計算了購買該特定代碼的股票所花費的總金額。投影結果:現在, $project
運算子介入定義最終的輸出格式。它透過將自動_id
的分組標識符 ( _id
) 設為 0 來丟棄它。最後,它使用$subtract
運算子計算每個交易品種的投資報酬率。這從sellValue
中減去buyValue
以確定該交易品種的利潤或損失。
按返回排序:最後, $sort
運算子組織結果。它根據“returnOnInvestment”欄位按降序 (-1) 對文件進行排序。這意味著投資回報率最高(利潤最高)的符號將首先出現在最終輸出中。
最後,我們開始執行任務。研究人員代理將使用來自我們的 MongoDB 聚合的資料以及他們可以使用的任何其他工具來分析資料並提供見解。
Final Answer:
# Detailed Financial Report
## TLDR Summary
Based on the net gain data and recent news trends, all three stocks – Amazon (AMZN), SAP (SAP), and Apple (AAPL) – show promising prospects. Amazon and Apple are experiencing growth and their stocks are hitting new highs. SAP has recently acquired WalkMe, indicating potential future growth.
## Key Insights and Recommendations
### Amazon (AMZN)
- Net Gain: $72,769,230.71
- Recent News: Amazon is poised for its next decade of growth after delivering a return of around 1,000% over the last decade. Its stock price recently hit a new all-time high.
- Recommendation: With its stock hitting an all-time high and positive future growth outlook, Amazon presents a solid investment opportunity for long-term investors.
### SAP (SAP)
- Net Gain: $39,912,931.04
- Recent News: SAP recently announced an agreement to acquire WalkMe, a digital adoption platform, in an all-cash deal valued at about $1.5 billion. The acquisition is expected to close in the third quarter of 2024.
- Recommendation: The recent acquisition of WalkMe indicates potential for future growth. Investors should keep a close eye on SAP's performance post-acquisition.
### Apple (AAPL)
- Net Gain: $25,738,882.29
- Recent News: Apple's stock has risen substantially since releasing its fiscal Q2 earnings. It is predicted to still be undervalued based on its powerful free cash flow.
- Recommendation: Given the powerful free cash flow and the potential for an AI-driven growth cycle, Apple appears to be a good investment opportunity.
## Other Observations
While all three stocks show promising prospects, it's important for investors to consider their own risk tolerance and investment goals before making investment decisions. It's also important to keep an eye on the market trends and news, as they can greatly impact the stock prices.
## Conclusion
In conclusion, Amazon, SAP, and Apple present promising investment opportunities based on their recent news and net gain data. However, as with all investments, potential investors should conduct thorough research and consider their own investment goals and risk tolerance.
雖然 MongoDB 的聚合框架和 GenAI 的結合代表了資料分析和解釋的強大工具,但認識到一些潛在的限制也很重要:
對歷史數據的依賴:過去的表現可能並不總是能預測未來的結果,特別是在不可預測的市場中,不可預見的事件可能會嚴重影響投資結果。
預測的不確定性:儘管分析很複雜,但投資預測始終存在一定程度的固有不確定性。未來的結果本質上是不可知的,歷史資料範圍之外的因素可能會影響結果。
法學碩士的限制:法學碩士仍在不斷發展,他們研究、解釋和分析數據的能力正在不斷提高。然而,訓練資料的偏差或模型架構的限制可能會導致不準確或誤導性的見解。
透過了解這些限制並採取措施緩解這些限制,您可以確保採用更負責任、更全面的投資分析方法。