Skip to main content

Standard financial enumerations

Project description

finance enums

Standard financial enumerations

Build Status codecov License PyPI

Overview

finance-enums is the shared vocabulary layer for the finance-* stack. It exposes string-valued Python enums backed by Rust static data tables, plus structured currency metadata and a small frequency enum used by calendar-aware libraries.

The goal is to make identifiers boring and consistent: country codes, currencies, exchange codes, GICS-like sector taxonomy, security types, instrument types, portfolio labels, lifecycle states, order flags, trade sides, and time-in-force values all come from one package.

Quick start

from finance_enums import (
    CommodityType,
    ContractStyle,
    Currency,
    ExchangeCode,
    FundType,
    OptionExerciseType,
    OptionType,
    SecurityType,
    SettlementStatus,
    SettlementType,
    Sector,
    transaction_intent,
    UnderlyingAssetClass,
    exchange_record,
    exchange_records_by_country,
    build_cfi,
    parse_cfi,
    Frequency,
    to_frequency,
)

str(Currency.USD)                    # "USD"
Currency.USD.currency_name()         # "United States dollar"
Currency.USD.is_iso4217()            # True
Currency("e-CNY")                    # Currency.ECNY

ExchangeCode.XNYS.value              # "XNYS"
ExchangeCode.XNYS.record().region    # "Americas"
exchange_record("XNYS").market_name  # "NEW YORK STOCK EXCHANGE, INC."
len(exchange_records_by_country("US")) > 0

parse_cfi("ESVUFB").equity_type.value   # "Shares"
build_cfi(security_type=SecurityType.Option, option_type=OptionType.Call)  # "OCXXXX"
build_cfi(
    security_type=SecurityType.Option,
    option_type=OptionType.Call,
    option_exercise_type=OptionExerciseType.American,
    underlying_asset_class=UnderlyingAssetClass.Equity,
    settlement_type=SettlementType.Physical,
    contract_style=ContractStyle.Standardized,
)  # "OCASPS"
build_cfi(security_type=SecurityType.Currency)                              # "IFXXXP"
build_cfi(security_type=SecurityType.Commodity, commodity_type=CommodityType.Agriculture)  # "ITAXXX"
build_cfi(category="S", group="F")                                        # "SFXXXX"
transaction_intent("open_short").side.value                               # "Sell"
SettlementStatus.Settled.value                                             # "Settled"

Sector.InformationTechnology.value   # "InformationTechnology"
FundType.ETF is FundType.ExchangeTradedFund     # True
FundType("ETF").value                           # "ExchangeTradedFund"

to_frequency("monthly")             # Frequency.Month
Frequency.Month.periods_per_year     # 12
Frequency.Month.polars_truncate      # "1mo"

Enum families

The public Python API includes:

  • Countries: CountryCode, CountryCode3
  • Currencies: Currency, CurrencyRecord, CurrencyAliasRecord, currency_records, currency_alias_records
  • Venues: ExchangeCode, ExchangeRecord, exchange_record, exchange_records, exchange_records_by_country, exchange_records_by_operating_mic, exchange_records_by_parent_mic, exchange_records_by_status, exchange_records_by_region, exchange_records_by_market_category, MICMarketCategory, VenueRegulatoryFlag, exchange_records_by_market_category_type, exchange_records_by_regulatory_flag
  • Sector taxonomy: Sector, IndustryGroup, Industry, SubIndustry
  • Market structure: VenueType, MarketType, TradingSession, MarketState, AuctionType, SegmentType, MarketStatusReason
  • Identifier and notation: IdentifierType, TickerNamespace, PriceNotation, QuantityUnit, CurrencyRole
  • Instruments: SecurityType, InstrumentType, EquityType, OptionType, OptionExerciseType, BondType, CommodityType, EnergyType, MetalsType, AgricultureType, FundType, FundSubType, MutualFundEndedness, FutureType, FutureDeliveryType, SettlementType, DeliveryType, UnderlyingAssetClass, ContractStyle, PayoffStyle, ContractUnit, LegRole
  • Fixed income and financing: CouponType, CouponFrequency, DayCountConvention, AmortizationType, Seniority, CollateralType, MarginType, BorrowType, RepoType, FinancingType
  • Swaps and structured products: SwapType, SwapLegType, RateIndex, ResetFrequency, CompoundingMethod, StubType, BarrierType, AveragingMethod, ExoticOptionFeature
  • Post-trade and clearing: SettlementStatus, ClearingModel, ClearingHouse, FailsReason, AllocationMethod, GiveUpType
  • Benchmarks and index administration: BenchmarkType, IndexWeightingMethod, RebalanceFrequency, CorporateActionAdjustmentType, CalculationAgentType
  • Portfolio and fund structure: AccountType, BookType, PositionType, InventoryType, StrategyType, NettingType, VehicleWrapper, DistributionPolicy, ShareClassHedging, LiquidityTerm, RedemptionFrequency
  • Corporate actions and lifecycle: CorporateActionType, ListingStatus, SecurityStatus, ExerciseEventType, TenderOfferType, DelistingReason
  • CFI helpers: CFIClassification, parse_cfi, build_cfi, build_cfi_from_classification, validate_cfi_classification
  • Versioned enum schema helpers: EnumVariantRecord, EnumFamilySchema, enum_variant_records, enum_family_schemas, enum_schema, enum_schema_json, enum_export_capsule
  • Trading: OrderType, OrderStatus, ExecType, ExecutionInstruction, LiquidityFlag, PositionEffect, OpenClose, OrderCapacity, ShortSaleRestriction, Side, OrderFlag, TimeInForce, TradingType
  • Market data: QuoteCondition, TradeCondition, AggressorSide, CrossType, PriceType
  • Frequencies: Frequency, to_frequency

Documentation

See the Enums page for the enum families, metadata conventions, exchange-code relationship with finance-dates, and Rust/Python naming notes. See the API page for a reference and recipes.

Rust crate

The Rust crate is published as finance_enums on crates.io and imported as finance_enums in Rust code:

[dependencies]
finance_enums = "0.4.0"
use finance_enums::data::ExchangeCode_VARIANTS;

The Python package name is finance-enums; the Rust package uses an underscore because the original crates.io name cannot be renamed to the hyphenated spelling.

[!NOTE] This library was generated using copier from the Base Python Project Template repository.

Currency Metadata

Currency data is maintained from a structured Rust source of truth.

  • Each currency row includes a code, display name, and is_iso4217 flag.
  • Python exposes structured access through currency_records() and currency_alias_records().
  • Native consumers can re-extract the same immutable dataset through the versioned finance_enums.currency_export_v1 PyCapsule or the exported finance_enums_currency_export_v1 C ABI symbol.

Exchange Metadata

Exchange coverage is now backed by bundled ISO 10383 MIC records plus a small set of project-defined calendar families.

  • Python exposes structured exchange access through exchange_records() and ExchangeCode.record().
  • Python also exposes direct venue lookups through exchange_record() and indexed filters through exchange_records_by_country(), exchange_records_by_operating_mic(), exchange_records_by_parent_mic(), exchange_records_by_status(), exchange_records_by_region(), exchange_records_by_market_category(), exchange_records_by_market_category_type(), and exchange_records_by_regulatory_flag().
  • Each ExchangeRecord and ExchangeCode can derive a typed MIC market category through .market_category() and standards-backed regulatory flags through .regulatory_flags() / .has_regulatory_flag().
  • Bundled exchange metadata includes market name, legal entity, operating and parent MICs, market category, acronym, ISO country code, city, website, status, region, subregion, segment flag, and official/project provenance.
  • Project-defined non-ISO venue families remain available for downstream calendar consumers: PYPR, SIMU, FOREX, CRYPTO, SIFMA_US, ICE_US, and CFE.

Native C ABI

finance-enums ships a versioned C ABI for immutable metadata and enum-family discovery.

  • The core Rust crate exports finance_enums_currency_export_v1 and finance_enums_exchange_export_v1.
  • The core Rust crate also exports finance_enums_enum_export_v1, a flat enum-family / variant table that lets C and C++ consumers discover every Rust-backed enum without needing Python.
  • The public header lives at finance_enums/include/finance_enums.h; hatch-rs validates it as an expected artifact and wheel builds install it to include/finance_enums/finance_enums.h.
  • Wheels also bundle a standalone shared library inside finance_enums/lib/ so downstream C or C++ code can link against the same versioned export surface.
  • Python exposes the same schema as dataclasses through enum_variant_records() and enum_family_schemas(), and as deterministic JSON through enum_schema_json() for Arrow/JSON schema bridges.

Trading Intent Helpers

Side intentionally remains trade direction only: None, Buy, and Sell. Short-sale and cover semantics are represented by combining Side with PositionEffect, OpenClose, and PositionType.

from finance_enums import transaction_intent

transaction_intent("open_long")   # Buy + Open + Long
transaction_intent("close_long")  # Sell + Close + Long
transaction_intent("open_short")  # Sell + Open + Short
transaction_intent("cover_short") # Buy + Close + Short

This follows the FIX-style separation between side/direction and position effect while giving downstream transaction schemas one canonical helper for common intents.

Reference Data Maintenance

The repository includes deterministic local tooling for standards-backed data maintenance.

  • scripts/generate_reference_data.py --check validates that rust/src/exchange_codes.rs remains aligned with the vendored MIC records in rust/src/exchange_records/*.tsv; --write can regenerate the compatibility table.
  • scripts/snapshot_reference_diffs.py --check compares current MIC, currency, country, and future-related snapshots with reference_snapshots/standards.json; --write refreshes the checked-in snapshot after an intentional data update.
  • make develop now performs an editable install with build isolation, and make rebuild-extension rebuilds the local extension in-place after Rust or PyO3 changes.

CFI Helpers

finance-enums now includes a broader ISO 10962 / CFI parser and builder.

  • parse_cfi() maps supported families into the existing enum surface for equities, bonds, funds, options, futures, swaps, financing, spot FX, spot commodities, forwards, spreads, and indices, while preserving the raw category, group, and attribute characters.
  • build_cfi() emits category/group-correct codes for the supported enum-backed families and also accepts raw category, group, and attributes inputs for ISO categories that the library does not model with dedicated enums yet.
  • build_cfi_from_classification() and CFIClassification.to_code() provide a structured round-trip path from typed enum-backed classifications back into ISO 10962 strings.
  • validate_cfi_classification() and CFIClassification.validate() check that the typed fields, raw CFI positions, and stored code all agree before downstream code persists or republishes a classification.
  • Listed options and futures now expose typed derivative attributes for underlier asset class, settlement or delivery semantics, and contract standardization instead of leaving those positions opaque.
  • Non-listed options, forwards, and strategies now support rate, credit, mixed-asset, and other high-value CFI underlier groups through UnderlyingAssetClass.
  • SecurityType.PerpetualFuture is available as a standalone library type and builds through the ISO futures CFI envelope, because ISO 10962 does not encode a dedicated perpetual-future category.
  • Remaining unsupported enum families still raise NotImplementedError during generation rather than guessing invalid codes.

Live Reference Tests

Live standards coverage tests are part of the normal pytest suite and are marked live_source.

  • Default local test runs skip them automatically.
  • Enable them by running FINANCE_ENUMS_RUN_LIVE_TESTS=1 /opt/homebrew/bin/python -m pytest -q finance_enums/tests.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

finance_enums-0.5.1.tar.gz (871.3 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

finance_enums-0.5.1-cp310-abi3-win_amd64.whl (501.8 kB view details)

Uploaded CPython 3.10+Windows x86-64

finance_enums-0.5.1-cp310-abi3-manylinux_2_28_x86_64.whl (782.0 kB view details)

Uploaded CPython 3.10+manylinux: glibc 2.28+ x86-64

finance_enums-0.5.1-cp310-abi3-macosx_11_0_arm64.whl (687.6 kB view details)

Uploaded CPython 3.10+macOS 11.0+ ARM64

File details

Details for the file finance_enums-0.5.1.tar.gz.

File metadata

  • Download URL: finance_enums-0.5.1.tar.gz
  • Upload date:
  • Size: 871.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for finance_enums-0.5.1.tar.gz
Algorithm Hash digest
SHA256 ff5af6b04d8bb21d0fda8ae4e2753b8b7eb2ac87d8650b4a8fd27c903254a102
MD5 8910e59f1a319f250a0bc7c6cd4d98d5
BLAKE2b-256 d02f5ddded15ea576c85df7db41696fbaacc686b3dd3c14dfc6d7341cd0622fd

See more details on using hashes here.

File details

Details for the file finance_enums-0.5.1-cp310-abi3-win_amd64.whl.

File metadata

File hashes

Hashes for finance_enums-0.5.1-cp310-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 02129b8c665e85b3dd8fb76c10dee81fae253ff87579c6b9c70e88f9aa0445df
MD5 5a33e5acc036454ceccd067349050faa
BLAKE2b-256 3213b99ae4d7ec63e86a7f861e1b122f18f12408cc7046ad6998dc11e773bf5d

See more details on using hashes here.

File details

Details for the file finance_enums-0.5.1-cp310-abi3-manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for finance_enums-0.5.1-cp310-abi3-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 c05401c7fc66d3704d7d989e3e2dee4655f5dcc558c52a20ec4e1e083f964747
MD5 a51bcc1b0c761ba795d1ec180e50cba8
BLAKE2b-256 c3563c213ac43370ccf4609824b0af8d14db67b2fbeb747b855fcd73b47c2474

See more details on using hashes here.

File details

Details for the file finance_enums-0.5.1-cp310-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for finance_enums-0.5.1-cp310-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 d579642a961e0531f2e7d791f4850fe67379346325da28b766f7123dfb63a0a6
MD5 65305f21d98eb91ff008d14f777ce0c2
BLAKE2b-256 c12ab61c382fd3b7f935466c5a739c01cb730522777d922b3345b92b07a5658c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page