(图片来自浪链博客 | 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
) 设置为 0 来丢弃它。然后,它将分组字段(包含“transactions.symbol”的_id
)重命名为更清晰的名称“symbol”。最后,它使用$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 的结合代表了数据分析和解释的强大工具,但认识到一些潜在的限制也很重要:
对历史数据的依赖:过去的表现可能并不总是能预测未来的结果,特别是在不可预测的市场中,不可预见的事件可能会严重影响投资结果。
预测的不确定性:尽管分析很复杂,但投资预测始终存在一定程度的固有不确定性。未来的结果本质上是不可知的,历史数据范围之外的因素可能会影响结果。
法学硕士的局限性:法学硕士仍在不断发展,他们研究、解释和分析数据的能力正在不断提高。然而,训练数据的偏差或模型架构的限制可能会导致不准确或误导性的见解。
通过了解这些限制并采取措施缓解这些限制,您可以确保采用更负责任、更全面的投资分析方法。