data_formatter.py•2.91 kB
"""
Data formatting utilities for MCP Stock Details Server
"""
from typing import Dict, Any, List
from decimal import Decimal
import re
class DataFormatter:
"""Utility class for formatting data responses"""
@staticmethod
def format_company_overview(company_data: Dict[str, Any]) -> str:
"""Format company overview data for text response"""
lines = []
for key, value in company_data.items():
formatted_key = key.replace("_", " ").title()
lines.append(f"{formatted_key}: {value}")
return "\n".join(lines)
@staticmethod
def format_financial_data(financial_data: List[Dict[str, Any]]) -> str:
"""Format financial data for text response"""
if not financial_data:
return "No financial data available"
data = financial_data[0] # Use most recent data
return (
f"Revenue: {data['revenue']:,} KRW\n"
f"Operating Profit: {data['operating_profit']:,} KRW\n"
f"Net Profit: {data['net_profit']:,} KRW\n"
f"Total Assets: {data['total_assets']:,} KRW"
)
@staticmethod
def parse_company_code(company_code: str) -> str:
"""Validate and normalize company code"""
if not company_code or not company_code.strip():
raise ValueError("Company code cannot be empty")
# Remove any whitespace and ensure 6-digit format
normalized_code = company_code.strip().zfill(6)
if not normalized_code.isdigit() or len(normalized_code) != 6:
raise ValueError("Company code must be a 6-digit number")
return normalized_code
@staticmethod
def format_large_number(number: float, currency: str = "KRW") -> str:
"""Format large numbers in a human-readable way with Korean units"""
if number == 0:
return f"0 {currency}"
# Korean units: 원(1), 만(10^4), 억(10^8), 조(10^12), 경(10^16)
units = [
(10**16, "경"),
(10**12, "조"),
(10**8, "억"),
(10**4, "만"),
(1, "")
]
abs_number = abs(number)
sign = "-" if number < 0 else ""
for unit_value, unit_name in units:
if abs_number >= unit_value:
value = abs_number / unit_value
if value >= 1000:
# Show with decimal if large
formatted = f"{value:,.1f}"
elif value >= 100:
formatted = f"{value:,.0f}"
else:
formatted = f"{value:,.2f}" if value < 10 else f"{value:,.1f}"
return f"{sign}{formatted}{unit_name} {currency}".strip()
# For very small numbers
return f"{sign}{abs_number:,.2f} {currency}"