Skip to content

Hypergraph is more powerful. Transform unstructured text into structured knowledge with LLMs. Graphs, hypergraphs, and spatio-temporal extractions — with one command.

feat: add SEC Filings (10-K/10-Q/8-K) templates - FilingFinancialSnapshot (AutoModel) - financial statements extraction - MDANarrativeGraph (AutoGraph) - MD&A causal relationships - FilingRiskFactorSet (AutoSet) - risk factor registry - MaterialEventTimeline (AutoTemporalGraph) - 8-K event chronology - SegmentPerformanceList (AutoList) - segment-level metrics

yuxizhed2da0a5c21ce
diff --git a/hyperextract/templates/en/__init__.py b/hyperextract/templates/en/__init__.py
index 557ab06..ef6da83 100644
--- a/hyperextract/templates/en/__init__.py
+++ b/hyperextract/templates/en/__init__.py
@@ -1,7 +1,33 @@
-from .general import KnowledgeGraph, ConceptMap, LogicGraph
+from .general import KnowledgeGraph, ConceptMap, LogicGraph
from .agriculture import CropCycleGraph, LivestockGraph, AgriPestControl
from .biology import TaxonomyGraph, BiologicalNetwork, MetabolicHypergraph
from .chemistry import MolecularStructureGraph, ChemicalReactionHyper, LabProtocolTemporal
+from .finance import (
+ RiskAssessmentGraph,
+ MarketSentimentGraph,
+ SupplyChainGraph,
+ FilingFinancialSnapshot,
+ MDANarrativeGraph,
+ FilingRiskFactorSet,
+ MaterialEventTimeline,
+ SegmentPerformanceList,
+ ResearchNoteSummary,
+ FinancialForecast,
+ ValuationLogicMap,
+ FactorInfluenceHypergraph,
+ RiskFactorList,
+ ShareholderStructure,
+ ProceedsUsage,
+ CompanyHistoryTimeline,
+ EarningsCallSummary,
+ ManagementGuidanceList,
+ AnalystQAGraph,
+ CallSentimentHypergraph,
+ MarketSentimentModel,
+ FinancialEventCausalGraph,
+ MultiSourceSentimentHypergraph,
+ MarketNarrativeTimeline,
+)
from .literature import CharacterRelationshipGraph, NarrativeTimeline, SymbolismSet
from .medicine import DrugInteractionGraph, ClinicalTreatmentTimeline, DiagnosticCriteriaSet
from .movie import ScriptSceneGraph, CharacterArcTracker, CinematicTriviaSet
@@ -20,6 +46,32 @@ __all__ = [
"MolecularStructureGraph",
"ChemicalReactionHyper",
"LabProtocolTemporal",
+ # Finance
+ "RiskAssessmentGraph",
+ "MarketSentimentGraph",
+ "SupplyChainGraph",
+ "FilingFinancialSnapshot",
+ "MDANarrativeGraph",
+ "FilingRiskFactorSet",
+ "MaterialEventTimeline",
+ "SegmentPerformanceList",
+ "ResearchNoteSummary",
+ "FinancialForecast",
+ "ValuationLogicMap",
+ "FactorInfluenceHypergraph",
+ "RiskFactorList",
+ "ShareholderStructure",
+ "ProceedsUsage",
+ "CompanyHistoryTimeline",
+ "EarningsCallSummary",
+ "ManagementGuidanceList",
+ "AnalystQAGraph",
+ "CallSentimentHypergraph",
+ "MarketSentimentModel",
+ "FinancialEventCausalGraph",
+ "MultiSourceSentimentHypergraph",
+ "MarketNarrativeTimeline",
+ # Literature
"CharacterRelationshipGraph",
"NarrativeTimeline",
"SymbolismSet",
diff --git a/hyperextract/templates/en/finance/__init__.py b/hyperextract/templates/en/finance/__init__.py
index 6fbf0ee..8292945 100644
--- a/hyperextract/templates/en/finance/__init__.py
+++ b/hyperextract/templates/en/finance/__init__.py
@@ -1,15 +1,75 @@
"""
Finance domain templates for extracting structured knowledge from financial documents.
-Includes templates for risk assessment, market sentiment, and supply chain analysis.
+Includes templates for SEC filings, equity research, prospectuses, earnings calls,
+financial news, risk assessment, market sentiment, and supply chain analysis.
"""
+# Existing templates
from .risk_assessment import RiskAssessmentGraph
from .market_sentiment import MarketSentimentGraph
from .supply_chain import SupplyChainGraph
+# SEC Filings (10-K / 10-Q / 8-K)
+from .filing_financial_snapshot import FilingFinancialSnapshot
+from .mda_narrative_graph import MDANarrativeGraph
+from .filing_risk_factor_set import FilingRiskFactorSet
+from .material_event_timeline import MaterialEventTimeline
+from .segment_performance_list import SegmentPerformanceList
+
+# Equity Research Reports
+from .research_note_summary import ResearchNoteSummary
+from .financial_forecast import FinancialForecast
+from .valuation_logic_map import ValuationLogicMap
+from .factor_influence_hypergraph import FactorInfluenceHypergraph
+from .risk_factor_list import RiskFactorList
+
+# Prospectuses / IPO Filings (S-1)
+from .shareholder_structure import ShareholderStructure
+from .proceeds_usage import ProceedsUsage
+from .company_history_timeline import CompanyHistoryTimeline
+
+# Earnings Call Transcripts
+from .earnings_call_summary import EarningsCallSummary
+from .management_guidance_list import ManagementGuidanceList
+from .analyst_qa_graph import AnalystQAGraph
+from .call_sentiment_hypergraph import CallSentimentHypergraph
+
+# Financial News & Market Commentary
+from .market_sentiment_model import MarketSentimentModel
+from .financial_event_causal_graph import FinancialEventCausalGraph
+from .multi_source_sentiment_hypergraph import MultiSourceSentimentHypergraph
+from .market_narrative_timeline import MarketNarrativeTimeline
+
__all__ = [
+ # Existing templates
"RiskAssessmentGraph",
"MarketSentimentGraph",
"SupplyChainGraph",
+ # SEC Filings
+ "FilingFinancialSnapshot",
+ "MDANarrativeGraph",
+ "FilingRiskFactorSet",
+ "MaterialEventTimeline",
+ "SegmentPerformanceList",
+ # Equity Research
+ "ResearchNoteSummary",
+ "FinancialForecast",
+ "ValuationLogicMap",
+ "FactorInfluenceHypergraph",
+ "RiskFactorList",
+ # Prospectuses / IPO
+ "ShareholderStructure",
+ "ProceedsUsage",
+ "CompanyHistoryTimeline",
+ # Earnings Calls
+ "EarningsCallSummary",
+ "ManagementGuidanceList",
+ "AnalystQAGraph",
+ "CallSentimentHypergraph",
+ # Financial News
+ "MarketSentimentModel",
+ "FinancialEventCausalGraph",
+ "MultiSourceSentimentHypergraph",
+ "MarketNarrativeTimeline",
]
diff --git a/hyperextract/templates/en/finance/filing_financial_snapshot.py b/hyperextract/templates/en/finance/filing_financial_snapshot.py
new file mode 100644
index 0000000..cc269f2
--- /dev/null
+++ b/hyperextract/templates/en/finance/filing_financial_snapshot.py
@@ -0,0 +1,164 @@
+"""Filing Financial Snapshot - Extracts key financial figures from SEC filings.
+
+Extracts income statement, balance sheet, and cash flow data from 10-K/10-Q filings
+into a single structured object for fundamental screening and database population.
+"""
+
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from ontomem.merger import MergeStrategy
+from hyperextract.types import AutoModel
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class FilingFinancialSnapshotSchema(BaseModel):
+ """
+ A structured snapshot of key financial data extracted from SEC filings.
+ """
+
+ company_name: Optional[str] = Field(
+ None, description="Legal name of the filing entity."
+ )
+ ticker: Optional[str] = Field(
+ None, description="Stock ticker symbol (e.g., 'AAPL', 'MSFT')."
+ )
+ filing_type: Optional[str] = Field(
+ None, description="Filing type: '10-K', '10-Q', '8-K', '20-F'."
+ )
+ filing_period: Optional[str] = Field(
+ None,
+ description="Fiscal period covered (e.g., 'FY2024', 'Q3 2024', 'Year ended Dec 31, 2024').",
+ )
+ revenue: Optional[str] = Field(
+ None,
+ description="Total revenue or net sales for the period (e.g., '$394.3 billion').",
+ )
+ cost_of_revenue: Optional[str] = Field(
+ None, description="Cost of goods sold or cost of revenue."
+ )
+ gross_profit: Optional[str] = Field(
+ None, description="Gross profit (Revenue minus Cost of Revenue)."
+ )
+ operating_income: Optional[str] = Field(
+ None, description="Operating income or loss."
+ )
+ net_income: Optional[str] = Field(
+ None, description="Net income attributable to common shareholders."
+ )
+ earnings_per_share: Optional[str] = Field(
+ None, description="Diluted EPS (e.g., '$6.13')."
+ )
+ total_assets: Optional[str] = Field(
+ None, description="Total assets from the balance sheet."
+ )
+ total_liabilities: Optional[str] = Field(
+ None, description="Total liabilities from the balance sheet."
+ )
+ shareholders_equity: Optional[str] = Field(
+ None, description="Total shareholders' equity."
+ )
+ cash_and_equivalents: Optional[str] = Field(
+ None, description="Cash and cash equivalents."
+ )
+ operating_cash_flow: Optional[str] = Field(
+ None, description="Net cash from operating activities."
+ )
+ capital_expenditures: Optional[str] = Field(
+ None, description="Capital expenditures (CapEx)."
+ )
+ free_cash_flow: Optional[str] = Field(
+ None, description="Free cash flow (Operating Cash Flow minus CapEx)."
+ )
+ dividends_per_share: Optional[str] = Field(
+ None, description="Dividends declared per share."
+ )
+ shares_outstanding: Optional[str] = Field(
+ None, description="Weighted average diluted shares outstanding."
+ )
+ key_ratios: Optional[List[str]] = Field(
+ None,
+ description="Notable financial ratios mentioned (e.g., 'Gross Margin: 45.6%', 'D/E Ratio: 1.2x').",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an expert financial analyst specializing in SEC filing analysis. "
+ "Extract key financial figures from income statements, balance sheets, and cash flow statements "
+ "embedded within this filing.\n\n"
+ "Rules:\n"
+ "- Extract exact dollar amounts as reported, preserving units (millions, billions).\n"
+ "- Identify the filing entity, ticker, filing type, and fiscal period.\n"
+ "- Extract both the most recent period and prior period comparisons when available.\n"
+ "- Capture key ratios explicitly stated in the filing.\n"
+ "- Use exact figures from tables; do not compute derived values unless explicitly stated.\n\n"
+ "### Source Text:\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class FilingFinancialSnapshot(AutoModel[FilingFinancialSnapshotSchema]):
+ """
+ Applicable to: SEC 10-K Annual Reports, 10-Q Quarterly Reports, 20-F Foreign Filings,
+ Annual Reports with embedded financial statements.
+
+ Template for extracting a consolidated financial data snapshot from SEC filings.
+ Merges financial figures from income statements, balance sheets, and cash flow statements
+ across multiple sections of a filing into a single structured object.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> snapshot = FilingFinancialSnapshot(llm_client=llm, embedder=embedder)
+ >>> filing_text = "Item 8. Financial Statements: Revenue was $394.3 billion..."
+ >>> snapshot.feed_text(filing_text)
+ >>> print(snapshot.data)
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Filing Financial Snapshot template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for financial data extraction.
+ embedder (Embeddings): Embedding model for indexing.
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoModel.
+ """
+ super().__init__(
+ data_schema=FilingFinancialSnapshotSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ strategy_or_merger=MergeStrategy.LLM.BALANCED,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
diff --git a/hyperextract/templates/en/finance/filing_risk_factor_set.py b/hyperextract/templates/en/finance/filing_risk_factor_set.py
new file mode 100644
index 0000000..ccbf112
--- /dev/null
+++ b/hyperextract/templates/en/finance/filing_risk_factor_set.py
@@ -0,0 +1,146 @@
+"""Filing Risk Factor Set - Deduplicates and catalogs risk factors from SEC filings.
+
+Extracts and normalizes risk factors disclosed in Item 1A of 10-K/10-Q filings,
+tracking additions and removals between filing periods for risk evolution monitoring.
+"""
+
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class RiskFactorItem(BaseModel):
+ """
+ A single risk factor disclosed in SEC filings.
+ """
+
+ risk_title: str = Field(
+ description="Concise title of the risk factor (e.g., 'Cybersecurity Breach Risk', 'Foreign Currency Exposure')."
+ )
+ risk_category: str = Field(
+ description="Category: 'Market', 'Operational', 'Regulatory', 'Financial', 'Strategic', 'Cybersecurity', 'ESG', 'Legal', 'Geopolitical'."
+ )
+ description: str = Field(
+ description="Full description of the risk as disclosed in the filing."
+ )
+ potential_impact: Optional[str] = Field(
+ None,
+ description="Stated potential financial or operational impact (e.g., 'material adverse effect on revenue').",
+ )
+ affected_areas: Optional[List[str]] = Field(
+ None,
+ description="Business segments or functions affected (e.g., ['International Operations', 'Supply Chain']).",
+ )
+ mitigation_disclosed: Optional[str] = Field(
+ None,
+ description="Any mitigation measures or controls the company has disclosed.",
+ )
+ is_new: Optional[bool] = Field(
+ None,
+ description="Whether this risk factor appears to be newly added compared to prior filings.",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a regulatory filing analyst specializing in risk disclosure analysis. "
+ "Extract and catalog all individual risk factors from Item 1A (Risk Factors) or equivalent "
+ "risk disclosure sections of SEC filings.\n\n"
+ "Extraction Principles:\n"
+ "1. **Normalization**: Aggregate related risk language under a single concise risk title.\n"
+ "2. **Categorization**: Classify each risk into its primary category.\n"
+ "3. **Completeness**: Extract every distinct risk factor, even if briefly mentioned.\n"
+ "4. **Cumulative**: If the same risk appears with additional detail across sections, merge the information."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class FilingRiskFactorSet(AutoSet[RiskFactorItem]):
+ """
+ Applicable to: SEC 10-K Item 1A (Risk Factors), 10-Q Risk Factor updates,
+ S-1 Prospectus Risk Sections, 20-F Risk Disclosures.
+
+ Template for building a deduplicated registry of risk factors from regulatory filings.
+ Leverages AutoSet's key-accumulation to merge risk disclosures from different sections
+ or filing periods into a comprehensive risk catalog.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> risk_set = FilingRiskFactorSet(llm_client=llm, embedder=embedder)
+ >>> filing = "Item 1A. Risk Factors: We face significant cybersecurity risks..."
+ >>> risk_set.feed_text(filing)
+ >>> risk_set.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Filing Risk Factor Set template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for risk factor extraction.
+ embedder (Embeddings): Embedding model for retrieval.
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoSet.
+ """
+ super().__init__(
+ item_schema=RiskFactorItem,
+ key_extractor=lambda x: x.risk_title.strip().lower(),
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """
+ Visualize the risk factor registry.
+
+ Args:
+ top_k_for_search (int): Items for search. Default 3.
+ top_k_for_chat (int): Items for chat context. Default 3.
+ """
+
+ def item_label_extractor(item: RiskFactorItem) -> str:
+ return f"[{item.risk_category}] {item.risk_title}"
+
+ super().show(
+ item_label_extractor=item_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/en/finance/material_event_timeline.py b/hyperextract/templates/en/finance/material_event_timeline.py
new file mode 100644
index 0000000..dda6ba3
--- /dev/null
+++ b/hyperextract/templates/en/finance/material_event_timeline.py
@@ -0,0 +1,204 @@
+"""Material Event Timeline - Chronologically extracts material events from 8-K filings.
+
+Extracts executive changes, M&A announcements, restatements, and other material events
+with temporal ordering for event-driven analysis and regulatory monitoring.
+"""
+
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoTemporalGraph
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class MaterialEventEntity(BaseModel):
+ """
+ An entity involved in a material corporate event.
+ """
+
+ name: str = Field(
+ description="Name of the entity (e.g., company name, executive name, regulatory body)."
+ )
+ entity_type: str = Field(
+ description="Type: 'Company', 'Executive', 'Regulator', 'Counterparty', 'Subsidiary', 'Auditor'."
+ )
+ description: Optional[str] = Field(
+ None, description="Role or context (e.g., 'CEO', 'Acquiring Company', 'SEC')."
+ )
+
+
+class MaterialEventEdge(BaseModel):
+ """
+ A material event linking entities with temporal context.
+ """
+
+ source: str = Field(description="The acting entity name.")
+ target: str = Field(description="The affected entity name.")
+ event_type: str = Field(
+ description="Type: 'Executive Appointment', 'Executive Departure', 'Acquisition', 'Divestiture', "
+ "'Restatement', 'Bankruptcy', 'Delisting', 'Material Agreement', 'Dividend Declaration', "
+ "'Stock Split', 'Regulatory Action'."
+ )
+ start_timestamp: Optional[str] = Field(
+ None,
+ description="Date the event occurred or was announced (e.g., '2024-03-15', 'March 15, 2024').",
+ )
+ end_timestamp: Optional[str] = Field(
+ None,
+ description="End date if applicable (e.g., effective date, closing date).",
+ )
+ description: Optional[str] = Field(
+ None,
+ description="Details of the material event including financial terms, conditions, or regulatory context.",
+ )
+ sec_item: Optional[str] = Field(
+ None,
+ description="8-K Item number (e.g., 'Item 5.02', 'Item 1.01', 'Item 2.01').",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a regulatory filing analyst specializing in 8-K current reports and material event disclosures. "
+ "Extract entities involved in material events and the temporal relationships between them.\n\n"
+ "Rules:\n"
+ "- Identify companies, executives, regulators, and counterparties involved.\n"
+ "- Extract each material event with its specific date(s).\n"
+ "- Classify events by their 8-K Item number when available.\n"
+ "- Capture financial terms, conditions, and regulatory context.\n"
+ "- Maintain chronological accuracy."
+)
+
+_NODE_PROMPT = (
+ "You are a regulatory filing analyst. Extract all entities (Nodes) involved in material events.\n\n"
+ "Extraction Rules:\n"
+ "- Identify companies, executives, regulatory bodies, auditors, and counterparties.\n"
+ "- Classify each entity by type.\n"
+ "- Capture role descriptions.\n"
+ "- DO NOT extract events or relationships at this stage."
+)
+
+_EDGE_PROMPT = (
+ "You are a regulatory filing analyst. Given the entities, extract all material events (Edges) with dates.\n\n"
+ "Extraction Rules:\n"
+ "- Connect entities through material events.\n"
+ "- Extract specific dates for each event.\n"
+ "- Classify by event type and 8-K Item number.\n"
+ "- Capture financial terms and conditions.\n"
+ "- Only create edges between nodes that exist in the provided lists."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class MaterialEventTimeline(AutoTemporalGraph[MaterialEventEntity, MaterialEventEdge]):
+ """
+ Applicable to: SEC 8-K Current Reports, Material Event Disclosures,
+ Press Releases accompanying 8-K filings, Proxy Statements (DEF 14A).
+
+ Template for chronologically extracting material corporate events from 8-K filings
+ and related disclosures. Enables event-driven analysis, regulatory monitoring,
+ and corporate governance tracking.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> timeline = MaterialEventTimeline(llm_client=llm, embedder=embedder)
+ >>> filing = "Item 5.02: On March 15, 2024, the Board appointed John Smith as CEO..."
+ >>> timeline.feed_text(filing)
+ >>> timeline.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ observation_time: str = "2024-01-01",
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Material Event Timeline template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for event extraction.
+ embedder (Embeddings): Embedding model for deduplication.
+ observation_time (str): Reference time for resolving relative dates.
+ extraction_mode (str): "one_stage" or "two_stage".
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoTemporalGraph.
+ """
+ super().__init__(
+ node_schema=MaterialEventEntity,
+ edge_schema=MaterialEventEdge,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip().lower()}|{x.event_type.lower()}|{x.target.strip().lower()}"
+ ),
+ time_in_edge_extractor=lambda x: x.start_timestamp or "",
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ observation_time=observation_time,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """
+ Visualize the material event timeline using OntoSight.
+
+ Args:
+ top_k_nodes_for_search (int): Number of entities to retrieve. Default 3.
+ top_k_edges_for_search (int): Number of events to retrieve. Default 3.
+ top_k_nodes_for_chat (int): Entities for chat context. Default 3.
+ top_k_edges_for_chat (int): Events for chat context. Default 3.
+ """
+
+ def node_label_extractor(node: MaterialEventEntity) -> str:
+ return f"{node.name} ({node.entity_type})"
+
+ def edge_label_extractor(edge: MaterialEventEdge) -> str:
+ date = f" [{edge.start_timestamp}]" if edge.start_timestamp else ""
+ return f"{edge.event_type}{date}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/en/finance/mda_narrative_graph.py b/hyperextract/templates/en/finance/mda_narrative_graph.py
new file mode 100644
index 0000000..62cb713
--- /dev/null
+++ b/hyperextract/templates/en/finance/mda_narrative_graph.py
@@ -0,0 +1,192 @@
+"""MD&A Narrative Graph - Extracts causal relationships from Management Discussion & Analysis.
+
+Maps causal chains from business drivers to financial outcomes as described in MD&A sections
+of SEC filings (e.g., "Supply chain disruption -> Revenue decline -> Margin compression").
+"""
+
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoGraph
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class MDAFactor(BaseModel):
+ """
+ A business driver, financial outcome, or operational factor mentioned in MD&A.
+ """
+
+ name: str = Field(
+ description="Name of the factor (e.g., 'Supply Chain Disruption', 'Revenue Growth', 'Margin Compression')."
+ )
+ factor_type: str = Field(
+ description="Type: 'Business Driver', 'Financial Outcome', 'Operational Factor', 'Strategic Initiative', 'External Factor'."
+ )
+ description: Optional[str] = Field(
+ None,
+ description="Management's explanation or context for this factor.",
+ )
+
+
+class MDANarrativeEdge(BaseModel):
+ """
+ A causal or explanatory relationship between two MD&A factors.
+ """
+
+ source: str = Field(description="The cause or driver factor name.")
+ target: str = Field(description="The effect or outcome factor name.")
+ relationship_type: str = Field(
+ description="Type: 'Caused', 'Contributed To', 'Offset By', 'Resulted In', 'Led To', 'Mitigated By'."
+ )
+ magnitude: Optional[str] = Field(
+ None,
+ description="Quantified impact if mentioned (e.g., 'increased by $2.3B', '300 basis points').",
+ )
+ management_attribution: Optional[str] = Field(
+ None,
+ description="Management's own causal explanation verbatim or paraphrased.",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a financial analyst specializing in MD&A (Management Discussion & Analysis) sections of SEC filings. "
+ "Extract business drivers, financial outcomes, and the causal relationships management describes between them.\n\n"
+ "Rules:\n"
+ "- Identify factors management discusses: revenue drivers, cost pressures, strategic changes, external forces.\n"
+ "- Extract causal chains as management presents them (e.g., 'increased demand led to revenue growth').\n"
+ "- Capture quantified impacts when stated.\n"
+ "- Preserve management's attribution language."
+)
+
+_NODE_PROMPT = (
+ "You are a financial analyst. Extract all business drivers, financial outcomes, and operational factors (Nodes) "
+ "from the MD&A text.\n\n"
+ "Extraction Rules:\n"
+ "- Identify revenue drivers, cost factors, strategic initiatives, and external forces.\n"
+ "- Identify financial outcomes (revenue changes, margin shifts, cash flow impacts).\n"
+ "- Classify each factor by type.\n"
+ "- DO NOT establish causal relationships at this stage."
+)
+
+_EDGE_PROMPT = (
+ "You are a financial analyst. Given the list of MD&A factors, extract the causal and explanatory "
+ "relationships (Edges) that management describes.\n\n"
+ "Extraction Rules:\n"
+ "- Connect causes to effects as management presents them.\n"
+ "- Classify the relationship type (Caused, Contributed To, Offset By, etc.).\n"
+ "- Extract quantified magnitude when available.\n"
+ "- Capture management's own causal explanation.\n"
+ "- Only create edges between nodes that exist in the provided lists."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class MDANarrativeGraph(AutoGraph[MDAFactor, MDANarrativeEdge]):
+ """
+ Applicable to: SEC 10-K/10-Q Item 7 (Management Discussion & Analysis),
+ Annual Report MD&A sections, Interim Management Reports.
+
+ Template for extracting causal relationships from Management Discussion & Analysis
+ sections. Maps how management explains business performance drivers and their
+ financial impacts, enabling narrative analytics and driver attribution.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> mda = MDANarrativeGraph(llm_client=llm, embedder=embedder)
+ >>> text = "Revenue increased 12% driven by strong demand in our cloud segment..."
+ >>> mda.feed_text(text)
+ >>> mda.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "one_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the MD&A Narrative Graph template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for causal relationship extraction.
+ embedder (Embeddings): Embedding model for deduplication.
+ extraction_mode (str): "one_stage" or "two_stage".
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoGraph.
+ """
+ super().__init__(
+ node_schema=MDAFactor,
+ edge_schema=MDANarrativeEdge,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip().lower()}--({x.relationship_type})-->{x.target.strip().lower()}"
+ ),
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """
+ Visualize the MD&A narrative graph using OntoSight.
+
+ Args:
+ top_k_nodes_for_search (int): Number of factors to retrieve. Default 3.
+ top_k_edges_for_search (int): Number of causal links to retrieve. Default 3.
+ top_k_nodes_for_chat (int): Factors for chat context. Default 3.
+ top_k_edges_for_chat (int): Causal links for chat context. Default 3.
+ """
+
+ def node_label_extractor(node: MDAFactor) -> str:
+ return f"{node.name} ({node.factor_type})"
+
+ def edge_label_extractor(edge: MDANarrativeEdge) -> str:
+ mag = f" [{edge.magnitude}]" if edge.magnitude else ""
+ return f"{edge.relationship_type}{mag}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/en/finance/segment_performance_list.py b/hyperextract/templates/en/finance/segment_performance_list.py
new file mode 100644
index 0000000..ed3fcdb
--- /dev/null
+++ b/hyperextract/templates/en/finance/segment_performance_list.py
@@ -0,0 +1,146 @@
+"""Segment Performance List - Extracts revenue and metrics by business segment.
+
+Extracts revenue, operating income, and key metrics by business segment or
+geographic region from SEC filings for segment-level valuation and exposure analysis.
+"""
+
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoList
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class SegmentPerformanceItem(BaseModel):
+ """
+ Performance data for a single business segment or geographic region.
+ """
+
+ segment_name: str = Field(
+ description="Name of the business segment or geographic region (e.g., 'Americas', 'Cloud Services', 'iPhone')."
+ )
+ segment_type: str = Field(
+ description="Type: 'Business Segment', 'Geographic Region', 'Product Line', 'Operating Segment'."
+ )
+ revenue: Optional[str] = Field(
+ None, description="Segment revenue for the period (e.g., '$48.2 billion')."
+ )
+ operating_income: Optional[str] = Field(
+ None, description="Segment operating income or profit."
+ )
+ revenue_growth: Optional[str] = Field(
+ None,
+ description="Year-over-year or sequential revenue growth (e.g., '+12%', '-3% YoY').",
+ )
+ key_metrics: Optional[List[str]] = Field(
+ None,
+ description="Segment-specific KPIs (e.g., ['Subscribers: 230M', 'ARPU: $14.99', 'Churn: 2.1%']).",
+ )
+ commentary: Optional[str] = Field(
+ None,
+ description="Management commentary on segment performance or outlook.",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a financial analyst specializing in segment-level analysis. "
+ "Extract performance data for each business segment or geographic region from SEC filings.\n\n"
+ "Rules:\n"
+ "- Extract revenue and operating income for each identifiable segment.\n"
+ "- Capture growth rates and comparisons to prior periods.\n"
+ "- Extract segment-specific KPIs and metrics.\n"
+ "- Preserve management's segment commentary.\n"
+ "- Extract EVERY segment independently as a separate item.\n\n"
+ "### Source Text:\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class SegmentPerformanceList(AutoList[SegmentPerformanceItem]):
+ """
+ Applicable to: SEC 10-K/10-Q Segment Disclosures (ASC 280), Annual Reports,
+ Earnings Releases with segment breakdowns.
+
+ Template for extracting segment-level financial performance data from filings.
+ Each segment is captured as an independent list item for comparative analysis
+ and segment-level valuation.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> segments = SegmentPerformanceList(llm_client=llm, embedder=embedder)
+ >>> filing = "Americas segment revenue was $48.2B, up 12% YoY..."
+ >>> segments.feed_text(filing)
+ >>> segments.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Segment Performance List template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for segment data extraction.
+ embedder (Embeddings): Embedding model for indexing.
+ chunk_size (int): Max characters per chunk.
+ chunk_overlap (int): Overlap between chunks.
+ max_workers (int): Parallel processing workers.
+ verbose (bool): Enable progress logging.
+ **kwargs: Additional arguments for AutoList.
+ """
+ super().__init__(
+ item_schema=SegmentPerformanceItem,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """
+ Visualize the segment performance list.
+
+ Args:
+ top_k_for_search (int): Items for search. Default 3.
+ top_k_for_chat (int): Items for chat context. Default 3.
+ """
+
+ def label_extractor(item: SegmentPerformanceItem) -> str:
+ rev = f" | {item.revenue}" if item.revenue else ""
+ return f"{item.segment_name} ({item.segment_type}){rev}"
+
+ super().show(
+ item_label_extractor=label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/__init__.py b/hyperextract/templates/zh/__init__.py
index dc5dabd..e6d50a5 100644
--- a/hyperextract/templates/zh/__init__.py
+++ b/hyperextract/templates/zh/__init__.py
@@ -1,7 +1,33 @@
-from .general import KnowledgeGraph, ConceptMap, LogicGraph
+from .general import KnowledgeGraph, ConceptMap, LogicGraph
from .agriculture import CropCycleGraph, LivestockGraph, AgriPestControl
from .biology import TaxonomyGraph, BiologicalNetwork, MetabolicHypergraph
from .chemistry import MolecularStructureGraph, ChemicalReactionHyper, LabProtocolTemporal
+from .finance import (
+ RiskAssessmentGraph,
+ MarketSentimentGraph,
+ SupplyChainGraph,
+ FilingFinancialSnapshot,
+ MDANarrativeGraph,
+ FilingRiskFactorSet,
+ MaterialEventTimeline,
+ SegmentPerformanceList,
+ ResearchNoteSummary,
+ FinancialForecast,
+ ValuationLogicMap,
+ FactorInfluenceHypergraph,
+ RiskFactorList,
+ ShareholderStructure,
+ ProceedsUsage,
+ CompanyHistoryTimeline,
+ EarningsCallSummary,
+ ManagementGuidanceList,
+ AnalystQAGraph,
+ CallSentimentHypergraph,
+ MarketSentimentModel,
+ FinancialEventCausalGraph,
+ MultiSourceSentimentHypergraph,
+ MarketNarrativeTimeline,
+)
from .literature import CharacterRelationshipGraph, NarrativeTimeline, SymbolismSet
from .medicine import DrugInteractionGraph, ClinicalTreatmentTimeline, DiagnosticCriteriaSet
from .movie import ScriptSceneGraph, CharacterArcTracker, CinematicTriviaSet
@@ -28,6 +54,32 @@ __all__ = [
"MolecularStructureGraph",
"ChemicalReactionHyper",
"LabProtocolTemporal",
+ # Finance
+ "RiskAssessmentGraph",
+ "MarketSentimentGraph",
+ "SupplyChainGraph",
+ "FilingFinancialSnapshot",
+ "MDANarrativeGraph",
+ "FilingRiskFactorSet",
+ "MaterialEventTimeline",
+ "SegmentPerformanceList",
+ "ResearchNoteSummary",
+ "FinancialForecast",
+ "ValuationLogicMap",
+ "FactorInfluenceHypergraph",
+ "RiskFactorList",
+ "ShareholderStructure",
+ "ProceedsUsage",
+ "CompanyHistoryTimeline",
+ "EarningsCallSummary",
+ "ManagementGuidanceList",
+ "AnalystQAGraph",
+ "CallSentimentHypergraph",
+ "MarketSentimentModel",
+ "FinancialEventCausalGraph",
+ "MultiSourceSentimentHypergraph",
+ "MarketNarrativeTimeline",
+ # Literature
"CharacterRelationshipGraph",
"NarrativeTimeline",
"SymbolismSet",
diff --git a/hyperextract/templates/zh/finance/__init__.py b/hyperextract/templates/zh/finance/__init__.py
index 05c9906..e5a5359 100644
--- a/hyperextract/templates/zh/finance/__init__.py
+++ b/hyperextract/templates/zh/finance/__init__.py
@@ -1,15 +1,75 @@
"""
金融领域模板,用于从财务文档中提取结构化知识。
-包含风险评估、市场观点和供应链分析等模板。
+包含 SEC 文件、股票研究报告、招股说明书、财报电话会议、
+金融新闻、风险评估、市场观点和供应链分析等模板。
"""
+# 已有模板
from .risk_assessment import RiskAssessmentGraph
from .market_sentiment import MarketSentimentGraph
from .supply_chain import SupplyChainGraph
+# SEC 文件 (10-K / 10-Q / 8-K)
+from .filing_financial_snapshot import FilingFinancialSnapshot
+from .mda_narrative_graph import MDANarrativeGraph
+from .filing_risk_factor_set import FilingRiskFactorSet
+from .material_event_timeline import MaterialEventTimeline
+from .segment_performance_list import SegmentPerformanceList
+
+# 股票研究报告
+from .research_note_summary import ResearchNoteSummary
+from .financial_forecast import FinancialForecast
+from .valuation_logic_map import ValuationLogicMap
+from .factor_influence_hypergraph import FactorInfluenceHypergraph
+from .risk_factor_list import RiskFactorList
+
+# 招股说明书 / IPO 文件 (S-1)
+from .shareholder_structure import ShareholderStructure
+from .proceeds_usage import ProceedsUsage
+from .company_history_timeline import CompanyHistoryTimeline
+
+# 财报电话会议记录
+from .earnings_call_summary import EarningsCallSummary
+from .management_guidance_list import ManagementGuidanceList
+from .analyst_qa_graph import AnalystQAGraph
+from .call_sentiment_hypergraph import CallSentimentHypergraph
+
+# 金融新闻与市场评论
+from .market_sentiment_model import MarketSentimentModel
+from .financial_event_causal_graph import FinancialEventCausalGraph
+from .multi_source_sentiment_hypergraph import MultiSourceSentimentHypergraph
+from .market_narrative_timeline import MarketNarrativeTimeline
+
__all__ = [
+ # 已有模板
"RiskAssessmentGraph",
"MarketSentimentGraph",
"SupplyChainGraph",
+ # SEC 文件
+ "FilingFinancialSnapshot",
+ "MDANarrativeGraph",
+ "FilingRiskFactorSet",
+ "MaterialEventTimeline",
+ "SegmentPerformanceList",
+ # 股票研究报告
+ "ResearchNoteSummary",
+ "FinancialForecast",
+ "ValuationLogicMap",
+ "FactorInfluenceHypergraph",
+ "RiskFactorList",
+ # 招股说明书 / IPO
+ "ShareholderStructure",
+ "ProceedsUsage",
+ "CompanyHistoryTimeline",
+ # 财报电话会议
+ "EarningsCallSummary",
+ "ManagementGuidanceList",
+ "AnalystQAGraph",
+ "CallSentimentHypergraph",
+ # 金融新闻
+ "MarketSentimentModel",
+ "FinancialEventCausalGraph",
+ "MultiSourceSentimentHypergraph",
+ "MarketNarrativeTimeline",
]
diff --git a/hyperextract/templates/zh/finance/filing_financial_snapshot.py b/hyperextract/templates/zh/finance/filing_financial_snapshot.py
new file mode 100644
index 0000000..7987841
--- /dev/null
+++ b/hyperextract/templates/zh/finance/filing_financial_snapshot.py
@@ -0,0 +1,162 @@
+"""财报财务快照 - 从 SEC 申报文件中提取关键财务数据。
+
+从 10-K/10-Q 申报文件中提取利润表、资产负债表和现金流量表数据,
+整合为单一结构化对象,用于基本面筛选和数据库填充。
+"""
+
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from ontomem.merger import MergeStrategy
+from hyperextract.types import AutoModel
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class FilingFinancialSnapshotSchema(BaseModel):
+ """
+ 从 SEC 申报文件中提取的关键财务数据结构化快照。
+ """
+
+ company_name: Optional[str] = Field(
+ None, description="申报实体的法定名称。"
+ )
+ ticker: Optional[str] = Field(
+ None, description="股票代码(例如 'AAPL'、'MSFT')。"
+ )
+ filing_type: Optional[str] = Field(
+ None, description="申报类型:'10-K'、'10-Q'、'8-K'、'20-F'。"
+ )
+ filing_period: Optional[str] = Field(
+ None,
+ description="涵盖的财务期间(例如 'FY2024'、'Q3 2024'、'截至2024年12月31日的年度')。",
+ )
+ revenue: Optional[str] = Field(
+ None,
+ description="该期间的总营收或净销售额(例如 '3943亿美元')。",
+ )
+ cost_of_revenue: Optional[str] = Field(
+ None, description="销售成本或营业成本。"
+ )
+ gross_profit: Optional[str] = Field(
+ None, description="毛利润(营收减去营业成本)。"
+ )
+ operating_income: Optional[str] = Field(
+ None, description="营业利润或营业亏损。"
+ )
+ net_income: Optional[str] = Field(
+ None, description="归属于普通股股东的净利润。"
+ )
+ earnings_per_share: Optional[str] = Field(
+ None, description="稀释每股收益(例如 '$6.13')。"
+ )
+ total_assets: Optional[str] = Field(
+ None, description="资产负债表上的总资产。"
+ )
+ total_liabilities: Optional[str] = Field(
+ None, description="资产负债表上的总负债。"
+ )
+ shareholders_equity: Optional[str] = Field(
+ None, description="股东权益合计。"
+ )
+ cash_and_equivalents: Optional[str] = Field(
+ None, description="现金及现金等价物。"
+ )
+ operating_cash_flow: Optional[str] = Field(
+ None, description="经营活动产生的现金流量净额。"
+ )
+ capital_expenditures: Optional[str] = Field(
+ None, description="资本支出(CapEx)。"
+ )
+ free_cash_flow: Optional[str] = Field(
+ None, description="自由现金流(经营性现金流减去资本支出)。"
+ )
+ dividends_per_share: Optional[str] = Field(
+ None, description="每股已宣派股息。"
+ )
+ shares_outstanding: Optional[str] = Field(
+ None, description="加权平均稀释流通股数。"
+ )
+ key_ratios: Optional[List[str]] = Field(
+ None,
+ description="提及的主要财务比率(例如 '毛利率:45.6%'、'资产负债率:1.2倍')。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位专精于 SEC 申报文件分析的财务分析专家。"
+ "从本申报文件中嵌入的利润表、资产负债表和现金流量表中提取关键财务数据。\n\n"
+ "规则:\n"
+ "- 按报告原文提取精确的金额数据,保留单位(百万、十亿)。\n"
+ "- 识别申报实体、股票代码、申报类型和财务期间。\n"
+ "- 在可获取时同时提取最近期间和前期对比数据。\n"
+ "- 捕获申报文件中明确列出的关键财务比率。\n"
+ "- 使用表格中的精确数据;除非文件明确给出,否则不要计算衍生数值。\n\n"
+ "### 源文本:\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class FilingFinancialSnapshot(AutoModel[FilingFinancialSnapshotSchema]):
+ """
+ 适用文档: SEC 10-K 年度报告、10-Q 季度报告、20-F 外国发行人年报、
+ 包含嵌入式财务报表的年度报告。
+
+ 模板用于从 SEC 申报文件中提取合并财务数据快照。
+ 将利润表、资产负债表和现金流量表中的财务数据跨多个章节合并为单一结构化对象。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> snapshot = FilingFinancialSnapshot(llm_client=llm, embedder=embedder)
+ >>> filing_text = "第8项 财务报表:营收为3943亿美元..."
+ >>> snapshot.feed_text(filing_text)
+ >>> print(snapshot.data)
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化财报财务快照模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于财务数据提取的 LLM。
+ embedder (Embeddings): 用于索引的嵌入模型。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoModel 的其他参数。
+ """
+ super().__init__(
+ data_schema=FilingFinancialSnapshotSchema,
+ llm_client=llm_client,
+ embedder=embedder,
+ strategy_or_merger=MergeStrategy.LLM.BALANCED,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
diff --git a/hyperextract/templates/zh/finance/filing_risk_factor_set.py b/hyperextract/templates/zh/finance/filing_risk_factor_set.py
new file mode 100644
index 0000000..799bd34
--- /dev/null
+++ b/hyperextract/templates/zh/finance/filing_risk_factor_set.py
@@ -0,0 +1,145 @@
+"""申报风险因素集 - 对 SEC 申报文件中的风险因素进行去重和归类。
+
+从 10-K/10-Q 申报文件的第1A项中提取并规范化风险因素披露,
+跟踪不同申报期间的新增和删除,用于风险演变监控。
+"""
+
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoSet
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class RiskFactorItem(BaseModel):
+ """
+ SEC 申报文件中披露的单项风险因素。
+ """
+
+ risk_title: str = Field(
+ description="风险因素的简明标题(例如 '网络安全漏洞风险'、'外汇敞口')。"
+ )
+ risk_category: str = Field(
+ description="类别:'市场'、'运营'、'监管'、'财务'、'战略'、'网络安全'、'ESG'、'法律'、'地缘政治'。"
+ )
+ description: str = Field(
+ description="申报文件中披露的风险完整描述。"
+ )
+ potential_impact: Optional[str] = Field(
+ None,
+ description="所述的潜在财务或运营影响(例如 '对营收产生重大不利影响')。",
+ )
+ affected_areas: Optional[List[str]] = Field(
+ None,
+ description="受影响的业务板块或职能(例如 ['国际业务', '供应链'])。",
+ )
+ mitigation_disclosed: Optional[str] = Field(
+ None,
+ description="公司已披露的任何缓解措施或管控手段。",
+ )
+ is_new: Optional[bool] = Field(
+ None,
+ description="与前期申报相比,该风险因素是否为新增。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位专精于风险披露分析的监管申报分析师。"
+ "从 SEC 申报文件的第1A项(风险因素)或等效风险披露章节中提取并归类所有单项风险因素。\n\n"
+ "提取原则:\n"
+ "1. **规范化**: 将相关的风险描述归纳到一个简明的风险标题下。\n"
+ "2. **分类**: 将每项风险归入其主要类别。\n"
+ "3. **完整性**: 提取每一个不同的风险因素,即使只是简要提及。\n"
+ "4. **累积合并**: 如果同一风险在不同章节中出现了更多细节,则合并相关信息。"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class FilingRiskFactorSet(AutoSet[RiskFactorItem]):
+ """
+ 适用文档: SEC 10-K 第1A项(风险因素)、10-Q 风险因素更新、
+ S-1 招股说明书风险章节、20-F 风险披露。
+
+ 模板用于从监管申报文件中构建去重的风险因素注册表。
+ 利用 AutoSet 的键值累积机制,将不同章节或不同申报期间的风险披露合并为
+ 全面的风险目录。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> risk_set = FilingRiskFactorSet(llm_client=llm, embedder=embedder)
+ >>> filing = "第1A项 风险因素:我们面临重大网络安全风险..."
+ >>> risk_set.feed_text(filing)
+ >>> risk_set.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化申报风险因素集模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于风险因素提取的 LLM。
+ embedder (Embeddings): 用于检索的嵌入模型。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoSet 的其他参数。
+ """
+ super().__init__(
+ item_schema=RiskFactorItem,
+ key_extractor=lambda x: x.risk_title.strip().lower(),
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """
+ 可视化风险因素注册表。
+
+ Args:
+ top_k_for_search (int): 检索的条目数。默认 3。
+ top_k_for_chat (int): 对话上下文中的条目数。默认 3。
+ """
+
+ def item_label_extractor(item: RiskFactorItem) -> str:
+ return f"[{item.risk_category}] {item.risk_title}"
+
+ super().show(
+ item_label_extractor=item_label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )
diff --git a/hyperextract/templates/zh/finance/material_event_timeline.py b/hyperextract/templates/zh/finance/material_event_timeline.py
new file mode 100644
index 0000000..f076c38
--- /dev/null
+++ b/hyperextract/templates/zh/finance/material_event_timeline.py
@@ -0,0 +1,203 @@
+"""重大事件时间线 - 从 8-K 申报文件中按时间顺序提取重大事件。
+
+提取高管变动、并购公告、财务重述及其他重大事件,
+按时间排序,用于事件驱动分析和监管监控。
+"""
+
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoTemporalGraph
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class MaterialEventEntity(BaseModel):
+ """
+ 参与重大公司事件的实体。
+ """
+
+ name: str = Field(
+ description="实体名称(例如 公司名称、高管姓名、监管机构)。"
+ )
+ entity_type: str = Field(
+ description="类型:'公司'、'高管'、'监管机构'、'交易对手'、'子公司'、'审计师'。"
+ )
+ description: Optional[str] = Field(
+ None, description="角色或背景(例如 '首席执行官'、'收购方'、'SEC')。"
+ )
+
+
+class MaterialEventEdge(BaseModel):
+ """
+ 连接实体的重大事件及其时间背景。
+ """
+
+ source: str = Field(description="行为实体名称。")
+ target: str = Field(description="受影响实体名称。")
+ event_type: str = Field(
+ description="类型:'高管任命'、'高管离职'、'收购'、'资产剥离'、"
+ "'财务重述'、'破产'、'退市'、'重大协议'、'股息宣派'、"
+ "'股票拆分'、'监管行动'。"
+ )
+ start_timestamp: Optional[str] = Field(
+ None,
+ description="事件发生或公告的日期(例如 '2024-03-15'、'2024年3月15日')。",
+ )
+ end_timestamp: Optional[str] = Field(
+ None,
+ description="如适用的结束日期(例如 生效日期、交割日期)。",
+ )
+ description: Optional[str] = Field(
+ None,
+ description="重大事件的详细信息,包括财务条款、条件或监管背景。",
+ )
+ sec_item: Optional[str] = Field(
+ None,
+ description="8-K 条目编号(例如 'Item 5.02'、'Item 1.01'、'Item 2.01')。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位专精于 8-K 即时报告和重大事件披露的监管申报分析师。"
+ "提取参与重大事件的实体及其之间的时序关系。\n\n"
+ "规则:\n"
+ "- 识别涉及的公司、高管、监管机构和交易对手。\n"
+ "- 提取每个重大事件及其具体日期。\n"
+ "- 在可获取时按 8-K 条目编号对事件进行分类。\n"
+ "- 捕获财务条款、条件和监管背景。\n"
+ "- 保持时间顺序的准确性。"
+)
+
+_NODE_PROMPT = (
+ "你是一位监管申报分析师。提取参与重大事件的所有实体(节点)。\n\n"
+ "提取规则:\n"
+ "- 识别公司、高管、监管机构、审计师和交易对手。\n"
+ "- 按类型对每个实体进行分类。\n"
+ "- 捕获角色描述。\n"
+ "- 此阶段不提取事件或关系。"
+)
+
+_EDGE_PROMPT = (
+ "你是一位监管申报分析师。在获得实体清单的基础上,提取所有带日期的重大事件(边)。\n\n"
+ "提取规则:\n"
+ "- 通过重大事件连接实体。\n"
+ "- 提取每个事件的具体日期。\n"
+ "- 按事件类型和 8-K 条目编号进行分类。\n"
+ "- 捕获财务条款和条件。\n"
+ "- 仅在提供的列表中存在的节点之间创建边。"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class MaterialEventTimeline(AutoTemporalGraph[MaterialEventEntity, MaterialEventEdge]):
+ """
+ 适用文档: SEC 8-K 即时报告、重大事件披露、
+ 8-K 附带的新闻稿、委托声明书(DEF 14A)。
+
+ 模板用于从 8-K 申报文件及相关披露中按时间顺序提取重大公司事件。
+ 支持事件驱动分析、监管监控和公司治理跟踪。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> timeline = MaterialEventTimeline(llm_client=llm, embedder=embedder)
+ >>> filing = "Item 5.02:2024年3月15日,董事会任命张三为首席执行官..."
+ >>> timeline.feed_text(filing)
+ >>> timeline.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ observation_time: str = "2024-01-01",
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化重大事件时间线模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于事件提取的 LLM。
+ embedder (Embeddings): 用于去重的嵌入模型。
+ observation_time (str): 用于解析相对日期的参考时间。
+ extraction_mode (str): "one_stage" 或 "two_stage"。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoTemporalGraph 的其他参数。
+ """
+ super().__init__(
+ node_schema=MaterialEventEntity,
+ edge_schema=MaterialEventEdge,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip().lower()}|{x.event_type.lower()}|{x.target.strip().lower()}"
+ ),
+ time_in_edge_extractor=lambda x: x.start_timestamp or "",
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ observation_time=observation_time,
+ extraction_mode=extraction_mode,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """
+ 使用 OntoSight 可视化重大事件时间线。
+
+ Args:
+ top_k_nodes_for_search (int): 检索的实体数。默认 3。
+ top_k_edges_for_search (int): 检索的事件数。默认 3。
+ top_k_nodes_for_chat (int): 对话上下文中的实体数。默认 3。
+ top_k_edges_for_chat (int): 对话上下文中的事件数。默认 3。
+ """
+
+ def node_label_extractor(node: MaterialEventEntity) -> str:
+ return f"{node.name} ({node.entity_type})"
+
+ def edge_label_extractor(edge: MaterialEventEdge) -> str:
+ date = f" [{edge.start_timestamp}]" if edge.start_timestamp else ""
+ return f"{edge.event_type}{date}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/zh/finance/mda_narrative_graph.py b/hyperextract/templates/zh/finance/mda_narrative_graph.py
new file mode 100644
index 0000000..dfccb88
--- /dev/null
+++ b/hyperextract/templates/zh/finance/mda_narrative_graph.py
@@ -0,0 +1,189 @@
+"""管理层讨论与分析叙述图谱 - 从管理层讨论与分析中提取因果关系。
+
+映射 SEC 申报文件 MD&A 部分中从业务驱动因素到财务结果的因果链
+(例如"供应链中断 -> 营收下降 -> 利润率压缩")。
+"""
+
+from typing import Optional, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoGraph
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class MDAFactor(BaseModel):
+ """
+ MD&A 中提及的业务驱动因素、财务结果或运营因素。
+ """
+
+ name: str = Field(
+ description="因素名称(例如 '供应链中断'、'营收增长'、'利润率压缩')。"
+ )
+ factor_type: str = Field(
+ description="类型:'业务驱动因素'、'财务结果'、'运营因素'、'战略举措'、'外部因素'。"
+ )
+ description: Optional[str] = Field(
+ None,
+ description="管理层对该因素的解释或背景说明。",
+ )
+
+
+class MDANarrativeEdge(BaseModel):
+ """
+ 两个 MD&A 因素之间的因果或解释性关系。
+ """
+
+ source: str = Field(description="原因或驱动因素名称。")
+ target: str = Field(description="结果或影响因素名称。")
+ relationship_type: str = Field(
+ description="类型:'导致'、'促成'、'被抵消'、'引发'、'带来'、'被缓解'。"
+ )
+ magnitude: Optional[str] = Field(
+ None,
+ description="如有提及的量化影响(例如 '增加了23亿美元'、'300个基点')。",
+ )
+ management_attribution: Optional[str] = Field(
+ None,
+ description="管理层自身的因果解释原文或转述。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位专精于 SEC 申报文件 MD&A(管理层讨论与分析)部分的财务分析师。"
+ "提取管理层描述的业务驱动因素、财务结果及其之间的因果关系。\n\n"
+ "规则:\n"
+ "- 识别管理层讨论的各类因素:营收驱动因素、成本压力、战略变化、外部力量。\n"
+ "- 按管理层呈现的方式提取因果链(例如 '需求增长带动了营收增长')。\n"
+ "- 在有说明时捕获量化影响。\n"
+ "- 保留管理层的归因表述语言。"
+)
+
+_NODE_PROMPT = (
+ "你是一位财务分析师。从 MD&A 文本中提取所有业务驱动因素、财务结果和运营因素(节点)。\n\n"
+ "提取规则:\n"
+ "- 识别营收驱动因素、成本因素、战略举措和外部力量。\n"
+ "- 识别财务结果(营收变化、利润率变动、现金流影响)。\n"
+ "- 按类型对每个因素进行分类。\n"
+ "- 此阶段不建立因果关系。"
+)
+
+_EDGE_PROMPT = (
+ "你是一位财务分析师。在获得 MD&A 因素清单的基础上,提取管理层描述的因果和解释性关系(边)。\n\n"
+ "提取规则:\n"
+ "- 按管理层呈现的方式将原因与结果连接。\n"
+ "- 分类关系类型(导致、促成、被抵消等)。\n"
+ "- 在可获取时提取量化幅度。\n"
+ "- 捕获管理层自身的因果解释。\n"
+ "- 仅在提供的列表中存在的节点之间创建边。"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class MDANarrativeGraph(AutoGraph[MDAFactor, MDANarrativeEdge]):
+ """
+ 适用文档: SEC 10-K/10-Q 第7项(管理层讨论与分析)、
+ 年度报告 MD&A 部分、中期管理报告。
+
+ 模板用于从管理层讨论与分析部分提取因果关系。映射管理层如何解释业务绩效驱动因素
+ 及其对财务的影响,支持叙述分析和驱动因素归因。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> mda = MDANarrativeGraph(llm_client=llm, embedder=embedder)
+ >>> text = "营收增长12%,主要受益于云计算业务的强劲需求..."
+ >>> mda.feed_text(text)
+ >>> mda.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "one_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化管理层讨论与分析叙述图谱模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于因果关系提取的 LLM。
+ embedder (Embeddings): 用于去重的嵌入模型。
+ extraction_mode (str): "one_stage" 或 "two_stage"。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoGraph 的其他参数。
+ """
+ super().__init__(
+ node_schema=MDAFactor,
+ edge_schema=MDANarrativeEdge,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip().lower()}--({x.relationship_type})-->{x.target.strip().lower()}"
+ ),
+ nodes_in_edge_extractor=lambda x: (x.source.strip(), x.target.strip()),
+ llm_client=llm_client,
+ embedder=embedder,
+ extraction_mode=extraction_mode,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ prompt=_PROMPT,
+ prompt_for_node_extraction=_NODE_PROMPT,
+ prompt_for_edge_extraction=_EDGE_PROMPT,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_nodes_for_search: int = 3,
+ top_k_edges_for_search: int = 3,
+ top_k_nodes_for_chat: int = 3,
+ top_k_edges_for_chat: int = 3,
+ ) -> None:
+ """
+ 使用 OntoSight 可视化 MD&A 叙述图谱。
+
+ Args:
+ top_k_nodes_for_search (int): 检索的因素数。默认 3。
+ top_k_edges_for_search (int): 检索的因果关系数。默认 3。
+ top_k_nodes_for_chat (int): 对话上下文中的因素数。默认 3。
+ top_k_edges_for_chat (int): 对话上下文中的因果关系数。默认 3。
+ """
+
+ def node_label_extractor(node: MDAFactor) -> str:
+ return f"{node.name} ({node.factor_type})"
+
+ def edge_label_extractor(edge: MDANarrativeEdge) -> str:
+ mag = f" [{edge.magnitude}]" if edge.magnitude else ""
+ return f"{edge.relationship_type}{mag}"
+
+ super().show(
+ node_label_extractor=node_label_extractor,
+ edge_label_extractor=edge_label_extractor,
+ top_k_nodes_for_search=top_k_nodes_for_search,
+ top_k_edges_for_search=top_k_edges_for_search,
+ top_k_nodes_for_chat=top_k_nodes_for_chat,
+ top_k_edges_for_chat=top_k_edges_for_chat,
+ )
diff --git a/hyperextract/templates/zh/finance/segment_performance_list.py b/hyperextract/templates/zh/finance/segment_performance_list.py
new file mode 100644
index 0000000..e17e1a6
--- /dev/null
+++ b/hyperextract/templates/zh/finance/segment_performance_list.py
@@ -0,0 +1,145 @@
+"""业务板块业绩列表 - 按业务板块提取营收和关键指标。
+
+从 SEC 申报文件中按业务板块或地理区域提取营收、营业利润和关键指标,
+用于板块层面的估值和敞口分析。
+"""
+
+from typing import Optional, List, Any
+from pydantic import BaseModel, Field
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.embeddings import Embeddings
+from hyperextract.types import AutoList
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class SegmentPerformanceItem(BaseModel):
+ """
+ 单个业务板块或地理区域的业绩数据。
+ """
+
+ segment_name: str = Field(
+ description="业务板块或地理区域名称(例如 '美洲'、'云服务'、'iPhone')。"
+ )
+ segment_type: str = Field(
+ description="类型:'业务板块'、'地理区域'、'产品线'、'经营分部'。"
+ )
+ revenue: Optional[str] = Field(
+ None, description="该期间的板块营收(例如 '482亿美元')。"
+ )
+ operating_income: Optional[str] = Field(
+ None, description="板块营业利润或经营利润。"
+ )
+ revenue_growth: Optional[str] = Field(
+ None,
+ description="同比或环比营收增长率(例如 '+12%'、'-3% 同比')。",
+ )
+ key_metrics: Optional[List[str]] = Field(
+ None,
+ description="板块特定的关键绩效指标(例如 ['订阅用户:2.3亿', 'ARPU:$14.99', '流失率:2.1%'])。",
+ )
+ commentary: Optional[str] = Field(
+ None,
+ description="管理层对板块业绩或展望的评论。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一位专精于板块层面分析的财务分析师。"
+ "从 SEC 申报文件中提取每个业务板块或地理区域的业绩数据。\n\n"
+ "规则:\n"
+ "- 提取每个可识别板块的营收和营业利润。\n"
+ "- 捕获增长率和与前期的对比数据。\n"
+ "- 提取板块特定的关键绩效指标和度量。\n"
+ "- 保留管理层的板块评论。\n"
+ "- 将每个板块作为独立条目分别提取。\n\n"
+ "### 源文本:\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class SegmentPerformanceList(AutoList[SegmentPerformanceItem]):
+ """
+ 适用文档: SEC 10-K/10-Q 分部披露(ASC 280)、年度报告、
+ 包含分部明细的业绩公告。
+
+ 模板用于从申报文件中提取板块层面的财务业绩数据。
+ 每个板块作为独立的列表条目捕获,用于对比分析和板块层面估值。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> segments = SegmentPerformanceList(llm_client=llm, embedder=embedder)
+ >>> filing = "美洲地区板块营收为482亿美元,同比增长12%..."
+ >>> segments.feed_text(filing)
+ >>> segments.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ 初始化业务板块业绩列表模板。
+
+ Args:
+ llm_client (BaseChatModel): 用于板块数据提取的 LLM。
+ embedder (Embeddings): 用于索引的嵌入模型。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoList 的其他参数。
+ """
+ super().__init__(
+ item_schema=SegmentPerformanceItem,
+ llm_client=llm_client,
+ embedder=embedder,
+ prompt=_PROMPT,
+ chunk_size=chunk_size,
+ chunk_overlap=chunk_overlap,
+ max_workers=max_workers,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def show(
+ self,
+ *,
+ top_k_for_search: int = 3,
+ top_k_for_chat: int = 3,
+ ) -> None:
+ """
+ 可视化业务板块业绩列表。
+
+ Args:
+ top_k_for_search (int): 检索的条目数。默认 3。
+ top_k_for_chat (int): 对话上下文中的条目数。默认 3。
+ """
+
+ def label_extractor(item: SegmentPerformanceItem) -> str:
+ rev = f" | {item.revenue}" if item.revenue else ""
+ return f"{item.segment_name} ({item.segment_type}){rev}"
+
+ super().show(
+ item_label_extractor=label_extractor,
+ top_k_for_search=top_k_for_search,
+ top_k_for_chat=top_k_for_chat,
+ )