Equity Penetration System Implementation: Graph Algorithms and Compliance Practices

    This article explains how to build an equity penetration system that traces ownership and control relationships layer by layer to identify ultimate beneficial owners. It covers graph-based data modeling with nodes and edges, recursive SQL and path-enumeration algorithms, combining direct and indirect shareholding, and resolving cross-shareholding cycles with matrix methods. It also shows how to use large language models (LLMs) to turn unstructured documents into structured, evidence-backed relationship edges, how to evaluate extraction and penetration quality, and how to manage model versions and the overall layered architecture. It closes with common pitfalls and compliance boundaries around data sourcing, personal-information protection, and audit traceability.

    1. Introduction: What Equity Penetration Actually Uncovers

    Equity penetration is not just looking up a shareholder list. It traces relationships upward layer by layer — shareholding, contractual control, voting rights delegation, concerted action, and more — until it identifies the terminal parties: natural persons, state-owned entities, public companies, or asset management products. It then quantifies each party’s economic interest and degree of control.

    Common use cases include anti-money-laundering (AML) customer due diligence, group credit assessment, supplier relationship screening, procurement compliance review, and related-party identification.

    Real-world equity data typically has three challenges:

    1. Multi-hop and heterogeneous: Direct shareholding, indirect shareholding, contractual control, voting rights delegation, and employment relationships are intertwined.
    2. Cyclic and time-varying: Cross-shareholding and historical changes make the same entity look different at different points in time.
    3. Inconsistent semantics: The economic-interest lens answers “who gets the money,” while the control lens answers “who calls the shots.” The two must not be conflated.

    Equity penetration is therefore a systems-engineering effort: data modeling, graph traversal, ratio calculation, cycle resolution, evidence traceability, evaluation, and compliance governance are all indispensable.

    2. Data Modeling: Rendering the Ownership Structure as a Graph

    2.1 Designing Nodes and Edges

    The most basic model is “entities as nodes, shareholding as edges.” On top of this, consider adding the following fields:

    • Entity nodes: Keep the registered legal name, internal primary key, entity type, and registration status.
    • Relationship types: Distinguish direct shareholding, contractual control, voting rights delegation, concerted action, employment, and so on.
    • Ratio semantics: Distinguish the equity percentage from the voting percentage, and note whether it is based on subscribed capital, paid-in capital, or a converted capital contribution.
    • Time dimension: Each edge records an effective date and an expiry date, supporting filtering by query time point.
    • Alias mapping: Map names, registration/tax identifiers, ID numbers, and former names to one another to avoid entity fragmentation.
    • Evidence fields: Each edge links to a registry snapshot, announcement passage, contract page, or extracted snippet, keeping conclusions traceable.

    2.2 Relational Table or Graph Database?

    If the data scale is moderate and the penetration depth is shallow, a relational database with recursive queries handles most needs. If multi-hop queries are frequent, the graph is large, and cycle detection and path analysis are routine, a graph database can be introduced. Mature systems typically adopt a hybrid architecture: the relational store keeps master data and evidence, the graph store handles multi-hop queries, and effective edges are synced periodically.

    Below is a corrected recursive SQL. The key point: the anchor path must include the starting entity and the first-layer shareholders, and each subsequent layer must append the new node to the complete path, filtering edges by the query time point.

    1. -- Entity table (illustrative)
    2. CREATE TABLE entity (
    3. entity_id BIGINT PRIMARY KEY,
    4. name VARCHAR(200) NOT NULL,
    5. entity_type VARCHAR(16) NOT NULL, -- COMPANY/PERSON/FUND/GOVERNMENT
    6. reg_no VARCHAR(32),
    7. status VARCHAR(16)
    8. );
    9. -- Edge table (illustrative)
    10. CREATE TABLE shareholding_edge (
    11. edge_id BIGINT PRIMARY KEY,
    12. holder_id BIGINT NOT NULL,
    13. target_id BIGINT NOT NULL,
    14. ratio DECIMAL(10,6),
    15. edge_type VARCHAR(16) NOT NULL, -- HOLDING/CONTROL/AGREEMENT
    16. ratio_type VARCHAR(8) NOT NULL, -- EQUITY/VOTING
    17. valid_from DATE NOT NULL,
    18. valid_to DATE,
    19. evidence_id BIGINT
    20. );
    21. CREATE INDEX idx_target ON shareholding_edge(target_id, valid_from, valid_to);
    22. CREATE INDEX idx_holder ON shareholding_edge(holder_id, ratio_type, valid_from, valid_to);

    The recursive penetration query:

    1. WITH RECURSIVE chain AS (
    2. SELECT
    3. holder_id,
    4. target_id,
    5. CAST(ratio AS DECIMAL(20,10)) AS path_ratio,
    6. ARRAY[target_id, holder_id] AS path_nodes,
    7. 1 AS depth
    8. FROM shareholding_edge
    9. WHERE edge_type = 'HOLDING'
    10. AND ratio_type = 'EQUITY'
    11. AND valid_from <= :as_of_date
    12. AND (valid_to IS NULL OR valid_to >= :as_of_date)
    13. AND target_id = :target_id
    14. UNION ALL
    15. SELECT
    16. e.holder_id,
    17. c.holder_id,
    18. c.path_ratio * e.ratio,
    19. c.path_nodes || e.holder_id,
    20. c.depth + 1
    21. FROM shareholding_edge e
    22. JOIN chain c ON e.target_id = c.holder_id
    23. WHERE e.edge_type = 'HOLDING'
    24. AND e.ratio_type = 'EQUITY'
    25. AND e.valid_from <= :as_of_date
    26. AND (e.valid_to IS NULL OR e.valid_to >= :as_of_date)
    27. AND c.depth < :max_depth
    28. AND NOT (e.holder_id = ANY(c.path_nodes))
    29. )
    30. SELECT holder_id, path_ratio, path_nodes, depth
    31. FROM chain
    32. ORDER BY depth, holder_id, path_ratio DESC;

    Here :as_of_date is the query time-point parameter, ensuring historical and current shareholders are never mixed. If the business only keeps a single best path, the API documentation should state clearly that “only the best path is returned.” If full economic-interest aggregation is required, all paths should be preserved.

    3. Penetration Algorithms: From Path Enumeration to Ratio Solving

    3.1 Path Enumeration: Depth-First with Truncation Flags

    Penetration analysis usually cares about all possible paths, not the shortest one. Both control determination and final economic-interest calculation depend on the complete path set. The common approach is a depth-first search with a path stack.

    So downstream consumers know whether results are complete, the traversal function should return a truncated flag. When max_depth or min_ratio triggers pruning, the result should be treated as incomplete and aligned with meta.truncated in the API response.

    1. def enumerate_paths(graph, start, stop, max_depth=10, min_ratio=1e-6):
    2. """Enumerate all upward shareholding paths starting from `start`.
    3. graph: dict mapping holder -> [(target, ratio), ...], already filtered by time point
    4. stop: function that decides whether a node is a terminal entity
    5. Returns: (list of results, truncated)
    6. """
    7. results = []
    8. truncated = False
    9. stack = [(start, [start], 1.0)]
    10. while stack:
    11. node, path, prod = stack.pop()
    12. if stop(node) and len(path) > 1:
    13. if prod < min_ratio:
    14. truncated = True
    15. else:
    16. results.append((path, prod))
    17. continue
    18. if prod < min_ratio:
    19. truncated = True
    20. continue
    21. if len(path) - 1 >= max_depth:
    22. truncated = True
    23. continue
    24. for nxt, ratio in graph.get(node, []):
    25. if nxt in path:
    26. continue
    27. new_prod = prod * ratio
    28. if new_prod < min_ratio:
    29. truncated = True
    30. continue
    31. stack.append((nxt, path + [nxt], new_prod))
    32. return results, truncated

    Engineering considerations:

    1. Cycle prevention: Use the visited set of the current path, not a global visited set, otherwise other paths passing through the same node will be missed.
    2. Pruning: A too-small ratio or an exceeded depth can terminate early, but the result must be flagged as incomplete.
    3. Path explosion: Deep, wide-fan-out structures can cause the number of results to grow rapidly, so rate limiting via parameters is needed.

    Path explosion can be configured as follows:

    Parameter or mechanism Recommended baseline Notes
    max_depth 8–10 Group multi-layer structures can raise it, but a cap is recommended
    min_ratio 1e-6 Tighten for high-risk scenarios; loosen moderately for ordinary ones
    Sync interface timeout 2–5 s On timeout, return the truncated result and flag it
    Fallback strategy Async queue Large fan-out queries can be turned into batch jobs
    Cache entity + time point + version Avoid recomputing results of the same scope

    3.2 Combining Direct and Indirect Shareholding

    A shareholder’s equity ratio in the target entity equals the direct shareholding ratio plus the sum of all indirect path products.

    For example: a natural person directly holds 30% of the target company. The same person holds 30% of Company A; Company A holds 60% of Company B; and Company B holds 40% of the target company. The indirect equity is therefore:

    30% × 60% × 40% = 7.2%

    If the person also directly holds 30% of the target company, the total equity is:

    30% + 7.2% = 37.2%

    If the person does not directly hold the target company, the result keeps only 7.2%. This point is critical; otherwise the direct and indirect shareholding lenses get easily confused.

    Simple path aggregation can be done with a dictionary:

    1. from collections import defaultdict
    2. def aggregate_paths(paths):
    3. """Aggregate equity ratios by terminal entity; does not handle cross-shareholding."""
    4. equity = defaultdict(float)
    5. for path, ratio in paths:
    6. equity[path[-1]] += ratio
    7. return dict(equity)

    Note that simple path deduplication only prevents walking the same cycle twice; it cannot resolve the equity reflux problem in cross-shareholding. Strict handling of cross-shareholding requires linear-algebra methods.

    3.3 Calculating Cross-Shareholding Ratios

    Suppose there are n entities. Let h(i, j) be the ratio by which entity j holds entity i, and let H be the n×n matrix. Let b(i) be the equity injected externally into entity i, and x(i) the proportion of entity i’s equity ultimately attributed to external parties.

    The model is:

    x(i) = b(i) + Σⱼ h(i, j) · x(j)

    That is:

    x = b + Hx

    Without cycles, this expands into a finite sum, equivalent to path enumeration. With cycles, it corresponds to the infinite series:

    x = (I + H + H² + …)b

    The series converges and the solution is unique if and only if the spectral radius of matrix H is less than 1.

    Example: A holds 60% of B, B holds 20% of A, a natural person holds 30% of A, and there are no other external holdings.

    The equations are:

    x(A) = 30% + 20% × x(B)
    x(B) = 60% × x(A)

    Substituting and solving:

    x(A) = 30% + 20% × 60% × x(A)
    x(A) = 30% + 12% × x(A)
    0.88 × x(A) = 30%
    x(A) ≈ 34.09%

    x(B) ≈ 20.45%

    If only path enumeration is used, the result may stay at 30%, underestimating the reflux equity introduced by cross-shareholding.

    In engineering, you can split by strongly connected components and then solve. Below is a corrected convergence check: a max absolute row sum less than 1 is a sufficient condition for fast convergence; if the row sum is not less than 1, you should not report an error directly, but try a linear solve and judge via the spectral radius or matrix singularity.

    1. import numpy as np
    2. def resolve_component(matrix, external, tol=1e-12, max_iter=10000):
    3. """Solve a single cross-shareholding component: x = b + Hx.
    4. matrix: square matrix where matrix[i][j] is the ratio by which j holds i
    5. external: list of externally injected ratios
    6. """
    7. n = len(external)
    8. if n == 0:
    9. return []
    10. H = np.array(matrix, dtype=float)
    11. b = np.array(external, dtype=float)
    12. # A max absolute row sum < 1 is a sufficient (not necessary) condition for convergence.
    13. max_row_sum = float(np.max(np.sum(np.abs(H), axis=1)))
    14. if max_row_sum < 1.0:
    15. x = b.copy()
    16. for _ in range(max_iter):
    17. nxt = b + H.dot(x)
    18. if np.max(np.abs(nxt - x)) < tol:
    19. return nxt.tolist()
    20. x = nxt
    21. # If iteration misbehaves, fall back to a linear solve.
    22. A = np.eye(n) - H
    23. try:
    24. return np.linalg.solve(A, b).tolist()
    25. except np.linalg.LinAlgError:
    26. eigen_values = np.linalg.eigvals(H)
    27. spectral_radius = float(np.max(np.abs(eigen_values)))
    28. if spectral_radius >= 1.0 - 1e-12:
    29. raise ValueError(
    30. "Spectral radius near or above 1; cross-shareholding may not converge. "
    31. "Check for duplicate capital contributions, duplicate entity imports, or mixed ratio semantics"
    32. )
    33. # If the spectral radius < 1 but the linear solve hits a numerical issue, use least squares as a fallback.
    34. return np.linalg.lstsq(A, b, rcond=None)[0].tolist()

    Another approach is matrix inversion:

    x = (I - H)⁻¹b

    1. import numpy as np
    2. def solve_component(matrix, external):
    3. """Solve x = (I - H)^-1 b per component."""
    4. n = len(external)
    5. A = np.eye(n) - np.array(matrix, dtype=float)
    6. b = np.array(external, dtype=float)
    7. return np.linalg.solve(A, b).tolist()

    A checklist of common anomaly scenarios:

    • The same capital contribution imported twice, inflating the ratio.
    • The same entity split into multiple entities due to inconsistent names or ID numbers.
    • Equity ratio and voting ratio mixed in the same field.
    • Missing externally injected equity, distorting final attribution.
    • Abnormal row sums or spectral radius, possibly indicating data with cycle amplification.

    3.4 The Control Lens: Identifying Who Calls the Shots

    The equity ratio answers “how the money is split,” while control answers “who calls the shots.” It is recommended to compute both the economic-interest and control lenses on the same graph, with explicit labeling.

    Scenario Rule Output
    Absolute control Equity or voting ratio over 50% Single controlling party
    Relative control Largest shareholder, with stable control formed via agreements, delegation, or concerted action Single controlling party
    Voting rights delegation Combined voting computed after delegation Delegatee
    Limited partnership Usually controlled by the general partner Penetrate to the GP and its upper layers
    Dual control Two parties with near-equal holdings and mutual checks No single controlling party

    For example: a natural person, Zhang, directly holds 51% of Company A; Company A holds 45% of Company B, and another investor holds 55% of Company B. By the economic-interest lens, Zhang indirectly holds 51% × 45% = 22.95% of Company B. But by the control lens, absent voting rights delegation, concerted action, or similar arrangements, Company A does not control Company B, and Zhang’s control chain stops at Company A.

    Therefore, the API should return the economic ratio and the control chain side by side, avoiding misreading by the business side.

    4. LLM Extraction: From Unstructured Material to the Graph

    Business registry data only covers the skeleton of the ownership structure. Concerted action agreements, voting rights delegations, nominee holding arrangements, contractual control clauses, and cross-shareholding descriptions in listed-company announcements are often buried in contracts, annual reports, prospectuses, and announcements. Traditional templates and regex extraction generalize poorly on documents with diverse layouts and flexible wording.

    The value of LLMs is not to replace graph algorithms, but to turn unstructured information into computable, auditable structured relationship edges.

    A typical pipeline includes:

    1. Document ingestion and layout reconstruction: Identify titles, tables, scanned text, and seal positions.
    2. Passage-level extraction: Split long documents; the model answers based only on the given passage and returns the source evidence.
    3. Structured output: Extract shareholders, target companies, ratios, dates, relationship types, and evidence passages.
    4. Entity alignment: Align extracted names with master data; unmatched ones go to a review queue.
    5. Human review: Low-confidence results or material conclusions must be confirmed by a person.

    Example structured output:

    1. {
    2. "relations": [
    3. {
    4. "holder": "Company A",
    5. "target": "Company B",
    6. "ratio": 0.45,
    7. "ratio_type": "equity",
    8. "edge_type": "holding",
    9. "valid_from": "2023-06-15",
    10. "evidence": {
    11. "doc_id": "doc_20240612_001",
    12. "page": 12,
    13. "snippet": "holds 45% equity"
    14. }
    15. }
    16. ],
    17. "warnings": []
    18. }

    Recommended confidence-tier strategy:

    Confidence Handling strategy
    High Can be auto-ingested, with sampling checks by proportion
    Medium Enter the manual review queue
    Low Returned for supplementary collection or manual judgment
    Material conclusions Even at high confidence, dual-person review is recommended

    In practice, hold to a few principles: distinguish “not mentioned in the material” from “zero in the material”; every extraction result must carry source location; extraction output is uniformly normalized into evidence-bearing relationship edges that follow the same penetration pipeline as registry data; and complete desensitization before sending to any external model — sensitive fields such as ID numbers and bank account numbers must not leave the internal network.

    5. Evaluation and Version Governance

    LLMs iterate quickly, and after a version upgrade two questions must be answered: can the old version’s results be reproduced, and is the new version actually better in real business scenarios? General leaderboards are a useful reference, but equity penetration has clear domain characteristics: long chains, cross-shareholding, same-name entities, complex scans, and mixed tables and body text. A higher leaderboard score does not necessarily mean more accurate business extraction.

    The evaluation set should be stratified from production data:

    • Entity coverage: Companies, natural persons, partnerships, asset management products.
    • Document types: Announcements, contracts, judgments, annual reports.
    • Document quality: Digital-native, scanned, low-resolution images.
    • Structural complexity: Simple two-layer, deep nesting, cross-shareholding.

    Evaluation metrics can be split into three layers:

    Layer Key metric Recommended baseline
    Extraction Field-level precision, recall, F1 At least 1,000 stratified sampled documents; adjustable by risk
    Extraction Hallucination rate Proportion of content without source grounding, spot-checked at the passage level
    Penetration Ultimate beneficial owner identification accuracy Sample paths cover both natural persons and terminal institutions
    Penetration Path completeness Whether all shareholding paths are covered
    Penetration Ratio error Deviation from manually annotated equity ratios
    Business Review rate, cost per document, P95 latency At least 500 typical queries; adjustable by scale

    Version governance recommendations:

    • Dual-run comparison: Run the new version in shadow mode alongside production first, manually adjudicate divergent samples, and roll out gradually once targets are met.
    • Triple recording: Each conclusion records a “data snapshot version + rule/algorithm version + model version,” ensuring historical conclusions are reproducible.
    • Rules first: Decouple business rules — termination conditions, pruning thresholds, penetration semantics — from the model, so model upgrades do not change the explainability of penetration.
    • Continuous monitoring: Combine sampled quality inspections with distribution monitoring to catch extraction-quality drift early.

    6. Overall Architecture, Common Pitfalls, and Compliance Boundaries

    6.1 Layered Architecture

    1. Data ingestion layer: Structured registry data is ingested through compliant, authorized channels; unstructured documents are uploaded via object storage and peak-shaved/decoupled by a message queue.
    2. Data processing layer: Layout parsing, passage extraction, entity alignment, evidence archiving.
    3. Graph storage layer: The relational store keeps master data and evidence; the graph store handles multi-hop queries and relationship analysis.
    4. Computation service layer: Path enumeration, ratio aggregation, cycle resolution, and control determination are deployed independently, with results cached by “entity + time point + version.”
    5. Application service layer: Exposes penetration query APIs externally, returning the ultimate beneficial owner, each layer’s equity ratio, the control chain, evidence references, and a truncation flag.

    Illustrative API:

    1. def penetration(subject_id, as_of_date, mode="both",
    2. max_depth=10, min_ratio=1e-6):
    3. """Equity penetration query interface (illustrative).
    4. Args:
    5. subject_id: internal entity ID
    6. as_of_date: query time point; only edges valid at this time are included
    7. mode: "equity" for the economic-interest lens / "control" for the control lens / "both"
    8. """
    9. paths, truncated = enumerate_paths(
    10. load_graph(subject_id, as_of_date),
    11. subject_id,
    12. is_terminator,
    13. max_depth=max_depth,
    14. min_ratio=min_ratio
    15. )
    16. return {
    17. "subject": {"id": subject_id},
    18. "as_of_date": as_of_date,
    19. "terminators": build_terminators(paths),
    20. "equity_ratios": aggregate_paths(paths),
    21. "control_chains": resolve_control_chains(paths),
    22. "cycles_resolved": resolve_cycles(paths),
    23. "evidence": load_evidence(paths),
    24. "meta": {
    25. "data_version": "...",
    26. "rule_version": "...",
    27. "model_version": "...",
    28. "truncated": truncated
    29. }
    30. }

    6.2 Common Mistakes

    1. Same name, different person: Two people named “Zhang” may be entirely unrelated; disambiguation must combine ID numbers, employment overlaps, addresses, and other features.
    2. Time-point mixing: Treating historical shareholders as current ones leads to wrong control conclusions.
    3. Semantics mixing: Returning the economic ratio and the control chain in the same field makes them easy to misread.
    4. Ignoring implicit relationships: Concerted action, voting rights delegation, and contractual control do not appear in registry equity and must be modeled as separate edges.
    5. Unresolved cycles: Using path enumeration directly under cross-shareholding systematically underestimates equity ratios.
    6. Path explosion: Deep, wide-fan-out structures that are not pruned cause response timeouts.
    7. Silent truncation: Results are cut off by a depth or ratio threshold, yet the response does not flag it.

    6.3 Compliance and Security

    • Lawful data sources: Obtain data through public query channels or lawfully authorized APIs, respect terms of service, and do not scrape by bypassing access restrictions.
    • Personal-information protection: Collect and store natural-person ID numbers, contact details, and similar data on a data-minimization basis, encrypt them, and restrict access.
    • Sensitive-data boundaries: Desensitize sensitive fields such as ID numbers and bank account numbers and avoid uploading them to external models; where genuinely necessary, keep them off the public internet or use a private deployment.
    • Audit traceability: Record the querier, query target, query time, returned results, model version, and rule version; audit logs must be traceable.
    • Retention period: Set log and result retention periods per regulatory requirements or internal policy — for example, key audit logs kept for no less than 6 months.
    • Clear boundaries: Penetration results are decision-support inputs and do not replace professional legal and compliance judgment.

    7. Conclusion and FAQ

    Equity penetration is a classic “data + algorithm + governance” cross-disciplinary effort. On the data side, the hard parts are entity alignment, time-point management, and evidence traceability. On the algorithm side, the core is path enumeration, combining direct and indirect shareholding, resolving cross-shareholding cycles, and determining the control lens. On the governance side, the focus is the evaluation system, version management, and compliance auditing.

    How do you write recursive SQL for equity penetration?

    Use a recursive CTE to traverse shareholding edges upward. The anchor records the starting entity and the first-layer shareholders; the recursive part appends each new shareholder to path_nodes, and filters the query time point via valid_from <= :as_of_date and valid_to to avoid mixing in historical relationships.

    How do you calculate cross-shareholding ratios?

    Write the equity relationships as a matrix model x = b + Hx. Without cycles, it expands into a sum of path products; with cycles, solve x = (I - H)⁻¹b. In engineering, split by strongly connected components first, then use iteration or a linear solve within each component.

    How do you choose between a relational database and a graph database?

    For moderate scale and shallow penetration, prefer a relational database with recursive queries; for large scale, multi-hop traversal, and frequent cycle detection, a graph database fits better. Mature systems typically use a hybrid architecture — the relational store holds master data and evidence, while the graph store handles relationship analysis.

    How do you avoid business misreading?

    Return the economic-interest lens and the control lens side by side, and label the query time point, truncation flag, data version, rule version, and model version. For cross-shareholding, low-confidence extractions, and material control conclusions, retain evidence and support human review.

    Only by making every layer — data, algorithm, and governance — solid can equity penetration be upgraded from “looking up shareholders” into a trustworthy relationship-analysis capability.