### Set Up Development Environment Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/README.md Guides on setting up the development environment for the project, including cloning the repository, creating and activating a virtual environment, and installing development dependencies. ```bash # 克隆项目 git clone cd crewai # 创建虚拟环境 python -m venv venv source venv/bin/activate # Linux/Mac venv\Scripts\activate # Windows # 安装开发依赖 pip install -r requirements-dev.txt ``` -------------------------------- ### Environment Variable Setup Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Shows how to set up environment variables for API keys required by the system. Create a `.env` file in the project root and add your OpenAI and Serper API keys. ```dotenv OPENAI_API_KEY=sk-your-openai-key-here SERPER_API_KEY=your-serper-key-here ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/FINAL_TEST_REPORT.md Installs project dependencies using pip. It reads the list of required packages from the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Setup Project Directory Structure Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CLAUDE.md This code snippet demonstrates the basic directory structure required for a CrewAI project, including 'src' for source files and 'config' for configuration files. ```bash mkdir src config ``` -------------------------------- ### Install CrewAI and Tools Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Installs the CrewAI framework and its associated tools using pip. This is a prerequisite for using CrewAI for agent-based system development. ```bash pip install crewai pip install 'crewai[tools]' ``` -------------------------------- ### Run Interactive Stock Analysis (Bash) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/FINAL_TEST_REPORT.md Starts an interactive mode for stock analysis via the command line. This allows for a more conversational analysis process. ```bash python main.py interactive ``` -------------------------------- ### Run Pytest Unit and Performance Tests Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/README.md Executes unit and performance tests using the pytest framework. Commands include running all tests, specific test files, and tests with verbose output. Requires pytest to be installed. ```bash # 运行所有测试 python -m pytest tests/ # 运行特定测试 python -m pytest tests/test_stock_analysis_system.py -v # 运行性能测试 python -m pytest tests/test_performance.py -v ``` -------------------------------- ### Run Web Application (Bash) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/FINAL_TEST_REPORT.md Launches the web interface for the stock analysis system. The application is accessible at http://localhost:5000. ```bash python src/web_app.py # 访问 http://localhost:5000 ``` -------------------------------- ### Analyze Stock using Python API (Python) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/FINAL_TEST_REPORT.md Demonstrates how to use the StockAnalysisSystem class programmatically. It initializes the system and calls the analyze_stock method. ```python from src.stock_analysis_system import StockAnalysisSystem system = StockAnalysisSystem() result = system.analyze_stock("苹果公司", "AAPL") ``` -------------------------------- ### Tool Configuration for Agents Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Illustrates how to configure specific tools for different agent roles within CrewAI. It defines tool lists for research, analysis, and writing agents, demonstrating the principle of assigning appropriate tools to enhance agent capabilities. ```python # 为不同角色配置合适的工具 research_tools = [SerperDevTool(), ScrapeWebsiteTool()] # Assuming SerperDevTool and ScrapeWebsiteTool are available analysis_tools = [FileReadTool(), CalculatorTool()] # Assuming FileReadTool and CalculatorTool are available writing_tools = [FileWriterTool()] # Assuming FileWriterTool is available ``` -------------------------------- ### 项目文件结构 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md 展示了股票分析系统的项目文件结构,包括源文件、配置文件、数据存储、报告、测试文件等。 ```directory stock_analysis_system/ ├── src/ │ ├── crews/ # 各种团队定义 │ │ ├── data_collection_crew.py │ │ ├── analysis_crew.py │ │ └── decision_crew.py │ ├── flows/ # 流程控制 │ │ ├── investment_flow.py │ │ └── analysis_flow.py │ ├── agents/ # Agent定义 │ ├── tasks/ # 任务定义 │ ├── tools/ # 自定义工具 │ └── utils/ # 工具函数 ├── config/ # 配置文件 │ ├── agents.yaml │ ├── tasks.yaml │ └── tools.yaml ├── data/ # 数据存储 ├── reports/ # 生成的报告 ├── tests/ # 测试文件 ├── requirements.txt ├── .env └── main.py ``` -------------------------------- ### 环境变量配置 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md 配置项目所需的环境变量,包括OpenAI API密钥、Serper API密钥和OpenAI模型名称。 ```python # .env OPENAI_API_KEY=your-openai-key SERPER_API_KEY=your-serper-key OPENAI_MODEL_NAME=gpt-4-turbo ``` -------------------------------- ### 配置环境变量 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/QWEN.md 设置项目运行所需的环境变量,包括OpenAI API Key、模型名称以及可选的Serper API Key和系统配置。 ```bash # OpenAI 配置 OPENAI_API_KEY=your-openai-api-key-here OPENAI_MODEL_NAME=gpt-4o # Serper API (可选,用于网络搜索) SERPER_API_KEY=your-serper-api-key-here # 系统配置 CACHE_TTL=3600 MAX_WORKERS=5 LOG_LEVEL=INFO ``` -------------------------------- ### 启动Web应用 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/QWEN.md 使用Flask启动Web应用程序,并通过本地地址访问。 ```bash # 启动Web应用 python src/web_app.py # 访问地址 http://localhost:5000 ``` -------------------------------- ### Run Batch Stock Analysis (Bash) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/FINAL_TEST_REPORT.md Initiates a batch analysis of stocks from the command line. This command is used for processing multiple stocks efficiently. ```bash python main.py batch ``` -------------------------------- ### 自定义工具开发示例 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/QWEN.md 在src/tools/目录下创建自定义工具类,继承BaseTool并实现_run方法。 ```python from src.tools.base_tool import BaseTool class CustomAnalysisTool(BaseTool): name: str = "Custom Analysis Tool" description: str = "自定义分析工具" def _run(self, input_data: str) -> str: # 实现自定义分析逻辑 result = self.custom_analysis(input_data) return result ``` -------------------------------- ### CrewAI Project Python Dependencies Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CLAUDE.md Lists the essential Python packages for a CrewAI project, including the core crewai library, tools integration, OpenAI API access, and environment variable management. ```text crewai crewai[tools] openai python-dotenv ``` -------------------------------- ### Enable Debugging and View Execution Process Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/README.md Enables debug logging by setting the LOG_LEVEL environment variable and demonstrates running the system with specific parameters. Also shows how to view detailed execution processes by running flow scripts directly. ```bash # 启用调试日志 export LOG_LEVEL=DEBUG python main.py single --company "苹果公司" --ticker "AAPL" # 查看详细执行过程 python src/flows/investment_flow.py ``` -------------------------------- ### Python项目依赖 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md 列出了股票分析系统所需的Python包及其版本要求,用于依赖管理。 ```python # requirements.txt crewai>=0.28.0 crewai-tools>=0.4.0 openai>=1.0.0 python-dotenv>=1.0.0 pandas>=2.0.0 numpy>=1.24.0 requests>=2.31.0 yfinance>=0.2.0 matplotlib>=3.7.0 seaborn>=0.12.0 ``` -------------------------------- ### Agent配置 - 数据收集团队 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md 定义了数据收集团队中各个Agent的角色、目标、背景故事和使用的工具。 ```yaml # agents.yaml market_researcher: role: 高级市场研究分析师 goal: 收集并分析{company}的最新市场数据和行业趋势 backstory: 拥有10年经验的市场分析师,擅长从海量信息中提取关键趋势 tools: [SerperDevTool, ScrapeWebsiteTool, NewsSearchTool] financial_data_expert: role: 财务数据专家 goal: 获取并分析{company}的财务报表和关键指标 backstory: 金融数据专家,精通财务数据分析和处理 tools: [YFinanceTool, FinancialDataTool] technical_analyst: role: 技术分析师 goal: 分析{company}的股价走势和技术指标 backstory: 资深技术分析师,精通各种技术分析方法 tools: [TechnicalAnalysisTool, ChartingTool] ``` -------------------------------- ### 智能投资流程定义 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md 使用CrewAI的Flows框架定义了一个智能投资流程,包含状态管理、事件监听和路由逻辑,以根据市场情况调整分析策略。 ```python # flows/investment_flow.py from crewai.flow.flow import Flow, listen, start, router from pydantic import BaseModel class AnalysisState(BaseModel): company: str = "" market_sentiment: str = "neutral" financial_score: float = 0.0 risk_level: str = "unknown" industry_position: str = "unknown" final_recommendation: str = "hold" class SmartInvestmentFlow(Flow[AnalysisState]): @start() def initialize_analysis(self): """初始化分析流程""" return self._get_company_input() @listen(initialize_analysis) def market_intelligence_gathering(self, company_data): """市场情报收集""" market_crew = self._create_market_intelligence_crew() result = market_crew.kickoff(inputs=company_data) # 更新状态 self.state.market_sentiment = self._analyze_sentiment(result) return result @router(market_intelligence_gathering) def determine_analysis_strategy(self): """根据市场情况决定分析策略""" if self.state.market_sentiment == "positive": return "comprehensive_analysis" elif self.state.market_sentiment == "negative": return "risk_focused_analysis" return "standard_analysis" @listen("comprehensive_analysis") def deep_dive_analysis(self): """深度分析""" comprehensive_crew = self._create_comprehensive_crew() return comprehensive_crew.kickoff() @listen("risk_focused_analysis") def risk_oriented_analysis(self): """风险导向分析""" risk_crew = self._create_risk_focused_crew() return risk_crew.kickoff() @listen("standard_analysis") def balanced_analysis(self): """平衡分析""" standard_crew = self._create_standard_crew() return standard_crew.kickoff() ``` -------------------------------- ### Agent配置 - 决策团队 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md 定义了决策团队中各个Agent的角色、目标、背景故事和使用的工具。 ```yaml # agents.yaml (续) investment_advisor: role: 投资策略顾问 goal: 基于综合分析结果制定投资建议 backstory: 经验丰富的投资顾问,注重风险收益平衡 tools: [] report_generator: role: 报告生成器 goal: 生成标准化的投资分析报告 backstory: 专业报告撰写专家,确保报告质量和一致性 tools: [ReportWritingTool] quality_monitor: role: 质量监控员 goal: 确保分析质量和结果一致性 backstory: 质量控制专家,严格把控分析质量 tools: [] ``` -------------------------------- ### Agent配置 - 分析团队 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md 定义了分析团队中各个Agent的角色、目标、背景故事和使用的工具。 ```yaml # agents.yaml (续) fundamental_analyst: role: 基本面分析师 goal: 评估{company}的基本面价值和投资潜力 backstory: 基本面分析专家,擅长公司价值评估 tools: [FundamentalAnalysisTool] risk_assessor: role: 风险评估师 goal: 识别并评估{company}的投资风险 backstory: 风险管理专家,全面识别各类投资风险 tools: [RiskAssessmentTool] industry_expert: role: 行业专家 goal: 分析{company}在行业中的地位和竞争优势 backstory: 行业分析专家,深入理解行业动态和竞争格局 tools: [IndustryAnalysisTool] ``` -------------------------------- ### 运行系统测试 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/QWEN.md 使用Python命令运行系统测试脚本或使用pytest框架运行所有单元测试或特定测试文件。 ```bash # 运行系统测试 python test_final_system.py # 运行所有单元测试 python -m pytest tests/ # 运行特定测试 python -m pytest tests/test_stock_analysis_system.py -v ``` -------------------------------- ### Python编程接口示例 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/QWEN.md 通过Python编程接口实例化StockAnalysisSystem,并调用analyze_stock方法进行单股票分析。 ```python from src.stock_analysis_system import StockAnalysisSystem # 创建系统实例 system = StockAnalysisSystem() # 分析单只股票 result = system.analyze_stock("贵州茅台", "600519") if result['success']: print(f"投资评级: {result['investment_rating']['rating']}") print(f"综合评分: {result['overall_score']:.1f}/100") print(f"报告路径: {result['report_path']}") ``` -------------------------------- ### Implement Stock Analysis Crew Logic (Python) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Python code defining a 'StockAnalysisCrew' using CrewAI's decorators. It sets up agents with specific roles, goals, backstories, and tools (SerperDevTool, ScrapeWebsiteTool). It also defines sequential tasks for market research, financial analysis, and investment recommendations, culminating in a Crew object. ```python from crewai import Agent, Crew, Process, Task from crewai.project import CrewBase, agent, crew, task from crewai_tools import SerperDevTool, ScrapeWebsiteTool from typing import List @CrewBase class StockAnalysisCrew(): """股票分析团队""" @agent def market_researcher(self) -> Agent: return Agent( config=self.agents_config['market_researcher'], verbose=True, tools=[SerperDevTool(), ScrapeWebsiteTool()] ) @agent def financial_analyst(self) -> Agent: return Agent( config=self.agents_config['financial_analyst'], verbose=True, tools=[SerperDevTool()] ) @agent def investment_advisor(self) -> Agent: return Agent( config=self.agents_config['investment_advisor'], verbose=True ) @task def research_task(self) -> Task: return Task( config=self.tasks_config['research_task'], ) @task def financial_analysis_task(self) -> Task: return Task( config=self.tasks_config['financial_analysis_task'], ) @task def investment_recommendation_task(self) -> Task: return Task( config=self.tasks_config['investment_recommendation_task'], output_file='investment_report.md' ) @crew def crew(self) -> Crew: return Crew( agents=self.agents, tasks=self.tasks, process=Process.sequential, verbose=True, ) ``` -------------------------------- ### 命令行界面使用示例 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/SYSTEM_VALIDATION_REPORT.md 展示了如何通过命令行界面执行股票分析系统的不同功能,包括单股票分析、批量分析、交互式流程和批量分析流程。 ```bash # 单股票分析 python main.py single --company "苹果公司" --ticker "AAPL" # 批量分析 python main.py batch # 交互式流程 python main.py interactive # 批量分析流程 python main.py batch-flow ``` -------------------------------- ### Basic Stock Analysis with CrewAI Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Demonstrates how to perform a basic stock analysis using CrewAI by defining a company name and initiating the analysis crew. It prints a completion message and returns the analysis result. Requires the 'stock_analysis' module. ```python from stock_analysis.crew import StockAnalysisCrew def analyze_stock(company_name): """执行股票分析""" inputs = { 'company': company_name } result = StockAnalysisCrew().crew().kickoff(inputs=inputs) print(f"\n分析完成!详细报告已保存到 investment_report.md") return result if __name__ == "__main__": # 分析具体公司 company = input("请输入要分析的公司名称: ") analyze_stock(company) ``` -------------------------------- ### Run Single Stock Analysis (Bash) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/FINAL_TEST_REPORT.md Executes a single stock analysis using the provided company name and ticker symbol. This is a command-line interface command. ```bash python main.py single --company "苹果公司" --ticker "AAPL" ``` -------------------------------- ### 命令行股票分析 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/QWEN.md 使用命令行界面执行单股票分析、批量分析、交互式流程、批量分析流程或查看系统信息。 ```bash # 单股票分析 python main.py single --company "贵州茅台" --ticker "600519" # 批量分析 python main.py batch # 交互式流程 python main.py interactive # 批量分析流程 python main.py batch-flow # 查看系统信息 python main.py info ``` -------------------------------- ### Configure Custom Analysis Tool Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/README.md Defines a custom analysis tool within the configuration file, specifying its name, description, module, and class for custom analysis logic. ```yaml custom_analysis_tool: name: "自定义分析工具" description: "执行自定义分析逻辑" module: "src.tools.custom_tools" class: "CustomAnalysisTool" ``` -------------------------------- ### Define Stock Analysis Tasks (YAML) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Configuration for the tasks within the stock analysis system in YAML format. Each task includes a description, expected output, and the agent responsible for executing it. The final task also specifies an output file. ```yaml research_task: description: > 对{company}进行全面的市场研究,包括: 1. 最近3个月的股价走势 2. 行业竞争态势 3. 市场新闻和重大事件 4. 分析师观点汇总 expected_output: > 详细的市场研究报告,包含数据来源和关键发现 agent: market_researcher financial_analysis_task: description: > 分析{company}的财务健康状况: 1. 最新季度财报关键指标 2. 营收和利润趋势分析 3. 负债比率和现金流状况 4. 与同行业公司对比 expected_output: > 完整的财务分析报告,包含风险提示 agent: financial_analyst investment_recommendation_task: description: > 基于市场研究和分析分析,制定投资建议: 1. 综合评估投资价值 2. 识别主要风险因素 3. 确定合理的价格区间 4. 给出具体的投资策略 expected_output: > 完整的投资建议报告,包含明确的买入/卖出/持有建议 agent: investment_advisor output_file: investment_report.md ``` -------------------------------- ### 安装依赖和 AkShare Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/QWEN.md 安装项目所需的Python依赖包,并可选择性安装AkShare用于A股数据获取。 ```bash # 安装依赖 pip install -r requirements.txt # 安装 AkShare (可选,用于 A 股数据) pip install akshare ``` -------------------------------- ### Advanced Stock Analysis Flow with CrewAI Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Implements an advanced stock analysis flow using CrewAI's Flows for more precise control over complex business processes. It defines states, manages transitions between analysis stages (market analysis, financial analysis), and allows for dynamic routing based on conditions. Requires 'crewai' and 'pydantic'. ```python from crewai.flow.flow import Flow, listen, start, router from pydantic import BaseModel class AnalysisState(BaseModel): company: str = "" market_sentiment: str = "neutral" financial_score: float = 0.0 risk_level: str = "unknown" recommendations: list = [] class SmartInvestmentFlow(Flow[AnalysisState]): @start() def initialize_analysis(self): """初始化分析流程""" company = input("请输入公司名称: ") self.state.company = company return {"target": company} @listen(initialize_analysis) def market_analysis(self, company_data): """市场分析阶段""" # 调用市场研究团队 market_crew = self._create_market_crew() result = market_crew.kickoff(inputs=company_data) # 更新状态 self.state.market_sentiment = "positive" # 根据实际结果更新 return result @router(market_analysis) def determine_analysis_depth(self): """根据市场情况决定分析深度""" if self.state.market_sentiment == "positive": return "deep_analysis" elif self.state.market_sentiment == "neutral": return "standard_analysis" return "risk_analysis" @listen("deep_analysis") def comprehensive_financial_analysis(self): """全面财务分析""" financial_crew = self._create_financial_crew() return financial_crew.kickoff() @listen("standard_analysis") def basic_financial_check(self): """基础财务检查""" # 简化的分析流程 return {"status": "basic_check_complete"} def _create_market_crew(self): # 创建市场分析团队的具体实现 pass def _create_financial_crew(self): # 创建财务分析团队的具体实现 pass ``` -------------------------------- ### Python编程接口示例 Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/SYSTEM_VALIDATION_REPORT.md 演示了如何通过Python编程接口使用股票分析系统,包括实例化系统并调用股票分析方法。 ```python from src.stock_analysis_system import StockAnalysisSystem system = StockAnalysisSystem() result = system.analyze_stock("苹果公司", "AAPL") ``` -------------------------------- ### Run System Integration and Single Function Tests Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/README.md Executes system integration tests and tests specific functionalities of the stock analysis system. This includes running a general integration test script and a command-line interface for analyzing a single company's data. ```bash # 运行系统集成测试 python test_final_system.py # 测试特定功能 python main.py single --company "测试公司" --ticker "TEST" ``` -------------------------------- ### Define Stock Analysis Agents (YAML) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Configuration for three agents (market_researcher, financial_analyst, investment_advisor) in YAML format. Each agent has a role, goal, and backstory, defining their expertise and purpose within the stock analysis system. ```yaml market_researcher: role: > 高级市场研究分析师 goal: > 收集并分析{company}的最新市场数据和行业趋势 backstory: > 你是一位拥有10年经验的资深市场分析师,擅长从海量信息中 提取关键趋势和数据,为投资决策提供可靠的基础数据支持。 financial_analyst: role: > 专业财务分析师 goal: > 深入分析{company}的财务状况和盈利能力 backstory: > 你是金融领域的专家,能够透过复杂的财务数据看到公司的 真实经营状况,擅长识别财务风险和增长机会。 investment_advisor: role: > 投资策略顾问 goal: > 基于研究和分析结果,为{company}提供具体的投资建议 backstory: > 你是经验丰富的投资顾问,善于综合各种信息做出平衡的 投资决策,注重风险控制和长期价值创造。 ``` -------------------------------- ### Optimized Crew Executor with Caching Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md An OptimizedCrewExecutor class that uses the 'performance_monitor' decorator and implements a caching mechanism to speed up crew execution. It stores results based on crew name and inputs. ```python class OptimizedCrewExecutor: """优化的团队执行器""" def __init__(self): self.cache = {} self.execution_history = [] @performance_monitor async def execute_crew_with_cache(self, crew_name, inputs): """带缓存的团队执行""" cache_key = self._generate_cache_key(crew_name, inputs) if cache_key in self.cache: cached_result = self.cache[cache_key] if self._is_cache_valid(cached_result): return cached_result['data'] # 执行团队 result = await self._execute_crew(crew_name, inputs) # 缓存结果 self.cache[cache_key] = { 'data': result, 'timestamp': time.time() } return result ``` -------------------------------- ### Unit Tests for Data Collection Crew Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md Provides unit tests for the DataCollectionCrew, specifically testing the market research and financial data tasks. It utilizes unittest and mock to simulate tool behavior. ```python # tests/test_crews.py import unittest from unittest.mock import Mock, patch from src.crews.data_collection_crew import DataCollectionCrew class TestDataCollectionCrew(unittest.TestCase): def setUp(self): self.crew = DataCollectionCrew() @patch('src.crews.data_collection_crew.SerperDevTool') def test_market_research_task(self, mock_tool): """测试市场研究任务""" mock_tool._run.return_value = "Mock search results" result = self.crew.market_research_task("AAPL") self.assertIn("market_data", result) @patch('src.crews.data_collection_crew.YFinanceTool') def test_financial_data_task(self, mock_tool): """测试财务数据任务""" mock_tool._run.return_value = "Mock financial data" result = self.crew.financial_data_task("AAPL") self.assertIn("financial_metrics", result) ``` -------------------------------- ### Robust Crew Execution with Retries Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Implements a robust execution mechanism for CrewAI tasks with a retry strategy. It attempts to execute a crew's kickoff method multiple times, handling exceptions and logging failures. This is crucial for production environments to ensure task completion. ```python def robust_crew_execution(crew, inputs, max_retries=3): """带重试机制的可靠执行""" for attempt in range(max_retries): try: result = crew.kickoff(inputs=inputs) return result except Exception as e: print(f"第{attempt + 1}次执行失败: {e}") if attempt == max_retries - 1: raise e # 可以在这里添加错误恢复逻辑 ``` -------------------------------- ### Performance Monitoring Decorator Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md A Python decorator 'performance_monitor' to measure and print the execution time of asynchronous functions. It helps in optimizing performance by identifying slow operations. ```python # src/optimization.py import asyncio import time from functools import wraps def performance_monitor(func): """性能监控装饰器""" @wraps(func) async def wrapper(*args, **kwargs): start_time = time.time() result = await func(*args, **kwargs) end_time = time.time() execution_time = end_time - start_time print(f"{func.__name__} 执行时间: {execution_time:.2f}秒") return result return wrapper ``` -------------------------------- ### Task Execution Monitoring Callback Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/CrewAI_note.txt Adds a callback function to monitor task execution within CrewAI. The `monitored_task` function configures a task with a callback, and `task_callback` handles the output of each completed task, allowing for logging or performance monitoring. ```python from crewai import Task # Assuming 'self.tasks_config' and 'self.task_callback' are defined in a class context @task # Assuming @task is a decorator available in the context def monitored_task(self) -> Task: return Task( config=self.tasks_config['research_task'], callback=self.task_callback # 添加回调监控 ) def task_callback(self, task_output): """任务执行回调""" print(f"任务 {task_output.description} 执行完成") # 可以添加日志记录、性能监控等 ``` -------------------------------- ### Stock Analysis API Endpoint (FastAPI) Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md Defines a POST endpoint '/analyze' using FastAPI to receive stock analysis requests. It processes requests using a SmartInvestmentFlow and returns analysis results or errors. ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI() class AnalysisRequest(BaseModel): company: str ticker: str analysis_type: str = "standard" class AnalysisResponse(BaseModel): success: bool data: dict = None error: str = None @app.post("/analyze", response_model=AnalysisResponse) async def analyze_stock(request: AnalysisRequest): """分析单只股票""" try: flow = SmartInvestmentFlow() result = await flow.kickoff_async( company=request.company, ticker=request.ticker, analysis_type=request.analysis_type ) return AnalysisResponse(success=True, data=result) except Exception as e: return AnalysisResponse(success=False, error=str(e)) ``` -------------------------------- ### POST /analyze Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/股票分析系统开发计划.md Analyzes a single stock based on provided company, ticker, and analysis type. Returns the analysis results or an error message. ```APIDOC ## POST /analyze ### Description Analyzes a single stock, taking company name, ticker symbol, and an optional analysis type as input. Returns a success status, the analysis data, or an error message if the analysis fails. ### Method POST ### Endpoint /analyze ### Parameters #### Request Body - **company** (string) - Required - The name of the company. - **ticker** (string) - Required - The stock ticker symbol. - **analysis_type** (string) - Optional - The type of analysis to perform (defaults to "standard"). ### Request Example ```json { "company": "Apple Inc.", "ticker": "AAPL", "analysis_type": "financial_health" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the analysis was successful. - **data** (object) - Contains the analysis results if successful. - **error** (string) - Contains an error message if the analysis failed. #### Response Example ```json { "success": true, "data": { "key_financials": { "revenue": "383285000000", "gross_profit": "100778000000" }, "market_sentiment": "positive" }, "error": null } ``` #### Error Response (500) - **success** (boolean) - Always false in case of error. - **data** (object) - Null. - **error** (string) - A message describing the error. #### Error Response Example ```json { "success": false, "data": null, "error": "An unexpected error occurred during analysis." } ``` ``` -------------------------------- ### Add Price Alert Rule Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/README.md Adds a price alert rule to the monitoring system for a specific stock, triggering when the price crosses a defined threshold. Requires the stock ticker, metric type ('price'), comparison operator ('above' or 'below'), threshold value, and a descriptive message. ```python monitor.add_alert_rule( "price_breakout", "AAPL", "price", "above", 180.0, "苹果股价突破180美元" ) ``` -------------------------------- ### Add Technical Indicator Alert Rule Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/README.md Adds an alert rule based on a technical indicator's value for a given stock. It specifies the indicator name, stock ticker, metric type ('indicator'), comparison operator, threshold value, and a description of the alert condition. ```python monitor.add_alert_rule( "rsi_oversold", "AAPL", "indicator", "below", 30, "RSI指标低于30,超卖信号" ) ``` -------------------------------- ### Add Score Alert Rule Source: https://github.com/liangdabiao/crewai_stock_analysis_system/blob/main/README.md Adds an alert rule based on a stock's overall score. This rule is triggered when the score falls below a specified threshold, indicating a potential concern. It requires the stock ticker, metric type ('score'), comparison operator, threshold, and a descriptive message. ```python monitor.add_alert_rule( "score_drop", "AAPL", "score", "below", 60, "综合评分低于60分" ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.