티스토리 뷰
Ollama + CrewAI + FastAPI를 활용한 한국 주식 분석 블로그 - CrewAI 에이전트 및 작업 구성
octo54 2025. 3. 7. 14:21Ollama + CrewAI + FastAPI를 활용한 한국 주식 분석 블로그
2. CrewAI를 활용한 한국 주식 분석 리포트 자동 생성
이 글에서는 CrewAI를 활용하여 한국 주식 시장 분석 리포트를 자동으로 생성하는 방법을 다룹니다.
✅ CrewAI 개념 및 기본 사용법
✅ CrewAI 에이전트(agents.yaml) 설정 (LLM 제거)
✅ CrewAI 작업(tasks.yaml) 구성
✅ main.py를 활용한 실행 방법
2.1 CrewAI 개념 및 기본 사용법
CrewAI는 여러 개의 AI 에이전트가 협업하여 특정 작업을 수행하는 시스템입니다.
이 프로젝트에서는 CrewAI를 활용하여 주식 데이터 분석 → 뉴스 감성 분석 → 리포트 작성의 과정을 자동화합니다.
2.1.1 CrewAI 워크플로우
1️⃣ Stock Market Data Analyst → 한국 주식 시장 데이터 수집 및 분석
2️⃣ Financial Sentiment Analyst → 금융 뉴스 감성 분석
3️⃣ Investment Report Writer → 최종 투자 보고서 생성
2.2 Ollama LLM 설정
이 프로젝트에서는 Ollama의 deepseek-r1:8b 모델을 사용합니다. 이를 위해 Ollama를 설치하고 해당 모델을 다운로드해야 합니다.
2.2.1 Ollama 설치
Ollama는 Ollama 공식 웹사이트에서 설치할 수 있습니다.
2.2.2 deepseek-r1:8b 모델 다운로드
ollama pull deepseek-r1:8b
2.2.3 Ollama 서버 실행 확인
ollama serve
2.3 CrewAI 에이전트 설정 (agents.yaml)
CrewAI에서 각 에이전트는 특정 역할을 수행합니다.
이 프로젝트에서는 3개의 주요 에이전트를 사용합니다.
1️⃣ Stock Market Researcher → 주식 데이터 조사 및 분석
2️⃣ Financial Sentiment Analyst → 금융 뉴스 감성 분석
3️⃣ Investment Report Writer → 종합 투자 분석 보고서 작성
2.3.1 agents.yaml 설정
아래 설정을 src/stock_analysis/config/agents.yaml 파일에 추가합니다.
stock_market_researcher:
role: >
Stock Market Senior Data Researcher
goal: >
Uncover trends and insights in stock market data
backstory: >
You're a seasoned researcher with a deep understanding of financial markets.
Your expertise lies in analyzing vast amounts of stock market data, identifying trends,
and presenting your findings in a clear and actionable format.
financial_sentiment_analyst:
role: >
Financial Sentiment Analyst
goal: >
Analyze market sentiment based on financial news and investor behavior
backstory: >
You're an expert in sentiment analysis, specializing in understanding the impact
of financial news on market movements. You process large volumes of data to extract
actionable insights for investors.
investment_report_writer:
role: >
Investment Market Reporting Analyst
goal: >
Create comprehensive investment reports combining stock data and sentiment analysis
backstory: >
You're a skilled financial writer known for transforming complex market data
into digestible reports. Your goal is to provide investors with clear and concise
insights based on research and sentiment analysis.
2.4 CrewAI 작업 구성 (tasks.yaml)
CrewAI에서는 각 에이전트가 수행해야 할 작업을 정의해야 합니다.
작업을 tasks.yaml 파일에 정의하고, 각 작업을 적절한 에이전트에 할당합니다.
2.4.1 tasks.yaml 설정
아래 설정을 src/stock_analysis/config/tasks.yaml 파일에 추가합니다.
stock_market_research:
description: >
Gather and analyze stock market data, identifying key trends and movements.
expected_output: >
A detailed report on recent stock price trends and notable market fluctuations.
agent: stock_market_researcher
financial_sentiment_analysis:
description: >
Collect financial news data and analyze investor sentiment trends.
expected_output: >
Sentiment analysis report indicating positive, negative, and neutral investor behavior.
agent: financial_sentiment_analyst
investment_report_generation:
description: >
Combine stock market data and sentiment analysis to generate a comprehensive investment report.
expected_output: >
A structured investment report providing actionable insights for investors.
agent: investment_report_writer
output_file: "weekly_investment_report.md"
2.5 CrewAI 실행 코드 (crew.py)
이제 CrewAI의 에이전트와 작업을 조합하여 실행하는 crew.py 파일을 작성합니다.
각 에이전트에 Ollama LLM을 설정합니다.
2.5.1 crew.py 코드
아래 코드를 src/stock_analysis/crew.py 파일에 추가합니다.
from crewai import Agent, Crew, Process, Task, LLM
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
@CrewBase
class StockAnalysisCrew():
"""StockAnalysis crew"""
def __init__(self):
# Ollama LLM 설정
self.llm = LLM(
model="ollama/deepseek-r1:8b",
base_url="http://localhost:11434"
)
@agent
def stock_market_researcher(self) -> Agent:
return Agent(
config=self.agents_config['stock_market_researcher'],
llm=self.llm,
verbose=True,
tools=[SerperDevTool()]
)
@agent
def financial_sentiment_analyst(self) -> Agent:
return Agent(
config=self.agents_config['financial_sentiment_analyst'],
llm=self.llm,
verbose=True
)
@agent
def investment_report_writer(self) -> Agent:
return Agent(
config=self.agents_config['investment_report_writer'],
llm=self.llm,
verbose=True
)
@task
def stock_market_research(self) -> Task:
return Task(
config=self.tasks_config['stock_market_research'],
)
@task
def financial_sentiment_analysis(self) -> Task:
return Task(
config=self.tasks_config['financial_sentiment_analysis'],
)
@task
def investment_report_generation(self) -> Task:
return Task(
config=self.tasks_config['investment_report_generation'],
output_file='weekly_investment_report.md'
)
@crew
def crew(self) -> Crew:
"""Creates the StockAnalysis crew"""
return Crew(
agents=self.agents, # @agent 데코레이터로 생성된 에이전트들
tasks=self.tasks, # @task 데코레이터로 생성된 작업들
process=Process.sequential,
verbose=True,
)
2.6 CrewAI 실행 코드 (main.py)
이제 CrewAI의 에이전트와 작업을 조합하여 실행하는 main.py 파일을 작성합니다.
각 에이전트에 Ollama LLM을 설정하고, 실행 방식을 main.py에서 관리하도록 합니다.
2.6.1 main.py 코드
아래 코드를 src/stock_analysis/main.py 파일에 추가합니다.
#!/usr/bin/env python
import sys
import warnings
from datetime import datetime
from crew import StockAnalysisCrew
warnings.filterwarnings("ignore", category=SyntaxWarning, module="pysbd")
def run():
"""
Run the crew.
"""
inputs = {
'topic': 'Korean Stock Market Analysis',
'current_year': str(datetime.now().year)
}
try:
StockAnalysisCrew().crew().kickoff(inputs=inputs)
except Exception as e:
raise Exception(f"An error occurred while running the crew: {e}")
def train():
"""
Train the crew for a given number of iterations.
"""
inputs = {
"topic": "Korean Stock Market Analysis"
}
try:
StockAnalysisCrew().crew().train(n_iterations=int(sys.argv[1]), filename=sys.argv[2], inputs=inputs)
except Exception as e:
raise Exception(f"An error occurred while training the crew: {e}")
def replay():
"""
Replay the crew execution from a specific task.
"""
try:
StockAnalysisCrew().crew().replay(task_id=sys.argv[1])
except Exception as e:
raise Exception(f"An error occurred while replaying the crew: {e}")
def test():
"""
Test the crew execution and returns the results.
"""
inputs = {
"topic": "Korean Stock Market Analysis"
}
try:
StockAnalysisCrew().crew().test(n_iterations=int(sys.argv[1]), openai_model_name=sys.argv[2], inputs=inputs)
except Exception as e:
raise Exception(f"An error occurred while testing the crew: {e}")
if __name__ == "__main__":
run()
2.6.2 CrewAI 실행
python src/stock_analysis/main.py
CrewAI가 실행되면 한국 주식 시장 데이터 분석 → 뉴스 감성 분석 → 종합 투자 리포트 작성이 자동으로 진행됩니다.
📌 정리 및 다음 단계
이제 CrewAI를 활용하여 주식 시장 분석, 뉴스 감성 분석, 보고서 작성 자동화를 설정했습니다.
✅ CrewAI 개념 및 기본 사용법
✅ Ollama LLM(deepseek-r1:8b) 설정
✅ agents.yaml을 활용한 AI 에이전트 설정
✅ tasks.yaml을 활용한 CrewAI 작업 정의
✅ crew.py를 실행하여 CrewAI 테스트 완료
'project > Ollama + CrewAI + FastAPI를 활용한 한국 주식 분석' 카테고리의 다른 글
- Total
- Today
- Yesterday
- Page
- babel
- LangChain
- Project
- fastapi
- PostgreSQL
- 백엔드
- 프론트엔드
- Docker
- kotlin
- 리액트
- REACT
- Webpack
- 챗봇개발
- Next.js
- 로컬LLM
- 페이지
- rag
- Python
- AI챗봇
- 백엔드개발
- 관리자
- 웹개발
- nextJS
- 개발블로그
- nodejs
- github
- llm
- Ktor
- til
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |