Metadata-Version: 2.4
Name: cnmv-xbrl
Version: 1.0.2
Summary: High-performance Python parser and data exporter for Spanish CNMV XBRL financial reports (FIM & SICAV).
Author-email: Marcos <marcos@example.com>
License: MIT
Project-URL: Homepage, https://github.com/marcosagni98/cnmv-xbrl
Project-URL: Repository, https://github.com/marcosagni98/cnmv-xbrl
Project-URL: Documentation, https://github.com/marcosagni98/cnmv-xbrl#readme
Project-URL: Bug Tracker, https://github.com/marcosagni98/cnmv-xbrl/issues
Keywords: xbrl,cnmv,finance,parser,fim,sicav,pandas,parquet,investment-funds
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: all
Requires-Dist: pandas>=2.0.0; extra == "all"
Requires-Dist: pyarrow>=12.0.0; extra == "all"
Requires-Dist: openpyxl>=3.1.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: hypothesis>=6.90.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Dynamic: license-file

# CNMV XBRL IIC Library (`cnmv-xbrl`)

[![Python Versions](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14-blue.svg)](https://pypi.org/project/cnmv-xbrl/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen.svg)](https://github.com/marcosagni98/cnmv-xbrl)
[![Code Style: Clean Code](https://img.shields.io/badge/code%20style-clean%20code-000000.svg)](https://github.com/marcosagni98/cnmv-xbrl)
[![PyPI status](https://img.shields.io/badge/status-stable-green.svg)](https://pypi.org/project/cnmv-xbrl/)

Enterprise-grade Python domain library for parsing, validating, and converting Spanish **CNMV XBRL Financial Reports** (*Circular 4/2008 of September 11th, and amendments 3/2009, 6/2010, 4/2011, and 5/2018*) into high-performance tabular datasets (`pandas.DataFrame`, `Apache Parquet`, `JSON`) optimized for quantitative finance, data science, and automated compliance auditing.

---

## Key Features

- **Zero-Heavy Dependencies Engine:** Core XML ElementTree parsing engine with optional PyArrow and Pandas data science backends.
- **Full Regulatory Scope:** Supports Spanish Investment Funds (**FIM**) and Open-Ended Investment Companies (**SICAV**).
- **High Performance:** Multithreaded parsing capable of processing **7,500+ XML documents** and **7.8M+ XBRL facts** in seconds.
- **Multilingual Label Resolution:** Resolves CNMV concept QNames to human-readable labels in **Spanish** and **English**.
- **Structured Domain Models:** Provides strongly typed objects for Share Classes, Portfolio Investment Holdings, Net Asset Variations, and Asset Distributions.
- **Data Science Export Pipeline:** One-line exports to `pandas.DataFrame`, binary column-oriented `Apache Parquet`, and structured `JSON`.
- **100% Test Coverage:** Verified with `pytest`, `pytest-cov`, and property-based testing with `hypothesis`.

---

## 1. Regulatory Context & Supported Scope

The **CNMV IIC Taxonomy** regulates quarterly and semi-annual financial reporting for Collective Investment Undertakings in Spain (*Instituciones de Inversión Colectiva*):

- **FIM (*Fondos de Inversión Mobiliares*):** Open-ended investment funds, share classes, portfolio holdings, net asset variations, management fees, and total expense ratios (TER).
- **SICAV (*Sociedades de Inversión de Capital Variable*):** Investment companies, share series, board metrics, and portfolio composition.
- **Circular Framework:** Fully compatible with **CNMV Circular 4/2008** and amending circulars **3/2009**, **6/2010**, **4/2011**, and **5/2018**.

---

## 2. Installation

Install `cnmv-xbrl` via `pip`:

```bash
pip install cnmv-xbrl
```

Or install with full data science exporters (Pandas & PyArrow Parquet support):

```bash
pip install cnmv-xbrl[all]
```

---

## 3. Quickstart & Usage Examples

### 3.1. Parsing an XBRL Document in 3 Lines

```python
import cnmv_xbrl as xbrl

# Parse XBRL/XML instance file directly
doc = xbrl.parse_xbrl("path/to/IIC_FIM_2024_S1.xml")

# Extract general fund metadata
info = doc.get_general_info()
print(f"Fund Name: {info['name']}")
print(f"CNMV Register #: {info['cnmv_register_number']}")
print(f"Management Company: {info['management_company']}")
```

### 3.2. Extracting Share Classes and Portfolio Holdings

```python
# Access structured Share Classes objects
classes = doc.get_classes()
for cls in classes:
    print(f"Class: {cls.name} | ISIN: {cls.isin} | NAV: {cls.nav} EUR | Total Assets: €{cls.total_assets:,.2f}")

# Access structured Portfolio Investment Holdings
holdings = doc.get_portfolio_holdings()
for item in holdings[:5]:
    print(f"Asset: {item.asset_name} | ISIN: {item.isin} | Weight: {item.portfolio_pct}% | Value: €{item.market_value:,.2f}")
```

### 3.3. Exporting to Pandas & Apache Parquet

```python
# Export facts table with enriched labels, periods, and context dimensions
df_facts = doc.to_dataframe(dataset="facts")

# Export share classes / SICAV series metrics
df_classes = doc.to_dataframe(dataset="classes")

# Export individual portfolio asset holdings
df_holdings = doc.to_dataframe(dataset="holdings")

# Save directly as binary columnar Apache Parquet files
doc.to_parquet("output_facts.parquet", dataset="facts")
doc.to_parquet("output_holdings.parquet", dataset="holdings")

# Export formatted JSON
json_string = doc.to_json(indent=2)
```

---

## 4. Architecture & Design Patterns

The library is engineered following **Clean Architecture** and **Domain-Driven Design (DDD)** principles, strictly decoupling XML ElementTree parsing mechanics from domain entity extraction and exporter pipelines.

### Architecture Flowchart

```mermaid
flowchart TD
    A[Raw CNMV XBRL XML Instance] --> B[XBRLParser Engine]
    C[CNMV Taxonomy Linkbases & XSD Schemas] --> D[IICTaxonomy Loader]
    
    B --> E[XBRLContext / XBRLFact / XBRLUnit Domain Models]
    D --> F[Label & Schema Resolution Engine]
    
    E --> G[XBRLDocument Domain Wrapper]
    F --> G
    
    G --> H1[to_dataframe]
    G --> H2[to_parquet]
    G --> H3[to_json]
    
    H1 --> I1[Pandas DataFrame: facts / classes / holdings / financials]
    H2 --> I2[Apache PyArrow Parquet File]
    H3 --> I3[Structured JSON Output]
```

### Domain Class Diagram

```mermaid
classDiagram
    class AbstractTaxonomy {
        <<abstract>>
        +load_taxonomy(source_directory: str)*
        +get_label(concept_name: str, lang: str)* Optional~str~
        +get_concept_metadata(concept_name: str)* Optional~Dict~
    }

    class IICTaxonomy {
        -_labels: Dict~str, Dict~
        -_concept_metadata: Dict~str, Dict~
        +load_taxonomy(source_directory: str)
        +get_label(concept_name: str, lang: str) Optional~str~
        +get_concept_metadata(concept_name: str) Optional~Dict~
    }

    class XBRLParser {
        +root: Element
        +contexts: Dict~str, XBRLContext~
        +units: Dict~str, XBRLUnit~
        +facts: List~XBRLFact~
        +get_facts_by_concept(concept: str) List~XBRLFact~
    }

    class XBRLDocument {
        +parser: XBRLParser
        +taxonomy: AbstractTaxonomy
        +get_general_info() Dict
        +get_classes() List~FundClass~
        +get_financials() Dict
        +get_asset_distribution() Dict
        +get_variacion_patrimonial() Dict
        +get_portfolio_holdings() List~PortfolioHolding~
        +to_dataframe(dataset: str) DataFrame
        +to_parquet(filepath: str, dataset: str)
        +to_json(indent: int) str
    }

    AbstractTaxonomy <|-- IICTaxonomy
    XBRLDocument *-- XBRLParser
    XBRLDocument *-- AbstractTaxonomy
```

---

## 5. Export Data Schemas Reference

### 5.1. Facts Dataset (`facts`)

| Field | Primitive Type | Description |
| :--- | :--- | :--- |
| `concept_id` | `string` | Unqualified local XBRL concept tag name. |
| `qname` | `string` | Prefix-qualified concept name (`prefix:concept`). |
| `label` | `string` | Resolved human-readable label (Spanish or English). |
| `value` | `float` / `int` / `bool` / `string` | Coerced fact value. |
| `raw_value` | `string` | Exact text content extracted from XML. |
| `unit` | `string` | ISO currency code (`EUR`, `USD`) or measure unit (`shares`, `pure`). |
| `context_id` | `string` | Target XBRL context identifier reference. |
| `period_type` | `string` | Period classification (`instant` or `duration`). |
| `start_date` | `string` | ISO start date for duration periods (`YYYY-MM-DD`). |
| `end_date` | `string` | ISO end date for duration periods (`YYYY-MM-DD`). |
| `instant` | `string` | ISO instant reporting date (`YYYY-MM-DD`). |
| `entity_id` | `string` | CNMV entity identifier code (NIF/CIF). |
| `dimensions` | `string` (JSON) | Serialized explicit and typed context dimension key-value pairs. |
| `decimals` | `string` | Declared numerical precision attribute. |
| `prefix` | `string` | Taxonomy namespace prefix (`iic-com`, `iic-fim`, `iic-sic`). |
| `is_nil` | `boolean` | Flag indicating explicit `xsi:nil="true"` nil fact attribute. |

### 5.2. Fund Share Classes Dataset (`classes`)

| Field | Primitive Type | Description |
| :--- | :--- | :--- |
| `name` | `string` | Share class name or SICAV series identifier. |
| `isin` | `string` | International Securities Identification Number (ISIN). |
| `shares` | `float64` | Total outstanding share volume. |
| `shareholders` | `int64` | Total registered shareholder / investor count (*partícipes*). |
| `nav` | `float64` | Net Asset Value per share (*Valor Liquidativo*). |
| `total_assets` | `float64` | Total net assets under management (*Patrimonio*). |
| `currency` | `string` | Base denomination currency code (`EUR`). |
| `min_investment` | `string` | Minimum initial investment description. |
| `management_fee_pct` | `float64` | Applied management fee percentage. |
| `custody_fee_pct` | `float64` | Applied depositary custody fee percentage. |
| `ter_pct` | `float64` | Total Expense Ratio percentage (TER / TER-OGC). |

### 5.3. Portfolio Investment Holdings Dataset (`holdings`)

| Field | Primitive Type | Description |
| :--- | :--- | :--- |
| `description` | `string` | Raw pipe-delimited security descriptor text. |
| `asset_name` | `string` | Parsed security name or issuer designation. |
| `asset_type` | `string` | Asset class category (e.g. `BONO`, `ACCION`, `FONDOS`). |
| `isin` | `string` | Instrument ISIN code. |
| `category` | `string` | Domestic vs foreign portfolio classification (`Interior`, `Exterior`). |
| `market_value` | `float64` | Position total market valuation in base currency. |
| `portfolio_pct` | `float64` | Relative portfolio weight percentage. |
| `currency` | `string` | Original asset quotation currency (`EUR`, `USD`). |
| `coupon_rate` | `string` | Fixed income nominal interest coupon rate. |
| `maturity_date` | `string` | Instrument maturity ISO date string (`YYYY-MM-DD`). |

---

## 6. Verification & Automated Test Suite

The test suite combines `pytest`, `pytest-cov`, and `hypothesis` for high reliability:

```bash
# Run pytest test suite
python -m pytest

# Run unit tests with code coverage report
python -m pytest --cov=cnmv_xbrl --cov-report=term-missing
```

### Performance Benchmarks
- **Test Results:** 53 passed unit tests in <35 seconds.
- **Code Coverage:** **100%** coverage across models, parser, taxonomy, and exporters.
- **Parsing Velocity:** Parses **5,000+ facts** in <1.0 second per document.

---

## 7. License & Citation

Distributed under the **MIT License**. See `LICENSE` for details.

If you use `cnmv-xbrl` in academic research or quantitative financial engineering, please cite:

```bibtex
@software{cnmv_xbrl_2026,
  author = {Marcos},
  title = {CNMV XBRL IIC: High-Performance Python Parser and Exporter for Spanish Fund Prospectuses},
  year = {2026},
  publisher = {GitHub},
  journal = {GitHub repository},
  url = {https://github.com/marcosagni98/cnmv-xbrl}
}
```
