当前位置: 首页 > news >正文

使用 CrewAI 进行股票分析:自动化投资决策的新途径

一、引言

在当今快节奏的金融市场中,及时、准确的股票分析对于投资者做出明智决策至关重要。然而,传统的股票分析方法往往耗时且依赖人工,难以满足市场快速变化的需求。CrewAI 框架的出现为股票分析带来了新的解决方案。本项目展示了如何利用 CrewAI 框架自动化股票分析过程,通过协调多个自主 AI 代理协作完成复杂任务,从而提高分析效率和准确性。

二、CrewAI 框架概述

CrewAI 旨在促进角色扮演 AI 代理之间的协作。在股票分析示例中,这些代理共同协作,提供全面的股票分析和投资建议。每个代理都有特定的角色和任务,通过相互配合,能够更高效地完成复杂的分析任务。

三、运行脚本步骤

(一)环境配置

由于脚本默认使用 GPT - 4,因此需要确保拥有访问权限。同时,需复制.env.example文件并设置相关环境变量,包括Browseless、Serper、SEC - API和 [OpenAI](https://platform.openai.com/api - keys) 的配置信息。

(二)安装依赖

运行poetry install --no - root命令来安装所需的依赖项。

(三)执行脚本

运行poetry run python3 main.py(注意要从包含main.py的目录执行)。执行脚本后,会提示输入要分析的公司名称,脚本将利用 CrewAI 框架对该公司进行分析并生成详细报告。

四、关键组件说明

(一)main.py

主脚本文件,负责启动股票分析流程。以下是部分关键代码示例:

python

运行

import sys
from crew import StockAnalysisCrewdef run():inputs = {'query': 'What is the company you want to analyze?','company_stock': 'AMZN',}return StockAnalysisCrew().crew().kickoff(inputs=inputs)if __name__ == "__main__":print("## Welcome to Stock Analysis Crew")print('-------------------------------')result = run()print("\n\n########################")print("## Here is the Report")print("########################\n")print(result)

(二)stock_analysis_tasks.py

包含任务提示的主文件,定义了各个分析任务的具体要求和预期输出。例如:

yaml

financial_analysis:description: >Conduct a thorough analysis of {company_stock}'s stock financial health and market performance. This includes examining key financial metrics such asP/E ratio, EPS growth, revenue trends, and debt - to - equity ratio. Also, analyze the stock's performance in comparison to its industry peers and overall market trends.expected_output: >The final report must expand on the summary provided but now including a clear assessment of the stock's financial standing, its strengths and weaknesses, and how it fares against its competitors in the current market scenario.Make sure to use the most recent data possible.

(三)stock_analysis_agents.py

主要用于创建各种分析代理,为每个代理分配特定的角色和工具。例如:

python

运行

from crewai import Agent
from tools.calculator_tool import CalculatorTool
from tools.sec_tools import SEC10KTool, SEC10QTool
from crewai_tools import WebsiteSearchTool, ScrapeWebsiteTooldef financial_agent():return Agent(config=self.agents_config['financial_analyst'],verbose=True,llm=llm,tools=[ScrapeWebsiteTool(),WebsiteSearchTool(),CalculatorTool(),SEC10QTool("AMZN"),SEC10KTool("AMZN"),])

(四)tools目录

包含代理使用的工具类,例如用于获取 SEC 文件内容的工具:

python

运行

import os
import requests
import re
import html2text
from sec_api import QueryApidef get_10q_url_content(self, stock_name: str) -> Optional[str]:try:queryApi = QueryApi(api_key=os.environ['SEC_API_API_KEY'])query = {"query": {"query_string": {"query": f"ticker:{stock_name} AND formType:\"10 - Q\""}},"from": "0","size": "1","sort": [{"filedAt": {"order": "desc"}}]}filings = queryApi.get_filings(query)['filings']if len(filings) == 0:print("No filings found for this stock.")return Noneurl = filings[0]['linkToFilingDetails']headers = {"User - Agent": "crewai.com bisan@crewai.com","Accept - Encoding": "gzip, deflate","Host": "www.sec.gov"}response = requests.get(url, headers=headers)response.raise_for_status()  # Raise an exception for HTTP errorsh = html2text.HTML2Text()h.ignore_links = Falsetext = h.handle(response.content.decode("utf - 8"))# Removing all non - English words, dollar signs, numbers, and newlines from texttext = re.sub(r"[^a-zA-Z$0-9\s\n]", "", text)return textexcept requests.exceptions.HTTPError as e:print(f"HTTP error occurred: {e}")return Noneexcept Exception as e:print(f"Error fetching 10 - Q URL: {e}")return None

五、使用不同模型

(一)使用 GPT 3.5

CrewAI 允许在代理构造函数中传递llm参数来指定使用的大语言模型。如果要使用 GPT - 3.5 代替 GPT - 4,只需在需要使用该模型的代理中传递相应的llm参数即可。示例代码如下:

python

运行

from langchain.chat_models import ChatOpenAIllm = ChatOpenAI(model='gpt - 3.5')  # Loading GPT - 3.5def local_expert(self):return Agent(role='The Best Financial Analyst',goal="""Impress all customers with your financial data and market trends analysis""",backstory="""The most seasoned financial analyst with lots of expertise in stock market analysis and investmentstrategies that is working for a super important customer.""",verbose=True,llm=llm,  # <----- passing our llm reference heretools=[BrowserTools.scrape_and_summarize_website,SearchTools.search_internet,CalculatorTools.calculate,SECTools.search_10q,SECTools.search_10k])

(二)使用本地模型(Ollama)

可以将 Ollama 与 CrewAI 集成,使用本地模型进行分析。在代码中可以看到如下配置:

python

运行

from langchain.llms import Ollama
llm = Ollama(model="llama3.1")

六、结论

通过使用 CrewAI 框架进行股票分析,投资者可以利用自动化的方式更高效地获取全面的股票分析报告和投资建议。该框架通过协调多个 AI 代理的协作,能够充分发挥各代理的优势,提高分析的准确性和效率。同时,支持使用不同的大语言模型,包括本地模型,为用户提供了更多的选择和灵活性。未来,随着技术的不断发展,CrewAI 框架有望在金融分析领域发挥更大的作用。

http://www.xdnf.cn/news/1132957.html

相关文章:

  • YAML 自动化用例中 GET vs POST 请求的参数写法差异
  • 剑指offer64_圆圈中最后剩下的数字
  • 分块(chunked) vs 滑动窗口(windowed)
  • 力扣面试150(31/150)
  • Python爬虫实战:研究PyYAML库相关技术
  • 工作第一步建立连接——ssh
  • STM32硬件I2C的注意事项
  • UniApp 多端人脸认证图片上传实现
  • Sketch 与 Figma
  • 基于 Python/PHP/Node.js 的淘宝 API 商品数据抓取开发教程
  • 个人笔记(linux/sort与uniq命令)
  • [硬件电路-28]:从简单到复杂:宇宙、芯片与虚拟世界的共通逻辑
  • 快速掌握 Kafka:从核心概念到生产级部署指南
  • 网络安全初级(XSS-labs 1-8)
  • 基于Canal实现MySQL数据库数据同步
  • 数字IC后端培训教程之数字后端项目典型项目案例解析
  • 端侧推理软件栈
  • 智慧农业新图景:物联网如何精准守护作物生长​
  • FCN语义分割笔记(1)
  • XSS-labs 1-8关
  • 系统性学习C语言-第十八讲-C语言内存函数
  • 从零开始的云计算生活——番外4,使用 Keepalived 实现 MySQL 高可用
  • xss-lab1-8关
  • AWS ML Specialist 考试备考指南
  • Liunx练习项目6-创建dns服务器
  • 图机器学习(10)——监督学习中的图神经网络
  • AI Agent开发学习系列 - langchain之LCEL(1):LangChain LCEL链式编排与RAG增强实践
  • 新手向:自动化图片格式转换工具
  • orfeotoolbox ResetMargin
  • 硬件设计学习DAY3——电源Buck电路深度解析:CCM/DCM/BCM模式与电感设计