freeports_analysis.output
Output module for financial data processing and file generation.
This module handles the transformation, serialization, and output of financial investment data extracted from PDF documents. It provides classes for representing financial instruments and functions for writing data in various output formats.
Functions
|
Transform investment results into structured data for file output. |
|
Attempt to convert a string to Currency, preserving Promise objects. |
|
Validate that a company name exists in the predefined companies list. |
|
Write financial data to files according to specified output profile and flags. |
Classes
|
Represents a bond investment with maturity and interest rate. |
|
Represents an equity investment (stocks, shares). |
|
Abstract base class representing a financial investment. |
- class freeports_analysis.output.Bond(*, company: Annotated[str, AfterValidator(func=validate_company)], company_match: str, subfund: Promise | str, nominal_quantity: Annotated[float, Gt(gt=0)] | None = None, market_value: Promise | Annotated[float, Gt(gt=0)], currency: Annotated[Promise | Currency, BeforeValidator(func=try_convert_to_currency, json_schema_input_type=PydanticUndefined)], perc_net_assets: Promise | Annotated[float, None, Interval(gt=None, ge=0.0, lt=1.0, le=None), None, None] | None = None, acquisition_cost: Promise | Annotated[float, Gt(gt=0)] | None = None, acquisition_currency: Annotated[Promise | Currency, BeforeValidator(func=try_convert_to_currency, json_schema_input_type=PydanticUndefined)] | None = None, maturity: date | None = None, interest_rate: Promise | Annotated[float, None, Interval(gt=None, ge=0.0, lt=1.0, le=None), None, None] | None = None)
Represents a bond investment with maturity and interest rate.
- maturity
Bond maturity date when principal is repaid
- Type:
Optional[datetime.date]
- interest_rate
Annual interest rate as a decimal value (e.g., 0.05 for 5%)
- Type:
Optional[PromisedInterestRate]
Notes
Bond investments represent debt securities that pay periodic interest and return the principal at maturity. The interest rate is stored as a decimal value (e.g., 0.05 represents 5% annual interest).
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'validate_assignment': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class freeports_analysis.output.Equity(*, company: Annotated[str, AfterValidator(func=validate_company)], company_match: str, subfund: Promise | str, nominal_quantity: Annotated[float, Gt(gt=0)] | None = None, market_value: Promise | Annotated[float, Gt(gt=0)], currency: Annotated[Promise | Currency, BeforeValidator(func=try_convert_to_currency, json_schema_input_type=PydanticUndefined)], perc_net_assets: Promise | Annotated[float, None, Interval(gt=None, ge=0.0, lt=1.0, le=None), None, None] | None = None, acquisition_cost: Promise | Annotated[float, Gt(gt=0)] | None = None, acquisition_currency: Annotated[Promise | Currency, BeforeValidator(func=try_convert_to_currency, json_schema_input_type=PydanticUndefined)] | None = None)
Represents an equity investment (stocks, shares).
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'validate_assignment': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class freeports_analysis.output.Investment(*, company: Annotated[str, AfterValidator(func=validate_company)], company_match: str, subfund: Promise | str, nominal_quantity: Annotated[float, Gt(gt=0)] | None = None, market_value: Promise | Annotated[float, Gt(gt=0)], currency: Annotated[Promise | Currency, BeforeValidator(func=try_convert_to_currency, json_schema_input_type=PydanticUndefined)], perc_net_assets: Promise | Annotated[float, None, Interval(gt=None, ge=0.0, lt=1.0, le=None), None, None] | None = None, acquisition_cost: Promise | Annotated[float, Gt(gt=0)] | None = None, acquisition_currency: Annotated[Promise | Currency, BeforeValidator(func=try_convert_to_currency, json_schema_input_type=PydanticUndefined)] | None = None)
Abstract base class representing a financial investment.
This class serves as the foundation for different types of financial instruments, providing common attributes and validation logic.
- company
Validated company name from predefined list
- Type:
Company
- company_match
Original company name as matched in the source document
- Type:
str
- subfund
Subfund identifier, may be a Promise for deferred resolution
- Type:
PromisedSubfund
- nominal_quantity
Number of units/shares held
- Type:
Optional[PositiveFloat]
- market_value
Current market value of the investment
- Type:
PromisedMarketValue
- currency
Currency of the market value
- Type:
PromisedCurrency
- perc_net_assets
Percentage of total net assets represented by this investment
- Type:
Optional[PromisedPercNetAsstes]
- acquisition_cost
Original acquisition cost
- Type:
Optional[PromisedAcquisitionCost]
- acquisition_currency
Currency of the acquisition cost
- Type:
Optional[PromisedAcquisitionCurrency]
Notes
This class uses Pydantic for data validation and supports Promise objects for deferred value resolution. All currency values are validated against the Currency enum, and company names are validated against the predefined companies list.
- fulfill_promises(mapping: Dict[str, Any]) None
Resolve all promise objects in this financial data instance.
Processes each attribute that may contain a Promise object, resolving it using the provided mapping and performing validation where required.
- Parameters:
mapping (PromisesResolutionMap) – Dictionary containing values to resolve promises from.
Notes
For attributes that require validation (perc_net_assets, company), the resolved values will be validated before assignment. This method iterates through all model attributes and resolves any Promise objects found, updating the instance in place.
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'validate_assignment': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- freeports_analysis.output.transform_to_files_schema(result_documents: List[Tuple[List[List[Investment]], str, str | None]], batch_mode: bool) Dict[str, Any]
Transform investment results into structured data for file output.
- Parameters:
result_documents (List[Tuple[List[List[Investment]], str, Optional[str]]]) – List of document results containing investment data, format info, and prefixes
batch_mode (bool) – Whether processing is in batch mode (affects output structure)
- Returns:
Dictionary containing: - ‘investments’: DataFrame with investment data - ‘additional_infos’: Dictionary with bond-specific information
- Return type:
Dict[str, Any]
Notes
This function processes investment data from multiple documents and pages, transforming it into a format suitable for file output. In batch mode, additional metadata (format and document identifier) is included. Bond-specific information (maturity, interest rate) is separated from the main investment data structure.
- freeports_analysis.output.try_convert_to_currency(value: str | Promise) Currency | Promise
Attempt to convert a string to Currency, preserving Promise objects.
- Parameters:
value (Union[str, Promise]) – The value to convert - either a currency string or Promise object
- Returns:
Currency enum if conversion successful, otherwise original Promise
- Return type:
- Raises:
KeyError – If the currency string is not a valid Currency enum member
Notes
This function is used as a Pydantic validator to handle both concrete currency values and Promise objects that will be resolved later.
- freeports_analysis.output.validate_company(value: str) str
Validate that a company name exists in the predefined companies list.
- Parameters:
value (str) – The company name to validate
- Returns:
The validated company name
- Return type:
str
- Raises:
ValueError – If the company name is not found in the COMPANIES list
Notes
This function is used as a Pydantic validator to ensure that only companies from the predefined list are accepted in financial data models.
- freeports_analysis.output.write_files(data: Dict[str, Any], out_path: str | Path, profile: OutStructureNormalMode | OutStructureBatchMode, flags: OutFlagsNormalMode | OutFlagsBatchMode) None
Write financial data to files according to specified output profile and flags.
- Parameters:
data (Dict[str, Any]) – Dictionary containing investment data to write
out_path (Union[str, Path]) – Output directory or file path
profile (Union[OutStructureNormalMode, OutStructureBatchMode]) – Output structure profile determining file organization
flags (Union[OutFlagsNormalMode, OutFlagsBatchMode]) – Output flags controlling compression and other options
- Raises:
ValueError – If the specified profile is not recognized
Notes
Supported output profiles: - REGULAR: Separate CSV and YAML files for investments and additional info - SINGLE_FILE: All data combined into a single CSV file - STRUCTURED: Directory-based structure with table and metadata files
Compression flags create tar.gz archives for directories or gzip for single files.
Modules
Data schema definitions for financial investment data validation. |