펀더멘털 분석은 기업의 내재적 가치를 평가하는 투자 방법론으로, 재무제표와 경영 성과, 산업 환경 등을 종합적으로 고려합니다. 벤저민 그레이엄과 워렌 버핏을 비롯한 가치 투자자들이 애용하는 이 방법론이 코드로는 어떻게 구현되는지 살펴보겠습니다.
펀더멘털 분석 에이전트는 기업의 재무 지표를 분석하여 투자 신호(bullish, bearish, neutral)를 생성하는 AI 컴포넌트입니다. 이 에이전트는 수익성, 성장성, 재무 건전성, 그리고 밸류에이션 비율 등 네 가지 핵심 측면을 분석합니다.
def fundamentals_agent(state: AgentState):
"""Analyzes fundamental data and generates trading signals for multiple tickers."""
data = state["data"]
end_date = data["end_date"]
tickers = data["tickers"]
# Initialize fundamental analysis for each ticker
fundamental_analysis = {}
for ticker in tickers:
# 분석 로직...
이 함수는 각 주식 종목(ticker)에 대해 반복적으로 실행되며, 기업의 펀더멘털 데이터를 분석하고 투자 신호를 생성합니다.
첫 번째 단계는 기업의 재무 지표 데이터를 수집하는 것입니다:
# Get the financial metrics
financial_metrics = get_financial_metrics(
ticker=ticker,
end_date=end_date,
period="ttm", # trailing twelve months
limit=10,
)
if not financial_metrics:
progress.update_status("fundamentals_agent", ticker, "Failed: No financial metrics found")
continue
# Pull the most recent financial metrics
metrics = financial_metrics[0]
여기서 get_financial_metrics
함수는 외부 API를 호출하여 특정 종목의 재무 지표를 가져옵니다. period="ttm"
은 후행 12개월(Trailing Twelve Months) 데이터를 의미하며, 가장 최신의 연간 재무 성과를 반영합니다.
수익성은 기업이 얼마나 효율적으로 이익을 창출하는지를 평가합니다:
# 1. Profitability Analysis
return_on_equity = metrics.return_on_equity
net_margin = metrics.net_margin
operating_margin = metrics.operating_margin
thresholds = [
(return_on_equity, 0.15), # Strong ROE above 15%
(net_margin, 0.20), # Healthy profit margins
(operating_margin, 0.15), # Strong operating efficiency
]
profitability_score = sum(metric is not None and metric > threshold for metric, threshold in thresholds)
signals.append("bullish" if profitability_score >= 2 else "bearish" if profitability_score == 0 else "neutral")
여기서는 세 가지 핵심 지표를 분석합니다:
이 세 지표 중 두 개 이상이 기준치를 초과하면 '강세(bullish)'로, 모두 기준치 미만이면 '약세(bearish)'로, 그 사이는 '중립(neutral)'으로 신호를 생성합니다.
성장성은 기업이 시간이 지남에 따라 얼마나 확장되고 있는지를 평가합니다:
# 2. Growth Analysis
revenue_growth = metrics.revenue_growth
earnings_growth = metrics.earnings_growth
book_value_growth = metrics.book_value_growth
thresholds = [
(revenue_growth, 0.10), # 10% revenue growth
(earnings_growth, 0.10), # 10% earnings growth
(book_value_growth, 0.10), # 10% book value growth
]
growth_score = sum(metric is not None and metric > threshold for metric, threshold in thresholds)
signals.append("bullish" if growth_score >= 2 else "bearish" if growth_score == 0 else "neutral")
여기서는 다음 세 가지 성장 지표를 확인합니다:
마찬가지로, 두 개 이상의 지표가 기준치를 초과하면 '강세'로 판단합니다.
재무 건전성은 기업이 부채를 감당하고 단기 의무를 이행할 수 있는 능력을 평가합니다:
# 3. Financial Health
current_ratio = metrics.current_ratio
debt_to_equity = metrics.debt_to_equity
free_cash_flow_per_share = metrics.free_cash_flow_per_share
earnings_per_share = metrics.earnings_per_share
health_score = 0
if current_ratio and current_ratio > 1.5: # Strong liquidity
health_score += 1
if debt_to_equity and debt_to_equity < 0.5: # Conservative debt levels
health_score += 1
if free_cash_flow_per_share and earnings_per_share and free_cash_flow_per_share > earnings_per_share * 0.8: # Strong FCF conversion
health_score += 1
signals.append("bullish" if health_score >= 2 else "bearish" if health_score == 0 else "neutral")
재무 건전성 분석에서는 다음 세 가지 조건을 확인합니다:
밸류에이션 비율은 주식의 가격이 기업의 펀더멘털 가치에 비해 적절한지를 평가합니다:
# 4. Price to X ratios
pe_ratio = metrics.price_to_earnings_ratio
pb_ratio = metrics.price_to_book_ratio
ps_ratio = metrics.price_to_sales_ratio
thresholds = [
(pe_ratio, 25), # Reasonable P/E ratio
(pb_ratio, 3), # Reasonable P/B ratio
(ps_ratio, 5), # Reasonable P/S ratio
]
price_ratio_score = sum(metric is not None and metric > threshold for metric, threshold in thresholds)
signals.append("bullish" if price_ratio_score >= 2 else "bearish" if price_ratio_score == 0 else "neutral")
여기서는 세 가지 핵심 밸류에이션 지표를 확인합니다:
주의: 코드에서는 price_ratio_score
가 메트릭이 임계값보다 클 때 증가하도록 되어 있어 로직이 반대로 되어 있습니다. 실제로는 이 비율들이 낮을수록 더 저평가되어 있다고 봐야 하므로, 이 부분은 코드 수정이 필요해 보입니다!
네 가지 분석이 모두 완료되면, 종합적인 투자 신호와 신뢰도를 계산합니다:
# Determine overall signal
bullish_signals = signals.count("bullish")
bearish_signals = signals.count("bearish")
if bullish_signals > bearish_signals:
overall_signal = "bullish"
elif bearish_signals > bullish_signals:
overall_signal = "bearish"
else:
overall_signal = "neutral"
# Calculate confidence level
total_signals = len(signals)
confidence = round(max(bullish_signals, bearish_signals) / total_signals, 2) * 100
강세 신호가 약세 신호보다 많으면 종합적으로 '강세'로 판단하고, 그 반대의 경우 '약세'로, 동일한 경우 '중립'으로 판단합니다. 신뢰도는 가장 많은 신호(강세 또는 약세)의 비율로 계산됩니다.
분석이 완료되면 결과를 JSON 형식으로 반환하고 시스템에 저장합니다:
fundamental_analysis[ticker] = {
"signal": overall_signal,
"confidence": confidence,
"reasoning": reasoning,
}
# Create the fundamental analysis message
message = HumanMessage(
content=json.dumps(fundamental_analysis),
name="fundamentals_agent",
)
# Add the signal to the analyst_signals list
state["data"]["analyst_signals"]["fundamentals_agent"] = fundamental_analysis
이 펀더멘털 분석 에이전트는 다음과 같은 방향으로 개선될 수 있습니다:
펀더멘털 분석 에이전트는 투자 결정을 위한 강력한 도구이지만, 완벽한 것은 아닙니다. 더 종합적인 투자 분석을 위해서는 기술적 분석, 시장 심리 분석, 거시경제 분석 등 다른 측면과의 균형이 필요합니다.
AI 헤지펀드 시스템에서 이 에이전트는 벤 그레이엄, 빌 액크만, 워렌 버핏 등의 에이전트와 함께 작동하여 더 종합적인 투자 결정을 내리는 데 기여합니다.