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 Equity Research Reports templates - ResearchNoteSummary (AutoModel) - ratings & target prices - FinancialForecast (AutoList) - revenue/EPS projections - ValuationLogicMap (AutoGraph) - valuation driver chains - FactorInfluenceHypergraph (AutoHypergraph) - multi-factor analysis - RiskFactorList (AutoList) - downside risks

yuxizhee4f0532a93d0
diff --git a/hyperextract/templates/en/finance/factor_influence_hypergraph.py b/hyperextract/templates/en/finance/factor_influence_hypergraph.py
new file mode 100644
index 0000000..eda97ff
--- /dev/null
+++ b/hyperextract/templates/en/finance/factor_influence_hypergraph.py
@@ -0,0 +1,200 @@
+"""Factor Influence Hypergraph - Models multi-factor relationships in equity analysis.
+
+Models complex relationships between macro factors, industry trends, and company
+metrics as hyperedges connecting multiple factors simultaneously.
+"""
+
+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 AutoHypergraph
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class InvestmentFactor(BaseModel):
+ """
+ A factor in multi-factor investment analysis.
+ """
+
+ name: str = Field(
+ description="Name of the factor (e.g., 'GDP Growth', 'Semiconductor Cycle', 'Cloud Revenue')."
+ )
+ factor_level: str = Field(
+ description="Level: 'Macro', 'Industry', 'Company', 'Technical'."
+ )
+ current_reading: Optional[str] = Field(
+ None,
+ description="Current value or state (e.g., '3.2% YoY', 'Upcycle Phase', 'Accelerating').",
+ )
+ description: Optional[str] = Field(
+ None, description="Explanation of this factor's significance."
+ )
+
+
+class FactorInteraction(BaseModel):
+ """
+ A multi-factor interaction where several factors jointly influence an outcome.
+ """
+
+ interaction_name: str = Field(
+ description="Descriptive name (e.g., 'AI Capex Multiplier Effect', 'Rate-Sensitive Rotation')."
+ )
+ participating_factors: List[str] = Field(
+ description="Names of all factors involved in this interaction."
+ )
+ interaction_type: str = Field(
+ description="Type: 'Reinforcing', 'Offsetting', 'Conditional', 'Cascading', 'Threshold'."
+ )
+ outcome: str = Field(
+ description="The combined outcome or effect (e.g., 'Accelerated revenue growth for cloud names')."
+ )
+ mechanism: Optional[str] = Field(
+ None,
+ description="How the factors interact to produce the outcome.",
+ )
+ confidence: Optional[str] = Field(
+ None,
+ description="Analyst's confidence in this interaction: 'High', 'Medium', 'Low'.",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a quantamental research analyst. Extract investment factors and their multi-factor "
+ "interactions from this research report.\n\n"
+ "Rules:\n"
+ "- Identify macro, industry, and company-level factors.\n"
+ "- Extract complex interactions where multiple factors jointly produce an outcome.\n"
+ "- A hyperedge connects ALL participating factors, not just pairs.\n"
+ "- Capture the mechanism and outcome of each interaction."
+)
+
+_NODE_PROMPT = (
+ "You are a quantamental research analyst. Extract all investment factors (Nodes).\n\n"
+ "Extraction Rules:\n"
+ "- Identify macro indicators, industry metrics, and company KPIs.\n"
+ "- Capture current values or readings.\n"
+ "- Classify each factor by level.\n"
+ "- DO NOT extract interactions at this stage."
+)
+
+_EDGE_PROMPT = (
+ "You are a quantamental research analyst. Given the factors, extract multi-factor "
+ "interactions (Hyperedges) where multiple factors jointly influence outcomes.\n\n"
+ "Extraction Rules:\n"
+ "- Each hyperedge should connect 2 or more factors.\n"
+ "- Describe the interaction mechanism and outcome.\n"
+ "- Classify the interaction type.\n"
+ "- Only reference factors that exist in the provided lists."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class FactorInfluenceHypergraph(AutoHypergraph[InvestmentFactor, FactorInteraction]):
+ """
+ Applicable to: Multi-Factor Research Reports, Quantamental Analysis,
+ Macro Strategy Notes, Cross-Asset Research, Factor Attribution Studies.
+
+ Template for modeling complex multi-factor relationships in equity analysis.
+ Uses hyperedges to capture interactions where multiple factors jointly influence
+ an outcome, going beyond simple pairwise relationships.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> factors = FactorInfluenceHypergraph(llm_client=llm, embedder=embedder)
+ >>> report = "Rising rates combined with strong GDP and AI capex create a rotation into quality growth..."
+ >>> factors.feed_text(report)
+ >>> factors.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ extraction_mode: str = "two_stage",
+ chunk_size: int = 2048,
+ chunk_overlap: int = 256,
+ max_workers: int = 10,
+ verbose: bool = False,
+ **kwargs: Any,
+ ):
+ """
+ Initialize the Factor Influence Hypergraph template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for factor 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 AutoHypergraph.
+ """
+ super().__init__(
+ node_schema=InvestmentFactor,
+ edge_schema=FactorInteraction,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: x.interaction_name.strip().lower(),
+ nodes_in_edge_extractor=lambda x: tuple(
+ f.strip().lower() for f in x.participating_factors
+ ),
+ llm_client=llm_client,
+ embedder=embedder,
+ 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 factor influence hypergraph using OntoSight.
+
+ Args:
+ top_k_nodes_for_search (int): Number of factors to retrieve. Default 3.
+ top_k_edges_for_search (int): Number of interactions to retrieve. Default 3.
+ top_k_nodes_for_chat (int): Factors for chat context. Default 3.
+ top_k_edges_for_chat (int): Interactions for chat context. Default 3.
+ """
+
+ def node_label_extractor(node: InvestmentFactor) -> str:
+ reading = f": {node.current_reading}" if node.current_reading else ""
+ return f"{node.name} [{node.factor_level}]{reading}"
+
+ def edge_label_extractor(edge: FactorInteraction) -> str:
+ return f"[{edge.interaction_type}] {edge.interaction_name}"
+
+ 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/financial_forecast.py b/hyperextract/templates/en/finance/financial_forecast.py
new file mode 100644
index 0000000..7f505bf
--- /dev/null
+++ b/hyperextract/templates/en/finance/financial_forecast.py
@@ -0,0 +1,147 @@
+"""Financial Forecast - Extracts projected financial data from equity research reports.
+
+Extracts revenue, EPS, PE, and other financial projections for future periods
+from analyst reports for consensus analysis and financial modeling.
+"""
+
+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 ForecastItem(BaseModel):
+ """
+ A single financial projection for a specific metric and period.
+ """
+
+ metric: str = Field(
+ description="Financial metric being projected (e.g., 'Revenue', 'EPS', 'EBITDA', 'Operating Margin', 'Free Cash Flow')."
+ )
+ period: str = Field(
+ description="Forecast period (e.g., 'FY2025E', 'Q1 2025E', 'CY2026E')."
+ )
+ estimate: str = Field(
+ description="Projected value (e.g., '$120.5B', '$6.25', '35.2%')."
+ )
+ prior_estimate: Optional[str] = Field(
+ None, description="Previous estimate if revised (e.g., '$115.0B')."
+ )
+ consensus: Optional[str] = Field(
+ None, description="Street consensus estimate for comparison (e.g., '$118.2B')."
+ )
+ growth_rate: Optional[str] = Field(
+ None,
+ description="Implied growth rate (e.g., '+15% YoY', 'flat').",
+ )
+ assumptions: Optional[str] = Field(
+ None,
+ description="Key assumptions underlying the estimate (e.g., 'assumes 5M unit increase').",
+ )
+ source_firm: Optional[str] = Field(
+ None, description="Research firm providing the estimate."
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a financial analyst building earnings models. Extract all financial projections "
+ "and estimates from this equity research report.\n\n"
+ "Rules:\n"
+ "- Extract every projected metric with its specific time period.\n"
+ "- Capture both current and prior estimates when revisions are noted.\n"
+ "- Extract consensus estimates when compared.\n"
+ "- Capture growth rates and key assumptions.\n"
+ "- Extract EVERY forecast independently as a separate item.\n\n"
+ "### Source Text:\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class FinancialForecast(AutoList[ForecastItem]):
+ """
+ Applicable to: Equity Research Reports, Earnings Estimates, Financial Models,
+ Consensus Estimate Reports, Analyst Forecasts.
+
+ Template for extracting projected financial data from analyst reports. Each
+ forecast is captured as an independent list item, enabling consensus analysis,
+ estimate revision tracking, and financial model building.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> forecast = FinancialForecast(llm_client=llm, embedder=embedder)
+ >>> report = "We raise our FY2025 revenue estimate to $120.5B (from $115B)..."
+ >>> forecast.feed_text(report)
+ >>> forecast.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 Financial Forecast template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for estimate 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=ForecastItem,
+ 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 financial forecast 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: ForecastItem) -> str:
+ return f"{item.metric} ({item.period}): {item.estimate}"
+
+ 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/en/finance/research_note_summary.py b/hyperextract/templates/en/finance/research_note_summary.py
new file mode 100644
index 0000000..23b5a0b
--- /dev/null
+++ b/hyperextract/templates/en/finance/research_note_summary.py
@@ -0,0 +1,149 @@
+"""Research Note Summary - Extracts core investment thesis from equity research reports.
+
+Extracts ratings, target prices, and top-level investment logic from analyst research
+notes for report database population and screening.
+"""
+
+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 ResearchNoteSummarySchema(BaseModel):
+ """
+ Structured summary of an equity research report.
+ """
+
+ company_name: Optional[str] = Field(
+ None, description="Name of the covered company."
+ )
+ ticker: Optional[str] = Field(
+ None, description="Stock ticker symbol (e.g., 'AAPL', 'NVDA')."
+ )
+ analyst_name: Optional[str] = Field(
+ None, description="Name of the lead analyst."
+ )
+ research_firm: Optional[str] = Field(
+ None, description="Name of the research firm (e.g., 'Goldman Sachs', 'Morgan Stanley')."
+ )
+ report_date: Optional[str] = Field(
+ None, description="Publication date of the report."
+ )
+ rating: Optional[str] = Field(
+ None,
+ description="Analyst rating: 'Buy', 'Overweight', 'Hold', 'Neutral', 'Sell', 'Underweight'.",
+ )
+ prior_rating: Optional[str] = Field(
+ None, description="Previous rating if changed."
+ )
+ target_price: Optional[str] = Field(
+ None, description="Current price target (e.g., '$150.00')."
+ )
+ prior_target_price: Optional[str] = Field(
+ None, description="Previous price target if changed."
+ )
+ current_price: Optional[str] = Field(
+ None, description="Stock price at time of report."
+ )
+ investment_thesis: Optional[str] = Field(
+ None,
+ description="Core investment thesis or key argument for the rating.",
+ )
+ key_catalysts: Optional[List[str]] = Field(
+ None,
+ description="Near-term catalysts identified (e.g., ['Q4 earnings beat', 'New product launch', 'Regulatory approval']).",
+ )
+ key_risks: Optional[List[str]] = Field(
+ None,
+ description="Key risks highlighted by the analyst.",
+ )
+ revenue_estimate: Optional[str] = Field(
+ None, description="Analyst's revenue estimate for the current/next fiscal year."
+ )
+ eps_estimate: Optional[str] = Field(
+ None, description="Analyst's EPS estimate for the current/next fiscal year."
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an equity research analyst. Extract the core investment thesis, rating, target price, "
+ "and key arguments from this research report.\n\n"
+ "Rules:\n"
+ "- Extract the analyst's rating and any rating changes.\n"
+ "- Capture target price and prior target price if changed.\n"
+ "- Summarize the core investment thesis concisely.\n"
+ "- List key catalysts and risks as identified by the analyst.\n"
+ "- Extract financial estimates (revenue, EPS) when stated.\n\n"
+ "### Source Text:\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class ResearchNoteSummary(AutoModel[ResearchNoteSummarySchema]):
+ """
+ Applicable to: Equity Research Reports, Analyst Notes, Rating Changes,
+ Initiation of Coverage reports, Sector Research.
+
+ Template for extracting the core investment thesis and key parameters from
+ equity research reports. Produces a single structured summary per report for
+ database population and screening.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> summary = ResearchNoteSummary(llm_client=llm, embedder=embedder)
+ >>> report = "We upgrade AAPL to Buy with a $200 price target..."
+ >>> summary.feed_text(report)
+ >>> print(summary.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 Research Note Summary template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for report 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=ResearchNoteSummarySchema,
+ 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/risk_factor_list.py b/hyperextract/templates/en/finance/risk_factor_list.py
new file mode 100644
index 0000000..fe0c021
--- /dev/null
+++ b/hyperextract/templates/en/finance/risk_factor_list.py
@@ -0,0 +1,142 @@
+"""Risk Factor List - Extracts downside risks from equity research reports.
+
+Lists specific downside risks identified by analysts including regulatory,
+FX, supply chain, and other risk categories for risk 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 AutoList
+
+# ==============================================================================
+# 1. Schema Definitions
+# ==============================================================================
+
+
+class RiskItem(BaseModel):
+ """
+ A specific downside risk identified in equity research.
+ """
+
+ risk_name: str = Field(
+ description="Concise name of the risk (e.g., 'Regulatory Tightening in EU', 'FX Headwinds from Strong Dollar')."
+ )
+ risk_category: str = Field(
+ description="Category: 'Regulatory', 'Competitive', 'Macroeconomic', 'Operational', 'FX/Currency', "
+ "'Geopolitical', 'Technology', 'Legal/Litigation', 'ESG', 'Execution'."
+ )
+ description: str = Field(
+ description="Detailed description of the risk scenario."
+ )
+ potential_impact: Optional[str] = Field(
+ None,
+ description="Estimated financial impact (e.g., '3-5% revenue downside', '$0.50 EPS risk').",
+ )
+ probability: Optional[str] = Field(
+ None,
+ description="Analyst's probability assessment: 'High', 'Medium', 'Low'.",
+ )
+ time_horizon: Optional[str] = Field(
+ None,
+ description="When the risk could materialize (e.g., 'Near-term', '2025', '12-18 months').",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are a risk analyst reviewing equity research reports. Extract all downside risks "
+ "and risk factors identified by the analyst.\n\n"
+ "Rules:\n"
+ "- Extract every distinct risk factor mentioned.\n"
+ "- Categorize each risk appropriately.\n"
+ "- Capture quantified impact estimates when provided.\n"
+ "- Note probability assessments and time horizons.\n"
+ "- Extract EVERY risk independently as a separate item.\n\n"
+ "### Source Text:\n"
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class RiskFactorList(AutoList[RiskItem]):
+ """
+ Applicable to: Equity Research Reports (Risk Sections), Investment Committee Memos,
+ Portfolio Risk Assessments, Analyst Downgrade Notes.
+
+ Template for extracting downside risks from equity research. Each risk is captured
+ as an independent list item for risk monitoring and portfolio risk assessment.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> risks = RiskFactorList(llm_client=llm, embedder=embedder)
+ >>> report = "Key risks include: 1) EU Digital Markets Act compliance costs..."
+ >>> risks.feed_text(report)
+ >>> risks.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 Risk Factor List template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for risk 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=RiskItem,
+ 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 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: RiskItem) -> str:
+ return f"[{item.risk_category}] {item.risk_name}"
+
+ 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/en/finance/valuation_logic_map.py b/hyperextract/templates/en/finance/valuation_logic_map.py
new file mode 100644
index 0000000..62e1e1e
--- /dev/null
+++ b/hyperextract/templates/en/finance/valuation_logic_map.py
@@ -0,0 +1,194 @@
+"""Valuation Logic Map - Maps causal chains driving stock performance.
+
+Extracts the logical chain from business drivers to valuation conclusions as
+presented in equity research reports (e.g., New Market -> Growth -> Multiple Expansion).
+"""
+
+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 ValuationDriver(BaseModel):
+ """
+ A factor in the analyst's valuation logic chain.
+ """
+
+ name: str = Field(
+ description="Name of the valuation driver (e.g., 'Market Share Gains', 'Multiple Expansion', 'DCF Assumption')."
+ )
+ driver_type: str = Field(
+ description="Type: 'Fundamental', 'Valuation Metric', 'Growth Driver', 'Comparable', 'Discount Rate', 'Terminal Value'."
+ )
+ value: Optional[str] = Field(
+ None,
+ description="Quantified value or metric (e.g., '25x forward P/E', 'WACC 9.5%', '$15B TAM').",
+ )
+ description: Optional[str] = Field(
+ None,
+ description="Analyst's explanation of this driver's role in the valuation.",
+ )
+
+
+class ValuationEdge(BaseModel):
+ """
+ A causal link in the analyst's valuation logic.
+ """
+
+ source: str = Field(description="The cause or input driver name.")
+ target: str = Field(description="The effect or output driver name.")
+ logic: str = Field(
+ description="The analyst's reasoning connecting source to target "
+ "(e.g., 'higher cloud adoption drives recurring revenue growth')."
+ )
+ direction: str = Field(
+ description="Impact direction: 'Positive', 'Negative', 'Neutral'."
+ )
+ confidence: Optional[str] = Field(
+ None,
+ description="Analyst's conviction level: 'High', 'Medium', 'Low'.",
+ )
+
+
+# ==============================================================================
+# 2. Prompts
+# ==============================================================================
+
+_PROMPT = (
+ "You are an equity research analyst. Extract the valuation logic chain from this research report: "
+ "the causal reasoning from business fundamentals through to valuation conclusions.\n\n"
+ "Rules:\n"
+ "- Identify fundamental drivers, growth catalysts, and valuation metrics.\n"
+ "- Extract the causal chain from business drivers to target price.\n"
+ "- Capture the analyst's specific reasoning at each link.\n"
+ "- Note impact direction and conviction level."
+)
+
+_NODE_PROMPT = (
+ "You are an equity research analyst. Extract all valuation drivers and metrics (Nodes).\n\n"
+ "Extraction Rules:\n"
+ "- Identify fundamental drivers (revenue growth, market share, TAM).\n"
+ "- Identify valuation metrics (P/E, EV/EBITDA, DCF, comparable multiples).\n"
+ "- Capture quantified values when stated.\n"
+ "- DO NOT establish causal links at this stage."
+)
+
+_EDGE_PROMPT = (
+ "You are an equity research analyst. Given the valuation drivers, extract the logical "
+ "reasoning chain (Edges) that connects them.\n\n"
+ "Extraction Rules:\n"
+ "- Connect business drivers to financial outcomes to valuation conclusions.\n"
+ "- Capture the specific reasoning at each link.\n"
+ "- Note whether each link is positive, negative, or neutral.\n"
+ "- Only create edges between nodes that exist in the provided lists."
+)
+
+# ==============================================================================
+# 3. Template Class
+# ==============================================================================
+
+
+class ValuationLogicMap(AutoGraph[ValuationDriver, ValuationEdge]):
+ """
+ Applicable to: Equity Research Reports, Initiation Reports, Valuation Analysis,
+ Sum-of-Parts Analyses, DCF Model Summaries.
+
+ Template for mapping the causal chains in an analyst's valuation logic. Connects
+ business fundamentals to growth drivers to valuation metrics to target price,
+ enabling investment strategy mapping and thesis comparison.
+
+ Example Usage:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> valuation = ValuationLogicMap(llm_client=llm, embedder=embedder)
+ >>> report = "Cloud adoption drives recurring revenue, justifying a 30x forward P/E..."
+ >>> valuation.feed_text(report)
+ >>> valuation.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 Valuation Logic Map template.
+
+ Args:
+ llm_client (BaseChatModel): The LLM for valuation logic 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=ValuationDriver,
+ edge_schema=ValuationEdge,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip().lower()}--({x.direction})-->{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 valuation logic map using OntoSight.
+
+ Args:
+ top_k_nodes_for_search (int): Number of drivers to retrieve. Default 3.
+ top_k_edges_for_search (int): Number of logic links to retrieve. Default 3.
+ top_k_nodes_for_chat (int): Drivers for chat context. Default 3.
+ top_k_edges_for_chat (int): Logic links for chat context. Default 3.
+ """
+
+ def node_label_extractor(node: ValuationDriver) -> str:
+ val = f": {node.value}" if node.value else ""
+ return f"{node.name}{val}"
+
+ def edge_label_extractor(edge: ValuationEdge) -> str:
+ return f"[{edge.direction}] {edge.logic[:60]}"
+
+ 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/factor_influence_hypergraph.py b/hyperextract/templates/zh/finance/factor_influence_hypergraph.py
new file mode 100644
index 0000000..34a684e
--- /dev/null
+++ b/hyperextract/templates/zh/finance/factor_influence_hypergraph.py
@@ -0,0 +1,197 @@
+"""因子影响超图 - 建模股票分析中的多因子关系。
+
+将宏观因素、行业趋势和公司指标之间的复杂关系建模为
+同时连接多个因子的超边。
+"""
+
+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 AutoHypergraph
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class InvestmentFactor(BaseModel):
+ """
+ 多因子投资分析中的一个因子。
+ """
+
+ name: str = Field(
+ description="因子名称(例如 'GDP 增长'、'半导体周期'、'云计算收入')。"
+ )
+ factor_level: str = Field(
+ description="层级:'宏观'、'行业'、'公司'、'技术面'。"
+ )
+ current_reading: Optional[str] = Field(
+ None,
+ description="当前值或状态(例如 '同比 3.2%'、'上升周期'、'加速增长')。",
+ )
+ description: Optional[str] = Field(
+ None, description="该因子重要性的说明。"
+ )
+
+
+class FactorInteraction(BaseModel):
+ """
+ 多因子交互关系,多个因子共同影响一个结果。
+ """
+
+ interaction_name: str = Field(
+ description="交互关系的描述性名称(例如 'AI 资本支出乘数效应'、'利率敏感型轮动')。"
+ )
+ participating_factors: List[str] = Field(
+ description="参与此交互关系的所有因子名称。"
+ )
+ interaction_type: str = Field(
+ description="类型:'增强型'、'抵消型'、'条件型'、'级联型'、'阈值型'。"
+ )
+ outcome: str = Field(
+ description="综合结果或效应(例如 '云计算公司收入增长加速')。"
+ )
+ mechanism: Optional[str] = Field(
+ None,
+ description="各因子如何相互作用产生该结果的机制。",
+ )
+ confidence: Optional[str] = Field(
+ None,
+ description="分析师对此交互关系的确信度:'高'、'中等'、'低'。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一名量化基本面研究分析师。从本研究报告中提取投资因子及其多因子交互关系。\n\n"
+ "规则:\n"
+ "- 识别宏观、行业和公司层面的因子。\n"
+ "- 提取多个因子共同产生结果的复杂交互关系。\n"
+ "- 超边连接所有参与因子,而非仅成对连接。\n"
+ "- 捕获每个交互关系的机制和结果。"
+)
+
+_NODE_PROMPT = (
+ "你是一名量化基本面研究分析师。提取所有投资因子(节点)。\n\n"
+ "提取规则:\n"
+ "- 识别宏观指标、行业指标和公司关键绩效指标。\n"
+ "- 捕获当前值或读数。\n"
+ "- 按层级对每个因子进行分类。\n"
+ "- 此阶段不提取交互关系。"
+)
+
+_EDGE_PROMPT = (
+ "你是一名量化基本面研究分析师。在获得因子列表的基础上,提取多个因子共同影响结果的"
+ "多因子交互关系(超边)。\n\n"
+ "提取规则:\n"
+ "- 每条超边应连接 2 个或更多因子。\n"
+ "- 描述交互机制和结果。\n"
+ "- 对交互类型进行分类。\n"
+ "- 仅引用提供列表中存在的因子。"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class FactorInfluenceHypergraph(AutoHypergraph[InvestmentFactor, FactorInteraction]):
+ """
+ 适用文档: 多因子研究报告、量化基本面分析、宏观策略笔记、跨资产研究、因子归因研究。
+
+ 模板用于建模股票分析中的复杂多因子关系。使用超边捕获多个因子共同影响结果的
+ 交互关系,超越简单的成对关系。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> factors = FactorInfluenceHypergraph(llm_client=llm, embedder=embedder)
+ >>> report = "利率上升叠加强劲 GDP 和 AI 资本支出,推动向优质成长股轮动..."
+ >>> factors.feed_text(report)
+ >>> factors.show()
+ """
+
+ def __init__(
+ self,
+ llm_client: BaseChatModel,
+ embedder: Embeddings,
+ *,
+ 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): 用于去重的嵌入模型。
+ extraction_mode (str): "one_stage" 或 "two_stage"。
+ chunk_size (int): 每个分块的最大字符数。
+ chunk_overlap (int): 分块之间的重叠。
+ max_workers (int): 并行处理工作线程数。
+ verbose (bool): 是否启用进度日志。
+ **kwargs: AutoHypergraph 的其他参数。
+ """
+ super().__init__(
+ node_schema=InvestmentFactor,
+ edge_schema=FactorInteraction,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: x.interaction_name.strip().lower(),
+ nodes_in_edge_extractor=lambda x: tuple(
+ f.strip().lower() for f in x.participating_factors
+ ),
+ llm_client=llm_client,
+ embedder=embedder,
+ 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: InvestmentFactor) -> str:
+ reading = f": {node.current_reading}" if node.current_reading else ""
+ return f"{node.name} [{node.factor_level}]{reading}"
+
+ def edge_label_extractor(edge: FactorInteraction) -> str:
+ return f"[{edge.interaction_type}] {edge.interaction_name}"
+
+ 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/financial_forecast.py b/hyperextract/templates/zh/finance/financial_forecast.py
new file mode 100644
index 0000000..3ff4cce
--- /dev/null
+++ b/hyperextract/templates/zh/finance/financial_forecast.py
@@ -0,0 +1,144 @@
+"""财务预测 - 从股票研究报告中提取预测财务数据。
+
+提取分析师报告中的收入、每股收益、市盈率等未来期间的财务预测,
+用于一致性预期分析和财务建模。
+"""
+
+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 ForecastItem(BaseModel):
+ """
+ 特定指标和期间的单项财务预测。
+ """
+
+ metric: str = Field(
+ description="被预测的财务指标(例如 '收入'、'每股收益'、'EBITDA'、'营业利润率'、'自由现金流')。"
+ )
+ period: str = Field(
+ description="预测期间(例如 'FY2025E'、'Q1 2025E'、'CY2026E')。"
+ )
+ estimate: str = Field(
+ description="预测值(例如 '$120.5B'、'$6.25'、'35.2%')。"
+ )
+ prior_estimate: Optional[str] = Field(
+ None, description="如有修订,之前的预测值(例如 '$115.0B')。"
+ )
+ consensus: Optional[str] = Field(
+ None, description="用于对比的市场一致性预期(例如 '$118.2B')。"
+ )
+ growth_rate: Optional[str] = Field(
+ None,
+ description="隐含增长率(例如 '同比+15%'、'持平')。",
+ )
+ assumptions: Optional[str] = Field(
+ None,
+ description="预测所依据的关键假设(例如 '假设销量增加 500 万台')。",
+ )
+ source_firm: Optional[str] = Field(
+ None, description="提供该预测的研究机构。"
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一名构建盈利模型的金融分析师。从本股票研究报告中提取所有财务预测和估算。\n\n"
+ "规则:\n"
+ "- 提取每个预测指标及其对应的具体时间段。\n"
+ "- 在注明修订时,同时捕获当前和之前的预测值。\n"
+ "- 在进行对比时提取一致性预期。\n"
+ "- 捕获增长率和关键假设。\n"
+ "- 将每项预测作为独立条目单独提取。\n\n"
+ "### 源文本:\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class FinancialForecast(AutoList[ForecastItem]):
+ """
+ 适用文档: 股票研究报告、盈利预测、财务模型、一致性预期报告、分析师预测。
+
+ 模板用于从分析师报告中提取预测财务数据。每项预测作为独立列表项捕获,
+ 支持一致性预期分析、预测修订跟踪和财务模型构建。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> forecast = FinancialForecast(llm_client=llm, embedder=embedder)
+ >>> report = "我们将 FY2025 收入预测上调至 1205 亿美元(此前为 1150 亿美元)..."
+ >>> forecast.feed_text(report)
+ >>> forecast.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=ForecastItem,
+ 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: ForecastItem) -> str:
+ return f"{item.metric} ({item.period}): {item.estimate}"
+
+ 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/finance/research_note_summary.py b/hyperextract/templates/zh/finance/research_note_summary.py
new file mode 100644
index 0000000..f36f78c
--- /dev/null
+++ b/hyperextract/templates/zh/finance/research_note_summary.py
@@ -0,0 +1,146 @@
+"""研究报告摘要 - 从股票研究报告中提取核心投资论点。
+
+提取分析师研究报告中的评级、目标价和顶层投资逻辑,
+用于报告数据库填充和筛选。
+"""
+
+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 ResearchNoteSummarySchema(BaseModel):
+ """
+ 股票研究报告的结构化摘要。
+ """
+
+ company_name: Optional[str] = Field(
+ None, description="被覆盖公司的名称。"
+ )
+ ticker: Optional[str] = Field(
+ None, description="股票代码(例如 'AAPL'、'NVDA')。"
+ )
+ analyst_name: Optional[str] = Field(
+ None, description="首席分析师的姓名。"
+ )
+ research_firm: Optional[str] = Field(
+ None, description="研究机构名称(例如 '高盛'、'摩根士丹利')。"
+ )
+ report_date: Optional[str] = Field(
+ None, description="报告发布日期。"
+ )
+ rating: Optional[str] = Field(
+ None,
+ description="分析师评级:'买入'、'增持'、'持有'、'中性'、'卖出'、'减持'。",
+ )
+ prior_rating: Optional[str] = Field(
+ None, description="如有变更,之前的评级。"
+ )
+ target_price: Optional[str] = Field(
+ None, description="当前目标价(例如 '$150.00')。"
+ )
+ prior_target_price: Optional[str] = Field(
+ None, description="如有变更,之前的目标价。"
+ )
+ current_price: Optional[str] = Field(
+ None, description="报告发布时的股价。"
+ )
+ investment_thesis: Optional[str] = Field(
+ None,
+ description="核心投资论点或评级的关键论据。",
+ )
+ key_catalysts: Optional[List[str]] = Field(
+ None,
+ description="已识别的近期催化剂(例如 ['Q4 业绩超预期', '新产品发布', '监管审批'])。",
+ )
+ key_risks: Optional[List[str]] = Field(
+ None,
+ description="分析师强调的主要风险。",
+ )
+ revenue_estimate: Optional[str] = Field(
+ None, description="分析师对当前/下一财年的收入预测。"
+ )
+ eps_estimate: Optional[str] = Field(
+ None, description="分析师对当前/下一财年的每股收益预测。"
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一名股票研究分析师。从本研究报告中提取核心投资论点、评级、目标价和关键论据。\n\n"
+ "规则:\n"
+ "- 提取分析师的评级及任何评级变更。\n"
+ "- 捕获目标价以及变更前的目标价(如有变更)。\n"
+ "- 简洁地总结核心投资论点。\n"
+ "- 列出分析师识别的关键催化剂和风险。\n"
+ "- 在提及时提取财务预测(收入、每股收益)。\n\n"
+ "### 源文本:\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class ResearchNoteSummary(AutoModel[ResearchNoteSummarySchema]):
+ """
+ 适用文档: 股票研究报告、分析师笔记、评级变更、首次覆盖报告、行业研究。
+
+ 模板用于从股票研究报告中提取核心投资论点和关键参数。每份报告生成一个结构化摘要,
+ 用于数据库填充和筛选。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> summary = ResearchNoteSummary(llm_client=llm, embedder=embedder)
+ >>> report = "我们将 AAPL 评级上调为买入,目标价 200 美元..."
+ >>> summary.feed_text(report)
+ >>> print(summary.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=ResearchNoteSummarySchema,
+ 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/risk_factor_list.py b/hyperextract/templates/zh/finance/risk_factor_list.py
new file mode 100644
index 0000000..4c4992b
--- /dev/null
+++ b/hyperextract/templates/zh/finance/risk_factor_list.py
@@ -0,0 +1,140 @@
+"""风险因素列表 - 从股票研究报告中提取下行风险。
+
+列出分析师识别的具体下行风险,包括监管、汇率、供应链等
+风险类别,用于风险监控。
+"""
+
+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 AutoList
+
+# ==============================================================================
+# 1. Schema 定义
+# ==============================================================================
+
+
+class RiskItem(BaseModel):
+ """
+ 股票研究中识别的一项具体下行风险。
+ """
+
+ risk_name: str = Field(
+ description="风险的简洁名称(例如 '欧盟监管收紧'、'强势美元带来的汇率逆风')。"
+ )
+ risk_category: str = Field(
+ description="类别:'监管'、'竞争'、'宏观经济'、'运营'、'汇率/货币'、"
+ "'地缘政治'、'技术'、'法律/诉讼'、'ESG'、'执行'。"
+ )
+ description: str = Field(
+ description="风险情景的详细描述。"
+ )
+ potential_impact: Optional[str] = Field(
+ None,
+ description="估计的财务影响(例如 '收入下行 3-5%'、'每股收益风险 $0.50')。",
+ )
+ probability: Optional[str] = Field(
+ None,
+ description="分析师的概率评估:'高'、'中等'、'低'。",
+ )
+ time_horizon: Optional[str] = Field(
+ None,
+ description="风险可能兑现的时间(例如 '近期'、'2025 年'、'12-18 个月')。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一名审查股票研究报告的风险分析师。提取分析师识别的所有下行风险和风险因素。\n\n"
+ "规则:\n"
+ "- 提取提及的每一个不同的风险因素。\n"
+ "- 对每项风险进行适当分类。\n"
+ "- 在提供量化影响估算时予以捕获。\n"
+ "- 记录概率评估和时间范围。\n"
+ "- 将每项风险作为独立条目单独提取。\n\n"
+ "### 源文本:\n"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class RiskFactorList(AutoList[RiskItem]):
+ """
+ 适用文档: 股票研究报告(风险章节)、投资委员会备忘录、投资组合风险评估、分析师降级笔记。
+
+ 模板用于从股票研究中提取下行风险。每项风险作为独立列表项捕获,
+ 用于风险监控和投资组合风险评估。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> risks = RiskFactorList(llm_client=llm, embedder=embedder)
+ >>> report = "主要风险包括:1) 欧盟数字市场法合规成本..."
+ >>> risks.feed_text(report)
+ >>> risks.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=RiskItem,
+ 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: RiskItem) -> str:
+ return f"[{item.risk_category}] {item.risk_name}"
+
+ 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/finance/valuation_logic_map.py b/hyperextract/templates/zh/finance/valuation_logic_map.py
new file mode 100644
index 0000000..5318144
--- /dev/null
+++ b/hyperextract/templates/zh/finance/valuation_logic_map.py
@@ -0,0 +1,190 @@
+"""估值逻辑图谱 - 映射驱动股票表现的因果链。
+
+提取股票研究报告中从业务驱动因素到估值结论的逻辑链
+(例如 新市场 -> 增长 -> 估值倍数扩张)。
+"""
+
+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 ValuationDriver(BaseModel):
+ """
+ 分析师估值逻辑链中的一个因素。
+ """
+
+ name: str = Field(
+ description="估值驱动因素名称(例如 '市场份额增长'、'估值倍数扩张'、'DCF 假设')。"
+ )
+ driver_type: str = Field(
+ description="类型:'基本面'、'估值指标'、'增长驱动因素'、'可比公司'、'折现率'、'终值'。"
+ )
+ value: Optional[str] = Field(
+ None,
+ description="量化值或指标(例如 '25 倍前瞻市盈率'、'WACC 9.5%'、'TAM 150 亿美元')。",
+ )
+ description: Optional[str] = Field(
+ None,
+ description="分析师对该驱动因素在估值中所起作用的解释。",
+ )
+
+
+class ValuationEdge(BaseModel):
+ """
+ 分析师估值逻辑中的因果链接。
+ """
+
+ source: str = Field(description="原因或输入驱动因素名称。")
+ target: str = Field(description="结果或输出驱动因素名称。")
+ logic: str = Field(
+ description="分析师连接源到目标的推理逻辑"
+ "(例如 '更高的云计算采用率推动经常性收入增长')。"
+ )
+ direction: str = Field(
+ description="影响方向:'正面'、'负面'、'中性'。"
+ )
+ confidence: Optional[str] = Field(
+ None,
+ description="分析师的确信度:'高'、'中等'、'低'。",
+ )
+
+
+# ==============================================================================
+# 2. 提示词 (Prompts)
+# ==============================================================================
+
+_PROMPT = (
+ "你是一名股票研究分析师。从本研究报告中提取估值逻辑链:即从业务基本面到估值结论的因果推理。\n\n"
+ "规则:\n"
+ "- 识别基本面驱动因素、增长催化剂和估值指标。\n"
+ "- 提取从业务驱动因素到目标价的因果链。\n"
+ "- 捕获分析师在每个链接处的具体推理。\n"
+ "- 记录影响方向和确信度。"
+)
+
+_NODE_PROMPT = (
+ "你是一名股票研究分析师。提取所有估值驱动因素和指标(节点)。\n\n"
+ "提取规则:\n"
+ "- 识别基本面驱动因素(收入增长、市场份额、TAM)。\n"
+ "- 识别估值指标(P/E、EV/EBITDA、DCF、可比倍数)。\n"
+ "- 在提及时捕获量化值。\n"
+ "- 此阶段不建立因果链接。"
+)
+
+_EDGE_PROMPT = (
+ "你是一名股票研究分析师。在获得估值驱动因素的基础上,提取连接它们的逻辑推理链(边)。\n\n"
+ "提取规则:\n"
+ "- 将业务驱动因素连接到财务结果再到估值结论。\n"
+ "- 捕获每个链接处的具体推理。\n"
+ "- 记录每个链接是正面、负面还是中性影响。\n"
+ "- 仅在提供的列表中存在的节点之间创建边。"
+)
+
+# ==============================================================================
+# 3. 模板类
+# ==============================================================================
+
+
+class ValuationLogicMap(AutoGraph[ValuationDriver, ValuationEdge]):
+ """
+ 适用文档: 股票研究报告、首次覆盖报告、估值分析、分部加总分析、DCF 模型摘要。
+
+ 模板用于映射分析师估值逻辑中的因果链。将业务基本面连接到增长驱动因素,
+ 再到估值指标和目标价,支持投资策略映射和论点比较。
+
+ 使用示例:
+ >>> from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+ >>> llm = ChatOpenAI(model="gpt-4o")
+ >>> embedder = OpenAIEmbeddings()
+ >>> valuation = ValuationLogicMap(llm_client=llm, embedder=embedder)
+ >>> report = "云计算采用推动经常性收入,支撑 30 倍前瞻市盈率..."
+ >>> valuation.feed_text(report)
+ >>> valuation.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=ValuationDriver,
+ edge_schema=ValuationEdge,
+ node_key_extractor=lambda x: x.name.strip().lower(),
+ edge_key_extractor=lambda x: (
+ f"{x.source.strip().lower()}--({x.direction})-->{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 可视化估值逻辑图谱。
+
+ 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: ValuationDriver) -> str:
+ val = f": {node.value}" if node.value else ""
+ return f"{node.name}{val}"
+
+ def edge_label_extractor(edge: ValuationEdge) -> str:
+ return f"[{edge.direction}] {edge.logic[:60]}"
+
+ 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,
+ )