当前位置: 首页 > 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.dtcms.com/a/281902.html

相关文章:

  • Capture One24下载与保姆级安装教程!
  • 解决“Windows 无法启动服务”问题指南
  • 数据库询问RAG框架Vanna的总体架构
  • 线上崩溃复盘
  • Unity Android Logcat插件 输出日志中文乱码解决
  • FPGA基础 -- Verilog 访问寄存器数组的指定位示例
  • 第六章 OBProxy 路由与使用运维
  • [Linux入门] Linux 账号和权限管理入门:从基础到实践
  • Linux实现进程之间Socket通信详解
  • 30 天自制 C++ 服务器--Day3
  • NO.6数据结构树|二叉树|满二叉树|完全二叉树|顺序存储|链式存储|先序|中序|后序|层序遍历
  • 【SpringBoot】实战-开发接口-用户-注册
  • 参数检验?非参数检验?
  • 【openbmc3】时间相关
  • 代码随想录算法训练营第五十一天|图论part2
  • 【FreeRTOS】03任务管理
  • 工业相机GigE数据接口的优势及应用
  • django安装、跨域、缓存、令牌、路由、中间件等配置
  • Jenkins全方位CI/CD实战指南
  • LabVIEW Occurrence功能
  • 嵌入式Linux(RV1126)系统定制中的编译与引导问题调试报告
  • 【RTSP从零实践】12、TCP传输H264格式RTP包(RTP_over_TCP)的RTSP服务器(附带源码)
  • 基于WebRTC技术实现一个在线课堂系统
  • el-input 回显怎么用符号¥和变量拼接展示?
  • Spring Boot 解决跨域问题
  • Spring Boot - Spring Boot 集成 MyBatis 分页实现 手写 SQL 分页
  • 日语学习-日语知识点小记-构建基础-JLPT-N3阶段(5):语法+单词
  • Buffer Pool
  • css 如何实现大屏4个占位 中屏2个 小屏幕1个
  • Samba服务器