AAPL의 재무 상태를 분석해줘.
state = {
"llm": ChatOpenAI(model="gpt-4"),
"messages": [
HumanMessage(content="AAPL의 재무 상태를 분석해줘.")
]
}
result = financial_analyzer_node._run(state)
# USFinancialAnalyzerNode._run 내부
if self.agent is None:
self.agent = create_react_agent(
llm=state["llm"],
tools=self.tools, # [USFinancialStatementTool()]
prompt=self.system_prompt
)
result = self.agent.invoke(state)
사용자 요청: "AAPL의 재무 상태를 분석해줘."
먼저 쿼리에서 티커 심볼을 식별해야 합니다. 여기서는 "AAPL"이 티커 심볼입니다.
AAPL은 Apple Inc.의 티커 심볼입니다.
재무 상태를 분석하기 위해 us_financial_statement_analyzer 도구를 사용해야 합니다.
Action: us_financial_statement_analyzer
Action Input: "AAPL의 재무 상태를 분석해줘."
# USFinancialStatementTool._run 호출
query = "AAPL의 재무 상태를 분석해줘."
ticker = self._extract_ticker(query) # "AAPL" 추출됨
result = self.api_wrapper.analyze_financial_statements(ticker)
formatted_result = self._format_financial_analysis(result)
# AlphaVantageAPIWrapper.analyze_financial_statements("AAPL") 호출
result = {
"ticker": "AAPL",
"timestamp": 1711842000.12345 # Unix 타임스탬프
}
# 회사 개요 데이터 가져오기
overview = self.get_company_overview("AAPL")
# Alpha Vantage API 호출: https://www.alphavantage.co/query?function=OVERVIEW&symbol=AAPL&apikey=YOUR_API_KEY
result["profile"] = overview
result["company_name"] = overview.get("Name", "") # "Apple Inc."
# 대차대조표 가져오기
balance_sheet = self.get_balance_sheet("AAPL")
# Alpha Vantage API 호출: https://www.alphavantage.co/query?function=BALANCE_SHEET&symbol=AAPL&apikey=YOUR_API_KEY
result["balance_sheet"] = balance_sheet
# 손익계산서 가져오기
income_statement = self.get_income_statement("AAPL")
# Alpha Vantage API 호출: https://www.alphavantage.co/query?function=INCOME_STATEMENT&symbol=AAPL&apikey=YOUR_API_KEY
result["income_statement"] = income_statement
# 현금흐름표 가져오기
cash_flow = self.get_cash_flow("AAPL")
# Alpha Vantage API 호출: https://www.alphavantage.co/query?function=CASH_FLOW&symbol=AAPL&apikey=YOUR_API_KEY
result["cash_flow"] = cash_flow
# 분석 데이터 추가
result["analysis"] = self._analyze_financial_data(result)
# _analyze_financial_data 내부 실행 과정
analysis = {}
# 회사 프로필 분석
profile = data.get("profile", {})
analysis["sector"] = profile["Sector"] # "Technology"
analysis["industry"] = profile["Industry"] # "Consumer Electronics"
analysis["market_cap"] = f"${float(profile['MarketCapitalization']):,.2f}" # "$2,876,543,210,987.00"
analysis["employees"] = f"{profile['FullTimeEmployees']}" # "164,000"
analysis["eps"] = f"${float(profile['EPS']):,.2f}" # "$6.14"
analysis["pe_ratio"] = f"{float(profile['PERatio']):,.2f}" # "32.42"
# ... 다른 프로필 데이터 분석
# 대차대조표 분석
balance_sheet_data = data.get("balance_sheet", {})
recent = balance_sheet_data["annualReports"][0]
total_assets = float(recent.get("totalAssets", 0)) # 352,583,000,000
total_liabilities = float(recent.get("totalLiabilities", 0)) # 290,407,000,000
total_equity = float(recent.get("totalShareholderEquity", 0)) # 62,176,000,000
analysis["total_assets"] = f"${total_assets:,.2f}"
analysis["total_liabilities"] = f"${total_liabilities:,.2f}"
analysis["total_equity"] = f"${total_equity:,.2f}"
# 유동성 분석
current_assets = float(recent.get("totalCurrentAssets", 0)) # 143,600,000,000
current_liabilities = float(recent.get("totalCurrentLiabilities", 0)) # 125,260,000,000
current_ratio = (current_assets / current_liabilities) # 1.15
analysis["current_ratio"] = f"{current_ratio:.2f}"
analysis["liquidity_evaluation"] = "Adequate liquidity" # current_ratio > 1 but < 1.5
# 부채 비율
debt_to_equity = (total_liabilities / total_equity) * 100 # 153.24%
analysis["debt_to_equity"] = f"{debt_to_equity:.2f}%"
analysis["debt_evaluation"] = "High debt (aggressive)" # debt_to_equity > 100 but < 200
# ... 손익계산서, 현금흐름표 분석, 추가 비율 계산 등
# _format_financial_analysis 내부 실행 과정
output = []
ticker = analysis_data.get("ticker", "Unknown") # "AAPL"
company_name = analysis_data.get("company_name", "") # "Apple Inc."
header = f"# Financial Statement Analysis for {company_name} (Ticker: {ticker})"
output.append(header)
# 회사 프로필 정보 포맷팅
output.append("\n## Company Profile")
output.append(f"- Sector: {profile['Sector']}")
output.append(f"- Industry: {profile['Industry']}")
output.append(f"- Description: {profile['Description'][:300]}...")
# ... 기타 프로필 정보 포맷팅
# 대차대조표 정보 포맷팅
output.append("\n## Balance Sheet Information")
output.append(f"Reference Period: {recent.get('fiscalDateEnding', 'N/A')}")
output.append(f"- Total Assets: ${float(recent['totalAssets']):,.2f}")
# ... 기타 대차대조표 정보 포맷팅
# 손익계산서 정보 포맷팅
output.append("\n## Income Statement Information")
# ... 손익계산서 정보 포맷팅
# 현금흐름표 정보 포맷팅
output.append("\n## Cash Flow Information")
# ... 현금흐름표 정보 포맷팅
# 재무 비율 포맷팅
output.append("\n## Financial Ratios")
# ... 재무 비율 정보 포맷팅
# 재무 분석 결과 포맷팅
output.append("\n## Financial Analysis")
# ... 분석 결과 정보 포맷팅
formatted_result = "\n".join(output)
# Financial Statement Analysis for Apple Inc. (Ticker: AAPL)
## Company Profile
- Sector: Technology
- Industry: Consumer Electronics
- Description: Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. The company offers iPhone, a line of smartphones; Mac, a line of personal computers; iPad, a line of multi-purpose tablets; and wearables, home, and accessories comprising AirPods, Apple TV, Apple Watch, Beats products, and HomePod...
- Market Cap: $2,876,543,210,987.00
- Employees: 164,000
- Dividend Yield: 0.52%
- 52-Week Range: $132.61 - $182.94
## Balance Sheet Information
Reference Period: 2023-09-30
- Total Assets: $352,583,000,000.00
- Current Assets: $143,600,000,000.00
- Total Liabilities: $290,407,000,000.00
- Current Liabilities: $125,260,000,000.00
- Total Shareholder Equity: $62,176,000,000.00
- Long-Term Debt: $95,281,000,000.00
- Cash and Equivalents: $29,965,000,000.00
## Income Statement Information
Reference Period: 2023-09-30
- Total Revenue: $394,328,000,000.00
- Cost of Revenue: $223,814,000,000.00
- Gross Profit: $170,514,000,000.00
- Operating Expenses: $54,060,000,000.00
- Operating Income: $116,454,000,000.00
- Net Income: $96,995,000,000.00
- EBITDA: $130,485,000,000.00
## Cash Flow Information
Reference Period: 2023-09-30
- Operating Cash Flow: $113,780,000,000.00
- Cash Flow from Investment: $-22,690,000,000.00
- Cash Flow from Financing: $-95,974,000,000.00
- Capital Expenditures: $-11,284,000,000.00
- Dividend Payout: $-15,132,000,000.00
## Financial Ratios
- P/E Ratio: 32.42
- PEG Ratio: 2.98
- Price to Book Ratio: 53.21
- EPS: $6.14
- Return on Equity (TTM): 156.04%
- Return on Assets (TTM): 27.48%
- Operating Margin (TTM): 29.53%
- Profit Margin: 24.60%
- Quarterly Earnings Growth (YOY): 10.82%
- Quarterly Revenue Growth (YOY): 7.77%
## Financial Analysis
- Sector: Technology
- Industry: Consumer Electronics
- Current Ratio: 1.15
- Evaluation: Adequate liquidity
- Debt to Equity Ratio: 153.24%
- Evaluation: High debt (aggressive)
- Revenue Growth: 7.77%
- Evaluation: Good revenue growth
- Operating Margin: 29.53%
- Evaluation: Excellent profitability
- Gross Margin: 43.24%
- Net Margin: 24.60%
- ROE: 156.04%
- Evaluation: Excellent ROE
- Net Income Growth: 10.82%
- Market Cap: $2,876,543,210,987.00
- P/E Ratio: 32.42
- P/B Ratio: 53.21
Observation: [USFinancialStatementTool에서 반환된 마크다운 형식의 재무 분석 결과 텍스트]
이제 분석 결과를 받았습니다. 사용자에게 Apple Inc.(AAPL)의 재무 상태에 대한 종합적인 분석을 제공할 수 있습니다.
사용자에게 제공할 최종 응답:
# Financial Statement Analysis for Apple Inc. (Ticker: AAPL)
...
[상세 분석 결과]
...
# USFinancialAnalyzerNode._run 내부
result = self.agent.invoke(state)
self.logger.info(f"US Financial analysis result: \n{result['messages'][-1].content}")
# 티커 심볼 추출
ticker_info = self._extract_ticker_from_result(result['messages'][-1].content)
# 정규 표현식으로 "Ticker: AAPL"에서 AAPL 추출, 결과: {"ticker": "AAPL"}
# 최종 Command 객체 생성
return Command(
update={
"messages": [
HumanMessage(
content=result["messages"][-1].content,
name="us_financial_analyzer",
)
],
"financial_analysis": {
"ticker": ticker_info["ticker"], # "AAPL"
"market": "US",
"analysis_text": result["messages"][-1].content,
}
},
goto="supervisor",
)
Command(
update={
"messages": [
HumanMessage(
content="""# Financial Statement Analysis for Apple Inc. (Ticker: AAPL)
## Company Profile
- Sector: Technology
- Industry: Consumer Electronics
- Description: Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. The company offers iPhone, a line of smartphones; Mac, a line of personal computers; iPad, a line of multi-purpose tablets; and wearables, home, and accessories comprising AirPods, Apple TV, Apple Watch, Beats products, and HomePod...
- Market Cap: $2,876,543,210,987.00
- Employees: 164,000
- Dividend Yield: 0.52%
- 52-Week Range: $132.61 - $182.94
## Balance Sheet Information
Reference Period: 2023-09-30
- Total Assets: $352,583,000,000.00
- Current Assets: $143,600,000,000.00
- Total Liabilities: $290,407,000,000.00
- Current Liabilities: $125,260,000,000.00
- Total Shareholder Equity: $62,176,000,000.00
- Long-Term Debt: $95,281,000,000.00
- Cash and Equivalents: $29,965,000,000.00
## Income Statement Information
Reference Period: 2023-09-30
- Total Revenue: $394,328,000,000.00
- Cost of Revenue: $223,814,000,000.00
- Gross Profit: $170,514,000,000.00
- Operating Expenses: $54,060,000,000.00
- Operating Income: $116,454,000,000.00
- Net Income: $96,995,000,000.00
- EBITDA: $130,485,000,000.00
## Cash Flow Information
Reference Period: 2023-09-30
- Operating Cash Flow: $113,780,000,000.00
- Cash Flow from Investment: $-22,690,000,000.00
- Cash Flow from Financing: $-95,974,000,000.00
- Capital Expenditures: $-11,284,000,000.00
- Dividend Payout: $-15,132,000,000.00
## Financial Ratios
- P/E Ratio: 32.42
- PEG Ratio: 2.98
- Price to Book Ratio: 53.21
- EPS: $6.14
- Return on Equity (TTM): 156.04%
- Return on Assets (TTM): 27.48%
- Operating Margin (TTM): 29.53%
- Profit Margin: 24.60%
- Quarterly Earnings Growth (YOY): 10.82%
- Quarterly Revenue Growth (YOY): 7.77%
## Financial Analysis
- Sector: Technology
- Industry: Consumer Electronics
- Current Ratio: 1.15
- Evaluation: Adequate liquidity
- Debt to Equity Ratio: 153.24%
- Evaluation: High debt (aggressive)
- Revenue Growth: 7.77%
- Evaluation: Good revenue growth
- Operating Margin: 29.53%
- Evaluation: Excellent profitability
- Gross Margin: 43.24%
- Net Margin: 24.60%
- ROE: 156.04%
- Evaluation: Excellent ROE
- Net Income Growth: 10.82%
- Market Cap: $2,876,543,210,987.00
- P/E Ratio: 32.42
- P/B Ratio: 53.21""",
name="us_financial_analyzer",
)
],
"financial_analysis": {
"ticker": "AAPL",
"market": "US",
"analysis_text": "# Financial Statement Analysis for Apple Inc. (Ticker: AAPL)\n\n## Company Profile\n- Sector: Technology\n- Industry: Consumer Electronics\n...[전체 분석 텍스트]..."
}
},
goto="supervisor", # 다음 처리를 위해 'supervisor' 노드로 이동
)
INFO:USFinancialAnalyzerNode:US Financial analysis result:
# Financial Statement Analysis for Apple Inc. (Ticker: AAPL)
...
[전체 분석 텍스트]
...
미국 주식 시장 분석해줘.
사용자 요청: "미국 주식 시장 분석해줘."
사용자가 미국 주식 시장에 대한 분석을 요청했지만, 특정 주식의 티커 심볼이 없습니다.
재무 분석을 하려면 특정 회사의 티커 심볼이 필요합니다.
us_financial_statement_analyzer 도구를 사용해보고 추가 정보를 요청해봐야겠습니다.
Action: us_financial_statement_analyzer
Action Input: "미국 주식 시장 분석해줘."
# _extract_ticker("미국 주식 시장 분석해줘.") 호출
match = re.search(r'\b([A-Z]{1,5})\b', "미국 주식 시장 분석해줘.") # 매치 없음
match = re.search(r'(?:[ticker|symbol]?[:\s]*|[^\w\d]*\()([A-Z]{1,5})(?:\)|)', "미국 주식 시장 분석해줘.", re.IGNORECASE) # 매치 없음
return None # 티커 심볼을 찾지 못함
ticker = self._extract_ticker(query) # None
if not ticker:
return "No valid ticker symbol found in the query. Please provide a query with a US stock ticker (e.g., AAPL, MSFT)."
Observation: No valid ticker symbol found in the query. Please provide a query with a US stock ticker (e.g., AAPL, MSFT).
이제 사용자에게 특정 주식의 티커 심볼을 제공해달라고 요청해야 합니다.
사용자에게 제공할 최종 응답:
재무 분석을 위해 유효한 티커 심볼을 찾을 수 없습니다. 분석하시려는 특정 미국 주식의 티커 심볼(예: AAPL, MSFT)을 포함해 주시기 바랍니다. 어떤 특정 회사의 재무 상태를 분석하고 싶으신가요?
# USFinancialAnalyzerNode._extract_ticker_from_result 호출
# 결과 텍스트에서 티커 심볼을 찾지 못함
ticker_info = {"ticker": "unknown"}
# 최종 Command 객체 생성
return Command(
update={
"messages": [
HumanMessage(
content="재무 분석을 위해 유효한 티커 심볼을 찾을 수 없습니다. 분석하시려는 특정 미국 주식의 티커 심볼(예: AAPL, MSFT)을 포함해 주시기 바랍니다. 어떤 특정 회사의 재무 상태를 분석하고 싶으신가요?",
name="us_financial_analyzer",
)
],
"financial_analysis": {
"ticker": "unknown",
"market": "US",
"analysis_text": "재무 분석을 위해 유효한 티커 심볼을 찾을 수 없습니다. 분석하시려는 특정 미국 주식의 티커 심볼(예: AAPL, MSFT)을 포함해 주시기 바랍니다. 어떤 특정 회사의 재무 상태를 분석하고 싶으신가요?"
}
},
goto="supervisor",
)
이 전체 과정을 통해, 코드는 쿼리에서 티커 심볼을 명확하게 인식할 수 있는 경우에만 완전한 재무 분석 결과를 제공하고, 그렇지 않은 경우 사용자에게 추가 정보를 요청하도록 설계되어 있습니다.