在最近,一个更新的科技概念AI Agent(人工智能助手)引起了人们更为广泛的关注。比尔盖茨称其为“一个对科技行业的冲击波”。
OpenAI将AI Agent定义为“以大语言模型为大脑驱动的系统,具备自主理解、感知、规划、记忆和使用工具的能力,能够自动化执行完成复杂任务的系统。”我们可以将其通俗地理解为一个“你提要求就行,任务我来做”的强大工具人。
因此,本文要搭建一个扮演分析师角色的AI Agent。
但是,现实世界里的问题往往非常复杂,仅从单一角度进行分析远远不够。尽管让Agent从多个角度进行分析是可行的,但是由于多个角度的限制,它所给出的结论也会相应地因照顾角度而变得肤浅。因此,一个较好的解决办法是利用多个Agent,分别专注于某一特定角度进行分析,最后再将各自具有深度的分析内容进行整合。
令人兴奋的是,Python里的CrewAI库可以让用户搭建一个AI Agent团队,这个团队可以直接完成任务的所有的步骤,而不需要用户的任何介入。里面的Agent会各司其职,从而完成一个项目。
综上所述,本文要接入LLM的API,并利用Python的CrewAI库来搭建一个AI Agent团队,让它分析一个股票,并写出对应的研报。
重要提醒
国内用户不要连接Open AI的API,账户会因Open AI的地区政策而被直接封禁。除非有办法绕过地区政策
连接API
为在不违反地区政策且尽量的前提下完成这一目标,本文连接了Groq的API。
访问这个网站创建账号,并获取API_keys (科学上网):
点击访问Groq: https://console.groq.com/keys
Groq不需要收费,在创建账号后可以直接使用。 和OpenAI类似,点击上方链接后,点击create API key即可。
利用getpass来隐藏API TOKEN
利用os来定义GROQ_API_KEY
本文调用的llm是llama3-8b-8192
import getpass
import os
os.environ["GROQ_API_KEY"] = getpass.getpass()
from langchain_groq import ChatGroq
model = ChatGroq(model="llama3-8b-8192")
接入Groq后,本文使用LangChain库进行调用,让它说自己是猫。
from langchain_core.messages import HumanMessage
model.invoke([HumanMessage(content="说你是猫,中文回复")])
连接Tushare
接下来另一个非常重要的库是tushare,它可以获得对应的股票数据:
将自己的Token 替换’Your Token here’即可,如果遇到无法调用的情况,可能是自己的Token 的积分不够。
本文展示了五粮液2024年11月1日到2024年12月15日的数据:
import tushare as ts
pro = ts.pro_api('Your Token here')
df = pro.daily(ts_code='000858.SZ', start_date='20241101', end_date='20241215')
print(df.head())
ts_code是股票对应的代码,我们之后要反复使用。
安装CrewAI
Python的库一直被称赞为强大且丰富,在设计多个AI Agent让它们组成团队的时候,这一特点再次得到验证。
本文将直接利用Python的CrewAI库来完成组建Agent团队的目标。CrewAI是一个用于协调角色扮演、自主AI代理的Python框架。通过促进协作智能,CrewAI 使代理能够无缝协作,处理复杂的任务。
在使用之前,在终端安装CrewAI库。
pip install crewai
非常重要的点:
Crewai 需要 Python >=3.10 and <=3.12
查看版本号:
python3 --version
或者:
python --version
如果使用了Notebook进行编译,记得在Kernel设置为Python >=3.10 and <=3.12。
在CrewAI库中,我们利用Agent函数来定义AI Agent。
这个函数有以下几个常用参数:
CrewAI的官方文档还有更多详细的参数。
https://docs.crewai.com/concepts/agents
本文定义了四个agents,分别是股票研究员,用以了解股票的基本信息,财务研究员,用以分析股票的财务信息,报告撰写员,用以完成报告,翻译员,用以翻译研报。
from crewai import Crew, Agent, Task, Process
stock_researcher = Agent(
llm="groq/llama3-70b-8192",
role="Stock Researcher",
goal="get basic stock info about the selected stock.",
backstory="An junior stock researcher",
verbose=True,
allow_delegation=False
)
financial_analyst = Agent(
llm="groq/llama3-70b-8192",
role="Financial Analyst",
goal="Perform in-depth fundamental and technical analysis on the stock",
backstory="A seasoned financial analyst with expertise in interpreting complex financial data",
verbose=True,
allow_delegation=False
)
report_writer = Agent(
llm="groq/llama3-70b-8192",
role='Financial Report Writer',
goal='Synthesize all analysis into a cohesive, professional stock report',
backstory='Experienced financial writer with a talent for clear, concise reporting',
verbose=True,
allow_delegation=False
)
translate_writer = Agent(
llm="groq/llama3-70b-8192",
role='translator',
goal='Translation from English to simplified Chinese',
backstory='Experienced and financially literate translator',
verbose=True,
allow_delegation=False
)
Task函数指定了Agent要完成的具体的任务。
这个函数有以下几个常用参数:
CrewAI的官方文档还有更多详细的参数。
https://docs.crewai.com/concepts/tasks
在此我们定义了四个任务。find_company_task 提供公司名称和与股票代码相关的财务摘要,包括每股收益(EPS)、每股收入(Revenue per Share)。
perform_analysis 对指定公司(通过股票代码和名称识别)进行基本面分析,评估包括每股收益(EPS)、股本回报率(ROE)和资产负债率等财务比率,并基于公司财务健康状况提供投资建议。
generate_stock_report 为指定公司生成专业的股票报告。报告内容包括财务表现总结(如 EPS、每股收入和毛利率)、投资建议。
translate_report 翻译位简体中文。
find_company_task = Task(
description='''
Find the company name ({name}) and analyze its financial data for the stock code: {ts_code}.
Provide a summary of key financial indicators, including EPS ({eps}) and revenue per share ({revenue_ps}).
''',
expected_output="The company name and financial summary for the stock code {ts_code}.",
agent=stock_researcher,
)
perform_analysis = Task(
description='''
Analyze {name} ({ts_code}) in the {industry} industry, headquartered in {area}.
Focus on these key metrics:
- Earnings Per Share (EPS): {eps}
- Return on Equity (ROE): {roe}%
- Gross Margin: {grossprofit_margin}%
- Net Profit Margin: {netprofit_margin}%
Highlight trends in profitability and provide actionable insights based on the company's financial health.
''',
expected_output="A financial analysis of {name} ({ts_code}) with key insights.",
agent=financial_analyst,
async_execution=False,
dependencies=[find_company_task]
)
generate_stock_report = Task(
description='''
Prepare a stock report for {name} ({ts_code}), summarizing:
- Earnings: EPS ({eps}), ROE ({roe}%)
- Profitability: Net Profit Margin ({netprofit_margin}%), Gross Margin ({grossprofit_margin}%)
- Risk: Debt-to-Assets Ratio ({debt_to_assets}%)
Include actionable recommendations and use markdown format for clarity.
''',
agent=report_writer,
expected_output="A markdown-formatted stock report for {name} ({ts_code}).",
dependencies=[perform_analysis]
)
translate_report = Task(
description='''
Translate the stock report for {name} ({ts_code}) into simplified Chinese.
''',
expected_output="A translated markdown-formatted stock report for {name} ({ts_code}).",
agent=translate_writer,
dependencies=[generate_stock_report]
)
当定义完Agent函数和Task函数,用户就完成了一个最简单的AI Agent团队,利用Crew函数便可以尝试获得结果。
Crew函数有以下几个常用参数:
为了获得完整的且有说服力的研报, 我们利用tushare再获得一些数据,并将基本数据与财务数据合并。
import pandas as pd
df_fina = pro.fina_indicator(ts_code='000858.SZ')
df1 = pd.DataFrame(df_fina)
print(df1.head())
df2 = df1.iloc[1].to_dict()
print(df2)
df_basic = pro.stock_basic(ts_code='000858.SZ')
df3 = pd.DataFrame(df_basic)
df3 = df3.to_dict()
flattened_df3 = {key: value[0] for key, value in df3.items()}
merged_dict = {**df2, **flattened_df3}
print(merged_dict)
这里的tasks 和 agents 已在前文定义。
crew = Crew(
llm="groq/llama3-70b-8192",
agents=[stock_researcher, financial_analyst, report_writer],
tasks=[
find_company_task,
perform_analysis,
generate_stock_report
],
process=Process.sequential,
)
crew_output = crew.kickoff(inputs=merged_dict)
print(f"Raw Output: {crew_output.raw}")
Find the company name (五粮液) and analyze its financial data for the stock code: 000858.SZ.
Provide a summary of key financial indicators, including EPS (7.783) and revenue per share (21.453).
The company name for the stock code 000858.SZ is 五粮液 (Wuliangye Yibin Co., Ltd.). Based on the financial data, here is a summary of key financial indicators:
Company Name: 五粮液 (Wuliangye Yibin Co., Ltd.)
Stock Code: 000858.SZ
EPS (Earnings Per Share): 7.783
Revenue per Share: 21.453
Financial Summary:
The company 五粮液 (Wuliangye Yibin Co., Ltd.) with stock code 000858.SZ has a strong financial performance, as evident from its EPS of 7.783 and revenue per share of 21.453. These indicators suggest that the company is profitable and has a significant revenue generation capacity.
Analyze 五粮液 (000858.SZ) in the 白酒 industry, headquartered in 四川.
Focus on these key metrics:
- Earnings Per Share (EPS): 7.783
- Return on Equity (ROE): 24.8051%
- Gross Margin: 75.7936%
- Net Profit Margin: 37.8528%
Highlight trends in profitability and provide actionable insights based on the company's financial health.
Financial Analysis of 五粮液 (000858.SZ) in the 白酒 Industry:
Introduction:
五粮液 (Wuliangye Yibin Co., Ltd.), a leading player in the 白酒 industry, headquartered in 四川, has demonstrated a strong financial performance in recent times. This analysis aims to delve deeper into the company’s financial health, focusing on key metrics such as Earnings Per Share (EPS), Return on Equity (ROE), Gross Margin, and Net Profit Margin.
Key Financial Indicators:
Analysis and Insights:
Trends in Profitability:
Actionable Insights:
Conclusion:
The financial analysis of 五粮液 (000858.SZ) reveals a strong and profitable company with a sustainable competitive advantage in the 白酒 industry. With its high ROE, gross margin, and net profit margin, the company presents an attractive investment opportunity for investors. However, it is essential to continue monitoring the company’s performance and identifying areas for improvement to ensure sustained growth.
Prepare a stock report for 五粮液 (000858.SZ), summarizing:
- Earnings: EPS (7.783), ROE (24.8051%)
- Profitability: Net Profit Margin (37.8528%), Gross Margin (75.7936%)
- Risk: Debt-to-Assets Ratio (19.9982%)
Include actionable recommendations and use markdown format for clarity.
五粮液 (Wuliangye Yibin Co., Ltd.), a leading player in the 白酒 industry, has demonstrated a strong financial performance in recent times.
The company’s EPS of 7.783 indicates a strong earnings generation capacity. This, combined with a high ROE of 24.8051%, suggests that 五粮液 is efficiently utilizing its shareholder equity to generate profits.
The gross margin of 75.7936% is exceptionally high, implying that the company has a strong pricing power and operates with a high level of efficiency in its cost structure.
The net profit margin of 37.8528% is impressive, indicating that 五粮液 is able to convert a significant portion of its revenue into profits.
The debt-to-assets ratio of 19.9982% suggests that the company has a manageable level of debt, which is not a significant concern.
Based on the company’s strong financial performance, 五粮液 (000858.SZ) presents a compelling investment opportunity for investors seeking exposure to the 白酒 industry.
The company’s high gross margin and net profit margin suggest that it has a sustainable competitive advantage, which can be leveraged to drive future growth.
Despite the high gross margin, there is still room for improvement in the company’s cost structure. Identifying areas for cost optimization could further enhance profitability.
The financial analysis of 五粮液 (000858.SZ) reveals a strong and profitable company with a sustainable competitive advantage in the 白酒 industry. With its high ROE, gross margin, and net profit margin, the company presents an attractive investment opportunity for investors. However, it is essential to continue monitoring the company’s performance and identifying areas for improvement to ensure sustained growth.
Translate the stock report for 五粮液 (000858.SZ) into simplified Chinese.
五粮液 (Wuliangye Yibin Co., Ltd.) 是白酒行业的领军企业,最近表明了强劲的财务表现。
公司的每股收益 7.783 表明了强劲的盈利能力。结合高股东权益回报率 24.8051%,表明五粮液能够高效地利用股东权益来创造利润。
毛利率 75.7936% 令人印象深刻,表明公司拥有强劲的定价能力和高效的成本结构。
净利润率 37.8528% 令人印象深刻,表明五粮液能够将大量收入转化为利润。
资产负债率 19.9982% 表明公司的债务水平是可管理的,不是主要关注点。
基于公司强劲的財务表现,五粮液 (000858.SZ) 对寻求白酒行业 exposure 的投资者来说是一个具有吸引力的投资机会。
公司的高毛利率和净利润率表明它拥有可持续的竞争优势,这可以被用来推动未来的增长。
尽管毛利率很高,但是在公司的成本结构中仍然有改进的空间。确定成本优化的领域能够进一步提高profitability。
五粮液 (000858.SZ) 的财务分析表明了 strong 和profitable 公司拥有白酒行业的可持续竞争优势。凭借其高股东权益回报率、毛利率和净利润率,公司对投资者来说是一个具有吸引力的投资机会。然而,继续监控公司的表现并确定改进的领域是确保可持续增长的关键。
五粮液 (Wuliangye Yibin Co., Ltd.) 是白酒行业的领军企业,最近表明了强劲的财务表现。
公司的每股收益 7.783 表明了强劲的盈利能力。结合高股东权益回报率 24.8051%,表明五粮液能够高效地利用股东权益来创造利润。
毛利率 75.7936% 令人印象深刻,表明公司拥有强劲的定价能力和高效的成本结构。
净利润率 37.8528% 令人印象深刻,表明五粮液能够将大量收入转化为利润。
资产负债率 19.9982% 表明公司的债务水平是可管理的,不是主要关注点。
基于公司强劲的財务表现,五粮液 (000858.SZ) 对寻求白酒行业 exposure 的投资者来说是一个具有吸引力的投资机会。
公司的高毛利率和净利润率表明它拥有可持续的竞争优势,这可以被用来推动未来的增长。
尽管毛利率很高,但是在公司的成本结构中仍然有改进的空间。确定成本优化的领域能够进一步提高profitability。
五粮液 (000858.SZ) 的财务分析表明了 strong 和profitable 公司拥有白酒行业的可持续竞争优势。凭借其高股东权益回报率、毛利率和净利润率,公司对投资者来说是一个具有吸引力的投资机会。然而,继续监控公司的表现并确定改进的领域是确保可持续增长的关键。
研报的说服力,深度,专业度,完全取决于LLM(Large Language Model,大语言模型)的选择,现在大语言模型已经井喷式出现,但是性能却天差地别。本文使用的LLM是llama3-70b-8192,综合来讲,这不是目前最高级先进的大语言模型,且离第一梯队的LLM还相差甚远,这只是一个在本实验中临时使用的LLM。
大语言模型之间的性能差距是数量级的,同样的数据利用不同的LLM会得到完全不同的结果,对应的深度,精确度的差异会非常巨大。这份研报显而易见是一份过分简单的研报 甚至仅用单个Agent也可获得近似的结果。使用目前较为先进的AI模型,让每个Agent拥有更准确专精的角色定义,这样会得到更加准确可靠的投资建议。
OpenAI 的API的地区政策是一大难题,不符合地区政策的API部署会被封禁账号,这是目前最大的难题。在未来,接入更新,更强大的LLM是提升报告水平的关键路径。
这份报告只是一个基于过去时间的基本面评估,用以了解一个公司尚有帮助,但离提供投资建议还相差甚远。利用AI进行数据分析是发挥AI优势的一条思路。
所以,我们必须不能局限于基本面分析,要发挥AI优势,在未来对股票的技术面进行分析。
CrewAI 库中还有一个Tool 函数在本文尚未使用,这是因为目前的实验目标(生成一篇基于基本面信息的研报)尚不需要Tool函数。
在未来,如前文所述,如果要进行技术面分析,甚至在满足法律和政策要求的前提下,进行情绪面、消息面分析(利用爬虫)时,我们会使用Tool函数。
利用LLM不可避免的遇到一些“网络问题”,拥有良好的通道可以让实验完成地非常通畅。
在Task和Agent函数将描述写得更加详尽会获得更好的效果,但是一般LLM对单位时长内的API调用都有限制,最好的解决方式是充值会员。