Skip to content

kotak

Kotak mapping adapter.

Kotak's raw file needs two field forms no other broker uses, so this adapter extends _field rather than adding them to the shared transform registry:

  • {constant: <value>} supplies a fixed value where the raw file has no usable column at all, which is the case for the lot and tick sizes of the NSE commodity and currency underlying segments.
  • {columns: [dstrikeprice, lprecision], transform: dynamic_precision_strike} divides the strike by ten raised to a precision that varies per row: two for equity and MCX commodity contracts, four for currency ones. NSE commodity options are the exception that proves the need for it — their true scale is always four decimal places even though the row reports a precision of two, so they name the fixed divide_by_10_thousand transform instead.

Expiry dates come in two flavours on this one broker. NSE contracts count seconds from 1980-01-01, which is what the kotak_expiry_epoch transform exists for; BSE and MCX contracts are plain Unix epochs and use unix_epoch_date.

The classification overrides are the ISIN splits that no equality rule can express: an NSE cash row whose ISIN is fund-prefixed is an exchange traded fund rather than an equity, a BSE row confirmed as a fund by cross-broker agreement is one whatever its group says, and both bond segments require a real non-fund ISIN. classify_extra restores the dual membership that a BSE row genuinely has when it is both a real security and a confirmed exchange traded fund.

Classes:

Name Description
KotakMappingAdapter

Mapping adapter for Kotak, covering 31 real segments plus the uncategorised buckets.

Functions:

Name Description
isin_is_fund

Check whether an ISIN belongs to the fund family, which India marks with an INF prefix.

isin_valid_bond

Check whether an ISIN can identify a bond, meaning it is present and is not a fund ISIN.

KotakMappingAdapter

KotakMappingAdapter()

Bases: BrokerMappingAdapter

Mapping adapter for Kotak, covering 31 real segments plus the uncategorised buckets.

Example programs

examples/stock_brokers/instruments/mapping/kotak/KotakMappingAdapter/example_1_isin_splits_and_scales.py
"""Classifies Kotak rows whose segment depends on the ISIN, and reads strikes and expiries in Kotak's several scales.

Kotak's groups say little about what a row really is, so `KotakMappingAdapter.classify` looks at the ISIN: an NSE equity-group row with a fund ISIN is an exchange traded fund, a BSE row with one is left uncategorised, bonds need a real non-fund ISIN, and BSE group E rows whose description starts with "INAV" (an indicative value, not a fund) are dropped. A BSE row that other brokers confirm as an exchange traded fund but that also has a company ISIN is both things, and `classify_extra` returns its second segment.

`to_identity` strips Kotak's group suffix, so `NBIFIN-EQ` is stored as NBIFIN. Behind it, Kotak's field reader handles the scales: an NSE expiry counts seconds from 1980-01-01, a BSE one from 1970, and a BSE option strike is divided by ten raised to the row's own precision. Kotak's currency underlying rows have no lot or tick size, so both are stored as None.

`run` normally gathers the BSE exchange traded fund list from the database; this program sets it by hand to one symbol, so no database is needed. `uncategorised_exchange` shows where a dropped row is filed. The dual-membership row is shaped by hand to show the case; its symbol is made up.

Run it from the project root:

    python examples/stock_brokers/instruments/mapping/kotak/KotakMappingAdapter/example_1_isin_splits_and_scales.py
"""

from stock_brokers.instruments.mapping.kotak import (
    KotakMappingAdapter,
)


class IsinSplitsAndScalesExample:
    """Classifies eight hand-written Kotak rows and prints each one's segments, identity and sizes.

    Attributes:
        adapter (KotakMappingAdapter): The adapter being shown.
        raw_rows (list): The raw rows, as dictionaries of text columns.
    """

    def __init__(self):
        """Builds the adapter, sets the list `run` would gather, and writes the rows.

        Returns:
            None: This method returns nothing.
        """
        self.adapter = KotakMappingAdapter()
        self.adapter.bse_etf_symbols = {
            'DUALETF',
        }
        self.raw_rows = [
            self.raw_row('nse_cm', 'NSE', 'EQ', None, '4749', 'NBIFIN-EQ', 'NBIFIN', 'INE918K01019', 'BAJAJ HOLDINGS'),
            self.raw_row('nse_cm', 'NSE', 'EQ', None, '10576', 'NIFTYBEES-EQ', 'NIFTYBEES', 'INF204KB14I2', 'NIPPON INDIA ETF NIFTY 50 BEES'),
            self.raw_row('nse_cm', 'NSE', 'GS', None, '15542', '762GS2036-GS', '762GS2036', 'IN0020160019', 'GOI LOAN 7.62% 2036'),
            self.raw_row('bse_cm', 'BSE', 'E', None, '540005', 'INAVGOLD', 'INAVGOLD', None, 'INAV OF A GOLD ETF'),
            self.raw_row('bse_cm', 'BSE', 'B', None, '543999', 'DUALETF', 'DUALETF', 'INE000X01011', 'A FUND LISTED AS AN EQUITY'),
            self.raw_row('nse_fo', 'NFO', None, 'OPTIDX', '40215', 'NIFTY26OCT25000CE', 'NIFTY', None, None),
            self.raw_row('bse_fo', 'BFO', None, 'SO', '1165432', 'IRFC26OCT102.5CE', 'IRFC', None, None),
            self.raw_row('cde_fo', 'CDS', None, 'UNDCUR', '1', 'USDINR', 'USDINR', None, None),
        ]
        self.raw_rows[5]['lexpirydate'] = '1477578600'
        self.raw_rows[5]['dstrikeprice'] = '2500000'
        self.raw_rows[5]['poptiontype'] = 'CE'
        self.raw_rows[6]['lexpirydate'] = '1793268000'
        self.raw_rows[6]['dstrikeprice'] = '10250'
        self.raw_rows[6]['lprecision'] = '2'
        self.raw_rows[6]['poptiontype'] = 'CE'

    def raw_row(self, exchange_segment, exchange, group, instrument_type, token, trading_symbol, symbol_name, isin, description):
        """Builds one raw row in the shape of `kotak.instruments`.

        Args:
            exchange_segment (str): The `pexchseg` column, such as nse_cm or bse_fo.
            exchange (str): The `pexchange` column.
            group (str | None): The `pgroup` column, which holds the series for cash rows.
            instrument_type (str | None): The `pinsttype` column, for derivatives.
            token (str): The `psymbol` column, Kotak's token.
            trading_symbol (str): The `ptrdsymbol` column.
            symbol_name (str): The `psymbolname` column.
            isin (str | None): The `pisin` column.
            description (str | None): The `pdesc` column.

        Returns:
            dict: The raw row, every column as text as the raw table stores it.
        """
        return {
            'psymbol': token,
            'pgroup': group,
            'pexchseg': exchange_segment,
            'pinsttype': instrument_type,
            'psymbolname': symbol_name,
            'ptrdsymbol': trading_symbol,
            'poptiontype': None,
            'pisin': isin,
            'pdesc': description,
            'dticksize': '5',
            'llotsize': '1',
            'lexpirydate': None,
            'lprecision': None,
            'dstrikeprice': None,
            'pexchange': exchange,
        }

    def run(self):
        """Prints each row's segments, identity and sizes, or where an unmatched row is filed.

        Returns:
            None: This method returns nothing.
        """
        for raw_row in self.raw_rows:
            label = f'{raw_row["pexchseg"]} {raw_row["ptrdsymbol"]}'
            segment_configuration = self.adapter.classify(raw_row)
            if segment_configuration is None:
                exchange = self.adapter.uncategorised_exchange(raw_row)
                print(f'{label} -> no segment, filed under {exchange}_uncategorised')
                continue
            extra_segments = []
            for extra_configuration in self.adapter.classify_extra(raw_row):
                extra_segments.append(extra_configuration['segment'])
            identity = self.adapter.to_identity(raw_row, segment_configuration)
            broker_fields = self.adapter.to_broker_fields(raw_row, segment_configuration)
            print(f'{label} -> {segment_configuration["segment"]}, also {extra_segments}')
            print(f'    identity {identity}')
            print(f'    lot size {broker_fields["lot_size"]}, tick size {broker_fields["tick_size"]}')


if __name__ == '__main__':
    IsinSplitsAndScalesExample().run()

It prints:

nse_cm NBIFIN-EQ -> nse_equities, also []
    identity {'symbol': 'NBIFIN'}
    lot size 1.0, tick size 0.05
nse_cm NIFTYBEES-EQ -> nse_exchange_traded_funds, also []
    identity {'symbol': 'NIFTYBEES'}
    lot size 1.0, tick size 0.05
nse_cm 762GS2036-GS -> nse_fixed_income, also []
    identity {'symbol': 'IN0020160019'}
    lot size 1.0, tick size 0.05
bse_cm INAVGOLD -> no segment, filed under bse_uncategorised
bse_cm DUALETF -> bse_exchange_traded_funds, also ['bse_equities']
    identity {'symbol': 'DUALETF'}
    lot size 1.0, tick size 0.05
nse_fo NIFTY26OCT25000CE -> nse_equity_index_options, also []
    identity {'underlying_symbol': 'NIFTY', 'expiry_date': datetime.date(2026, 10, 27), 'strike_price': 25000.0, 'option_type': 'CE'}
    lot size 1.0, tick size 0.05
bse_fo IRFC26OCT102.5CE -> bse_equity_options, also []
    identity {'underlying_symbol': 'IRFC', 'expiry_date': datetime.date(2026, 10, 29), 'strike_price': 102.5, 'option_type': 'CE'}
    lot size 1.0, tick size 0.05
cde_fo USDINR -> nse_currencies, also []
    identity {'symbol': 'USDINR'}
    lot size None, tick size None
examples/stock_brokers/instruments/mapping/kotak/KotakMappingAdapter/example_2_mapping_one_day.py
"""Maps one day of Kotak rows, where one BSE row is written into two segments.

`KotakMappingAdapter.run` first asks the other brokers' tables which BSE symbols are real exchange traded funds, then hands over to the shared mapping run, which reads Kotak's raw rows, classifies them, and writes `unified.instruments` and `unified.broker_mappings` in one transaction. A BSE row that is a confirmed exchange traded fund and also carries a company ISIN is written twice, once as a fund and once as an equity, because `classify_extra` returns the second segment.

The adapter normally talks to PostgreSQL, so this program replaces its `engine` with a stand-in. The stand-in connection answers queries by matching a piece of their text: the raw-row query gets two hand-written Kotak rows, and Flattrade's BSE fund-group query names DUALETF, a made-up symbol shaped to show the dual membership. Every other cross-broker query gets no rows, and every write is recorded instead of run. pandas only reads through something it recognises as an SQLAlchemy connectable, and it recognises one by the `ConnectionEventsTarget` base class, so the stand-in connection inherits from that class.

Notice that the summary counts two raw rows but three segment memberships and three instruments, and that the two DUALETF instruments share one Kotak token.

Run it from the project root:

    python examples/stock_brokers/instruments/mapping/kotak/KotakMappingAdapter/example_2_mapping_one_day.py
"""

import collections
import datetime

from sqlalchemy.engine import interfaces

from stock_brokers.instruments.mapping.kotak import (
    KotakMappingAdapter,
)


class StandInResult:
    """A stand-in for an SQLAlchemy result holding a fixed set of rows.

    Attributes:
        columns (list): The column names.
        rows (list): The rows, as dictionaries.
    """

    def __init__(self, rows):
        """Holds the rows.

        Args:
            rows (list): The rows, as dictionaries that all share the same keys.

        Returns:
            None: This method returns nothing.
        """
        self.rows = rows
        self.columns = []
        if rows:
            self.columns = list(rows[0])

    def keys(self):
        """The column names, as pandas asks for them.

        Returns:
            list: The column names.
        """
        return self.columns

    def fetchall(self):
        """Every row as a plain tuple, as pandas asks for them.

        Returns:
            list: The rows as tuples in column order.
        """
        tuples = []
        for row in self.rows:
            tuples.append(tuple(row.values()))
        return tuples

    def all(self):
        """Every row as a named tuple, so a column can be read as an attribute.

        Returns:
            list: The rows as named tuples.
        """
        row_type = collections.namedtuple('StandInRow', self.columns)
        named_rows = []
        for row in self.rows:
            named_rows.append(row_type(**row))
        return named_rows


class StandInConnection(interfaces.ConnectionEventsTarget):
    """A stand-in for a PostgreSQL connection that answers queries from prepared rows and records writes.

    Attributes:
        answers (list): Pairs of (a piece of query text, the rows to answer with).
        unanswered_queries (int): How many queries matched no prepared answer and got no rows.
        writes (list): Each write statement's first words and its parameters.
    """

    def __init__(self, answers):
        """Holds the prepared answers and starts with nothing recorded.

        Args:
            answers (list): Pairs of (a piece of query text, the rows to answer with).

        Returns:
            None: This method returns nothing.
        """
        self.answers = answers
        self.unanswered_queries = 0
        self.writes = []

    def __enter__(self):
        """Opens the connection for a `with` block.

        Returns:
            StandInConnection: This connection.
        """
        return self

    def __exit__(self, exception_type, exception, traceback):
        """Closes the connection at the end of a `with` block.

        Args:
            exception_type (type | None): The type of any exception raised in the block.
            exception (BaseException | None): Any exception raised in the block.
            traceback (object | None): The traceback of any exception raised in the block.

        Returns:
            bool: False, so any exception carries on.
        """
        return False

    def execute(self, statement, parameters=None):
        """Answers a query from the prepared rows, or records a write.

        Args:
            statement (sqlalchemy.sql.elements.TextClause): The statement to run.
            parameters (dict | list | None): Its bound parameters.

        Returns:
            StandInResult: The prepared rows whose text matches, otherwise an empty result.
        """
        sql = ' '.join(str(statement).split())
        if not sql.startswith('SELECT'):
            self.writes.append((' '.join(sql.split()[:3]), parameters))
            return StandInResult([])
        for query_text, rows in self.answers:
            if query_text in sql:
                return StandInResult(rows)
        self.unanswered_queries += 1
        return StandInResult([])


class StandInEngine:
    """A stand-in for an SQLAlchemy engine that always hands out the same stand-in connection.

    Attributes:
        connection (StandInConnection): The connection handed out.
    """

    def __init__(self, connection):
        """Holds the connection to hand out.

        Args:
            connection (StandInConnection): The connection handed out.

        Returns:
            None: This method returns nothing.
        """
        self.connection = connection

    def connect(self):
        """Hands out the connection for reading.

        Returns:
            StandInConnection: The connection.
        """
        return self.connection

    def begin(self):
        """Hands out the connection for one transaction.

        Returns:
            StandInConnection: The connection.
        """
        return self.connection


class MappingOneDayExample:
    """Maps two Kotak rows for one date and prints what would be written.

    Attributes:
        mapping_date (datetime.date): The snapshot date being mapped.
        connection (StandInConnection): The stand-in connection.
        adapter (KotakMappingAdapter): The adapter being shown, using the stand-in engine.
    """

    def __init__(self):
        """Builds the adapter and swaps its engine for the stand-in.

        Returns:
            None: This method returns nothing.
        """
        self.mapping_date = datetime.date(2026, 9, 28)
        raw_rows = [
            self.raw_row('nse_cm', 'EQ', '4749', 'NBIFIN-EQ', 'INE918K01019'),
            self.raw_row('bse_cm', 'B', '543999', 'DUALETF', 'INE000X01011'),
        ]
        flattrade_fund_group = [
            {
                'symbol': 'DUALETF',
            },
        ]
        answers = [
            (
                'SELECT * FROM kotak.instruments',
                raw_rows,
            ),
            (
                'FROM flattrade.instruments WHERE download_date = :d AND exchange = \'BSE\' AND instrument = \'E\'',
                flattrade_fund_group,
            ),
        ]
        self.connection = StandInConnection(answers)
        self.adapter = KotakMappingAdapter()
        self.adapter.engine = StandInEngine(self.connection)

    def raw_row(self, exchange_segment, group, token, trading_symbol, isin):
        """Builds one cash-market raw row in the shape of `kotak.instruments`.

        Args:
            exchange_segment (str): The `pexchseg` column, nse_cm or bse_cm.
            group (str): The `pgroup` column.
            token (str): The `psymbol` column, Kotak's token.
            trading_symbol (str): The `ptrdsymbol` column.
            isin (str): The `pisin` column.

        Returns:
            dict: The raw row, every column as text as the raw table stores it.
        """
        return {
            'psymbol': token,
            'pgroup': group,
            'pexchseg': exchange_segment,
            'pinsttype': None,
            'psymbolname': trading_symbol,
            'ptrdsymbol': trading_symbol,
            'pisin': isin,
            'pdesc': trading_symbol,
            'dticksize': '1',
            'llotsize': '1',
            'download_date': self.mapping_date,
        }

    def run(self):
        """Maps the day and prints the summary and the rows written.

        Returns:
            None: This method returns nothing.
        """
        summary = self.adapter.run(self.mapping_date)
        print(f'BSE exchange traded funds from other brokers: {sorted(self.adapter.bse_etf_symbols)}')
        print(f'Cross-broker queries that found nothing: {self.connection.unanswered_queries}')
        print(f'Summary: raw rows {summary["raw_rows"]}, matched {summary["matched"]}, memberships {summary["memberships"]}, instruments {summary["instruments_upserted"]}')
        for statement, parameters in self.connection.writes:
            print(statement)
            if not isinstance(parameters, list):
                continue
            for row in parameters:
                if 'segment' in row:
                    print(f'  {row["instrument_id"][:8]} {row["segment"]}: {row["symbol"]}')
                else:
                    print(f'  {row["instrument_id"][:8]} token {row["broker_token"]}, tick size {row["tick_size"]}')


if __name__ == '__main__':
    MappingOneDayExample().run()

It prints:

kotak: 2/2 raw row(s) classified, 0 uncategorised, 3 segment membership(s), 3 distinct instrument(s), 0 error(s).
BSE exchange traded funds from other brokers: ['DUALETF']
Cross-broker queries that found nothing: 10
Summary: raw rows 2, matched 2, memberships 3, instruments 3
DELETE FROM unified.broker_mappings
INSERT INTO unified.instruments
  1ed7ce71 nse_equities: NBIFIN
  7ce5b92e bse_exchange_traded_funds: DUALETF
  b7ed1cc6 bse_equities: DUALETF
INSERT INTO unified.broker_mappings
  1ed7ce71 token 4749, tick size 0.01
  7ce5b92e token 543999, tick size 0.01
  b7ed1cc6 token 543999, tick size 0.01

Load and validate the broker's rules file and create the database engine.

Raises:

Type Description
NotImplementedError

If the subclass did not set BROKER_NAME.

ValueError

If the rules file fails validation.

FileNotFoundError

If the broker has no rules file.

Example programs

examples/stock_brokers/instruments/mapping/base/BrokerMappingAdapter/example_1_classifying_rows_by_rules.py
"""Classifies three raw instrument rows using nothing but a broker's rules file.

`BrokerMappingAdapter` is the base class every broker's mapping adapter subclasses. A subclass only has to name its broker in `BROKER_NAME`, and the base class loads the matching rules file from `stock_brokers/instruments/mapping/utilities/rules/`, checks it against the canonical segment vocabulary, and classifies rows by plain equality rules. This program's subclass sets `BROKER_NAME` to Dhan and overrides nothing, so every answer below comes from the base class and Dhan's rules file alone, without the extra filters the real `DhanMappingAdapter` adds.

The rows are written out by hand in the shape of `dhan.instruments`, where every column is text. The adapter builds a database engine when it is constructed, but an engine does not connect until it is used, and this program never asks it to, so nothing touches PostgreSQL.

For each row the program prints the segment the rules chose, any extra segments (the base class never adds any), the identity fields that go into the instrument id, the broker's own fields, and the deterministic instrument id. The third row matches no rule. The base class cannot tell which exchange it belongs to, so it falls into the unprefixed `uncategorised` segment, and the run would store its token as its symbol.

Run it from the project root:

    python examples/stock_brokers/instruments/mapping/base/BrokerMappingAdapter/example_1_classifying_rows_by_rules.py
"""

from stock_brokers.instruments.mapping import base
from stock_brokers.instruments.mapping.base import (
    BrokerMappingAdapter,
)


class DhanRulesOnlyAdapter(BrokerMappingAdapter):
    """A mapping adapter that uses Dhan's rules file and nothing but the base class's behaviour."""

    BROKER_NAME = 'dhan'


class ClassifyingRowsByRulesExample:
    """Runs three hand-written Dhan rows through the base class's rules engine and prints the result.

    Attributes:
        adapter (DhanRulesOnlyAdapter): The adapter being shown.
        raw_rows (list): The raw rows to classify, as dictionaries of text columns.
    """

    def __init__(self):
        """Builds the adapter and the three raw rows.

        Returns:
            None: This method returns nothing.
        """
        self.adapter = DhanRulesOnlyAdapter()
        self.raw_rows = [
            {
                'exch_id': 'NSE',
                'segment': 'E',
                'security_id': '1594',
                'isin': 'INE009A01021',
                'instrument': 'EQUITY',
                'underlying_symbol': 'INFY',
                'symbol_name': 'INFOSYS LIMITED',
                'display_name': 'Infosys',
                'instrument_type': 'ES',
                'series': 'EQ',
                'lot_size': '1.0',
                'sm_expiry_date': None,
                'strike_price': None,
                'option_type': None,
                'tick_size': '10.0',
            },
            {
                'exch_id': 'NSE',
                'segment': 'D',
                'security_id': '40215',
                'isin': None,
                'instrument': 'OPTIDX',
                'underlying_symbol': 'NIFTY',
                'symbol_name': 'NIFTY-Oct2026-25000-CE',
                'display_name': 'NIFTY 27 OCT 25000 CALL',
                'instrument_type': 'OP',
                'series': None,
                'lot_size': '75.0',
                'sm_expiry_date': '2026-10-27',
                'strike_price': '25000.00000',
                'option_type': 'CE',
                'tick_size': '5.0',
            },
            {
                'exch_id': 'NSE',
                'segment': 'X',
                'security_id': '990001',
                'isin': None,
                'instrument': 'SPREAD',
                'underlying_symbol': '',
                'symbol_name': 'TEST SPREAD',
                'display_name': 'Test spread',
                'instrument_type': 'SP',
                'series': None,
                'lot_size': '1.0',
                'sm_expiry_date': None,
                'strike_price': None,
                'option_type': None,
                'tick_size': '0',
            },
        ]

    def run(self):
        """Prints how the rules file classifies each row.

        Returns:
            None: This method returns nothing.
        """
        equities = self.adapter.segment_config('nse_equities')
        print(f'Rules file: {self.adapter.config["raw_table"]}, {len(self.adapter.config["segments"])} segments')
        print(f'nse_equities is a {equities["shape"]} on {equities["exchange"]} with {len(equities["rules"])} rules')
        print(f'Unconfigured segment: {self.adapter.segment_config("nse_bonds")}')
        for raw_row in self.raw_rows:
            print()
            print(f'Row {raw_row["security_id"]} ({raw_row["symbol_name"]})')
            segment_configuration = self.adapter.classify(raw_row)
            if segment_configuration is None:
                exchange = self.adapter.uncategorised_exchange(raw_row)
                print(f'  No rule matched, and the base class finds no exchange: {exchange}')
                segment_configuration = self.adapter.segment_config('uncategorised')
            extra_segments = self.adapter.classify_extra(raw_row)
            identity = self.adapter.to_identity(raw_row, segment_configuration)
            broker_fields = self.adapter.to_broker_fields(raw_row, segment_configuration)
            identifier = base.instrument_id(
                segment_configuration['exchange'],
                segment_configuration['segment'],
                segment_configuration['shape'],
                identity,
            )
            print(f'  Segment: {segment_configuration["segment"]} ({segment_configuration["shape"]})')
            print(f'  Extra segments: {extra_segments}')
            print(f'  Identity: {identity}')
            print(f'  Broker fields: {broker_fields}')
            print(f'  Instrument id: {identifier}')


if __name__ == '__main__':
    ClassifyingRowsByRulesExample().run()

It prints:

Rules file: dhan.instruments, 32 segments
nse_equities is a security on nse with 2 rules
Unconfigured segment: None

Row 1594 (INFOSYS LIMITED)
  Segment: nse_equities (security)
  Extra segments: []
  Identity: {'symbol': 'INFY'}
  Broker fields: {'broker_token': '1594', 'broker_symbol': 'Infosys', 'order_symbol': None, 'lot_size': 1.0, 'tick_size': 0.1}
  Instrument id: f310e1b0-e082-5b16-808a-25f741abb9de

Row 40215 (NIFTY-Oct2026-25000-CE)
  Segment: nse_equity_index_options (option)
  Extra segments: []
  Identity: {'underlying_symbol': 'NIFTY', 'expiry_date': datetime.date(2026, 10, 27), 'strike_price': 25000.0, 'option_type': 'CE'}
  Broker fields: {'broker_token': '40215', 'broker_symbol': 'NIFTY-Oct2026-25000-CE', 'order_symbol': None, 'lot_size': 75.0, 'tick_size': 0.05}
  Instrument id: fe85c704-ce49-5190-b068-d4d3646ed162

Row 990001 (TEST SPREAD)
  No rule matched, and the base class finds no exchange: None
  Segment: uncategorised (security)
  Extra segments: []
  Identity: {'symbol': ''}
  Broker fields: {'broker_token': '990001', 'broker_symbol': 'Test spread', 'order_symbol': None, 'lot_size': 1.0, 'tick_size': None}
  Instrument id: 55a8952d-9071-5670-a4fe-a5384d3876bd
examples/stock_brokers/instruments/mapping/base/BrokerMappingAdapter/example_2_mapping_one_day.py
"""Maps one day's raw rows into the two unified tables, against a stand-in database.

`run` is what the daily mapping job calls for each broker. It reads the broker's raw rows for one date with `read_raw_rows`, classifies each row, and then, inside one transaction, deletes that broker's mappings for the date and upserts one row per instrument into `unified.instruments` and one per broker mapping into `unified.broker_mappings`. It returns a summary and prints a one-line report.

The adapter normally reads and writes PostgreSQL, so this program replaces its `engine` with a small stand-in. The stand-in connection answers the raw-row query with four hand-written rows in the shape of `dhan.instruments`, and records every other statement it is sent instead of running it. pandas only reads through something it recognises as an SQLAlchemy connectable, and it recognises one by the `ConnectionEventsTarget` base class, so the stand-in connection inherits from that class and nothing else.

The subclass uses Dhan's rules file and overrides nothing. The fourth row has a strike price that is not a number, so building its identity fails; `run` records that as an error and carries on with the other rows rather than stopping. The unmatched row is stored under its token as its symbol, and its tick size of 5.0 is kept as written, because Dhan's rules divide the tick size by 100 only in the real segments and not in the uncategorised one. The last lines show that a subclass which forgets to set `BROKER_NAME` cannot be built.

Run it from the project root:

    python examples/stock_brokers/instruments/mapping/base/BrokerMappingAdapter/example_2_mapping_one_day.py
"""

import datetime

from sqlalchemy.engine import interfaces

from stock_brokers.instruments.mapping.base import (
    BrokerMappingAdapter,
)


class DhanRulesOnlyAdapter(BrokerMappingAdapter):
    """A mapping adapter that uses Dhan's rules file and nothing but the base class's behaviour."""

    BROKER_NAME = 'dhan'


class UnnamedAdapter(BrokerMappingAdapter):
    """A mapping adapter that forgets to name its broker."""


class StandInResult:
    """A stand-in for an SQLAlchemy result holding a fixed set of rows.

    Attributes:
        columns (list): The column names.
        rows (list): The rows, as tuples in column order.
    """

    def __init__(self, columns, rows):
        """Holds the columns and rows.

        Args:
            columns (list): The column names.
            rows (list): The rows, as tuples in column order.

        Returns:
            None: This method returns nothing.
        """
        self.columns = columns
        self.rows = rows

    def keys(self):
        """The column names, as pandas asks for them.

        Returns:
            list: The column names.
        """
        return self.columns

    def fetchall(self):
        """Every row, as pandas asks for them.

        Returns:
            list: The rows.
        """
        return self.rows

    def all(self):
        """Every row, as the adapter's own queries ask for them.

        Returns:
            list: The rows.
        """
        return self.rows


class StandInConnection(interfaces.ConnectionEventsTarget):
    """A stand-in for a PostgreSQL connection that serves one raw table and records every other statement.

    Attributes:
        raw_table (str): The raw table whose rows this connection serves.
        raw_rows (list): The raw rows, as dictionaries of column values.
        statements (list): Each recorded statement's first line and its parameters.
    """

    def __init__(self, raw_table, raw_rows):
        """Holds the raw rows and starts with no statements recorded.

        Args:
            raw_table (str): The raw table whose rows this connection serves.
            raw_rows (list): The raw rows, as dictionaries of column values.

        Returns:
            None: This method returns nothing.
        """
        self.raw_table = raw_table
        self.raw_rows = raw_rows
        self.statements = []

    def __enter__(self):
        """Opens the connection for a `with` block.

        Returns:
            StandInConnection: This connection.
        """
        return self

    def __exit__(self, exception_type, exception, traceback):
        """Closes the connection at the end of a `with` block.

        Args:
            exception_type (type | None): The type of any exception raised in the block.
            exception (BaseException | None): Any exception raised in the block.
            traceback (object | None): The traceback of any exception raised in the block.

        Returns:
            bool: False, so any exception carries on.
        """
        return False

    def execute(self, statement, parameters=None):
        """Answers the raw-row query from the held rows and records anything else.

        Args:
            statement (sqlalchemy.sql.elements.TextClause): The statement to run.
            parameters (dict | list | None): Its bound parameters.

        Returns:
            StandInResult: The raw rows for the raw-row query, otherwise an empty result.
        """
        sql = ' '.join(str(statement).split())
        if sql.startswith(f'SELECT * FROM {self.raw_table} '):
            columns = list(self.raw_rows[0])
            rows = []
            for raw_row in self.raw_rows:
                values = []
                for column in columns:
                    values.append(raw_row[column])
                rows.append(tuple(values))
            return StandInResult(columns, rows)
        self.statements.append((sql, parameters))
        return StandInResult([], [])


class StandInEngine:
    """A stand-in for an SQLAlchemy engine that always hands out the same stand-in connection.

    Attributes:
        connection (StandInConnection): The connection handed out.
    """

    def __init__(self, connection):
        """Holds the connection to hand out.

        Args:
            connection (StandInConnection): The connection handed out.

        Returns:
            None: This method returns nothing.
        """
        self.connection = connection

    def connect(self):
        """Hands out the connection for reading.

        Returns:
            StandInConnection: The connection.
        """
        return self.connection

    def begin(self):
        """Hands out the connection for one transaction.

        Returns:
            StandInConnection: The connection.
        """
        return self.connection


class MappingOneDayExample:
    """Maps four raw rows for one date and prints what would be written.

    Attributes:
        mapping_date (datetime.date): The snapshot date being mapped.
        connection (StandInConnection): The stand-in connection holding the raw rows.
        adapter (DhanRulesOnlyAdapter): The adapter being shown, using the stand-in engine.
    """

    def __init__(self):
        """Builds the adapter and swaps its engine for the stand-in.

        Returns:
            None: This method returns nothing.
        """
        self.mapping_date = datetime.date(2026, 9, 28)
        raw_rows = [
            self.raw_row('1594', 'NSE', 'E', 'EQUITY', 'ES', 'INFY', 'INFOSYS LIMITED', None, None, None),
            self.raw_row('40215', 'NSE', 'D', 'OPTIDX', 'OP', 'NIFTY', 'NIFTY-Oct2026-25000-CE', '2026-10-27', '25000.00000', 'CE'),
            self.raw_row('990001', 'NSE', 'X', 'SPREAD', 'SP', '', 'TEST SPREAD', None, None, None),
            self.raw_row('40216', 'NSE', 'D', 'OPTIDX', 'OP', 'NIFTY', 'NIFTY-Oct2026-XX-PE', '2026-10-27', 'not a number', 'PE'),
        ]
        self.connection = StandInConnection('dhan.instruments', raw_rows)
        self.adapter = DhanRulesOnlyAdapter()
        self.adapter.engine = StandInEngine(self.connection)

    def raw_row(self, security_id, exchange, segment, instrument, instrument_type, underlying_symbol, symbol_name, expiry, strike_price, option_type):
        """Builds one raw row in the shape of `dhan.instruments`.

        Args:
            security_id (str): Dhan's token for the row.
            exchange (str): The `exch_id` column.
            segment (str): Dhan's one-letter segment code.
            instrument (str): The `instrument` column.
            instrument_type (str): The `instrument_type` column.
            underlying_symbol (str): The `underlying_symbol` column.
            symbol_name (str): The `symbol_name` column.
            expiry (str | None): The `sm_expiry_date` column.
            strike_price (str | None): The `strike_price` column.
            option_type (str | None): The `option_type` column.

        Returns:
            dict: The raw row, every column as text as the raw table stores it.
        """
        return {
            'exch_id': exchange,
            'segment': segment,
            'security_id': security_id,
            'isin': None,
            'instrument': instrument,
            'underlying_security_id': None,
            'underlying_symbol': underlying_symbol,
            'symbol_name': symbol_name,
            'display_name': symbol_name,
            'instrument_type': instrument_type,
            'series': None,
            'lot_size': '1.0',
            'sm_expiry_date': expiry,
            'strike_price': strike_price,
            'option_type': option_type,
            'tick_size': '5.0',
            'download_date': self.mapping_date,
        }

    def short_row(self, row):
        """Shortens one written row to its filled-in columns, leaving out the dates the example already names.

        Args:
            row (dict): One row the adapter asked to insert.

        Returns:
            dict: The row's columns that hold a value, with the instrument id cut to its first eight characters.
        """
        shortened = {}
        for column, value in row.items():
            if value is None or isinstance(value, datetime.date):
                continue
            if column == 'instrument_id':
                value = value[:8]
            shortened[column] = value
        return shortened

    def run(self):
        """Reads the raw rows, maps them, and prints the summary and the statements sent.

        Returns:
            None: This method returns nothing.
        """
        raw = self.adapter.read_raw_rows(self.connection, self.mapping_date)
        print(f'read_raw_rows returned {len(raw)} rows with {len(raw.columns)} columns')
        print()
        summary = self.adapter.run(self.mapping_date)
        print()
        for key in summary:
            print(f'{key}: {summary[key]}')
        print()
        print('Statements sent inside the write transaction:')
        for sql, parameters in self.connection.statements:
            print(f'  {sql[:60]}...')
            if isinstance(parameters, list):
                for row in parameters:
                    print(f'    {self.short_row(row)}')
            else:
                print(f'    {parameters}')
        print()
        try:
            UnnamedAdapter()
        except NotImplementedError as error:
            print(f'NotImplementedError: {error}')


if __name__ == '__main__':
    MappingOneDayExample().run()

It prints:

read_raw_rows returned 4 rows with 17 columns

dhan: 3/4 raw row(s) classified, 1 uncategorised, 3 segment membership(s), 3 distinct instrument(s), 1 error(s).

broker: dhan
mapping_date: 2026-09-28
raw_rows: 4
matched: 3
uncategorised: 1
memberships: 3
instruments_upserted: 3
errors: [('nse_equity_index_options', "could not convert string to float: 'not a number'")]

Statements sent inside the write transaction:
  DELETE FROM unified.broker_mappings WHERE broker = :b AND ma...
    {'b': 'dhan', 'd': datetime.date(2026, 9, 28)}
  INSERT INTO unified.instruments AS master (instrument_id, ex...
    {'instrument_id': '8fdcd38e', 'exchange': 'unknown', 'segment': 'uncategorised', 'shape': 'security', 'symbol': '990001'}
    {'instrument_id': 'f310e1b0', 'exchange': 'nse', 'segment': 'nse_equities', 'shape': 'security', 'symbol': 'INFY'}
    {'instrument_id': 'fe85c704', 'exchange': 'nse', 'segment': 'nse_equity_index_options', 'shape': 'option', 'underlying_symbol': 'NIFTY', 'strike_price': 25000.0, 'option_type': 'CE'}
  INSERT INTO unified.broker_mappings (instrument_id, broker, ...
    {'instrument_id': '8fdcd38e', 'broker': 'dhan', 'broker_token': '990001', 'broker_symbol': 'TEST SPREAD', 'lot_size': 1.0, 'tick_size': 5.0, 'attributes': '{"display_name": "TEST SPREAD", "instrument_type": "SP"}'}
    {'instrument_id': 'f310e1b0', 'broker': 'dhan', 'broker_token': '1594', 'broker_symbol': 'INFOSYS LIMITED', 'lot_size': 1.0, 'tick_size': 0.05, 'attributes': '{"display_name": "INFOSYS LIMITED", "instrument_type": "ES"}'}
    {'instrument_id': 'fe85c704', 'broker': 'dhan', 'broker_token': '40215', 'broker_symbol': 'NIFTY-Oct2026-25000-CE', 'lot_size': 1.0, 'tick_size': 0.05, 'attributes': '{"display_name": "NIFTY-Oct2026-25000-CE", "instrument_type": "OP"}'}

NotImplementedError: UnnamedAdapter must set BROKER_NAME

Methods:

Name Description
run

Map Kotak's raw rows for one date, precomputing the BSE exchange traded fund allowlist first.

classify

Classify a raw row, applying the ISIN splits and the cross-broker fund reroutes on top of the rules.

classify_extra

Return the second segment a BSE row also belongs to when it is both a real security and a confirmed exchange traded fund.

to_identity

Build the unified identity fields, stripping Kotak's trading symbol suffix and applying the BSE index alias.

uncategorised_exchange

Determine the canonical exchange for an unmatched Kotak row from its exchange segment column.

segment_config

Look up one segment configuration by its segment value.

to_broker_fields

Build the per-broker mapping fields for a raw row under one segment.

read_raw_rows

Read the broker's raw rows for one date.

Source code in stock_brokers/instruments/mapping/base.py
def __init__(self):
    """
    Load and validate the broker's rules file and create the database engine.

    Raises:
        NotImplementedError: If the subclass did not set BROKER_NAME.
        ValueError: If the rules file fails validation.
        FileNotFoundError: If the broker has no rules file.
    """
    if not self.BROKER_NAME:
        raise NotImplementedError(f"{type(self).__name__} must set BROKER_NAME")
    with open(RULES_DIRECTORY / f"{self.BROKER_NAME}.yaml") as rules_file:
        self.config = yaml.safe_load(rules_file)
    self._validate_config()
    self.engine = get_postgres_engine()
    self.raw_attributes = RawAttributes()

run

run(mapping_date)

Map Kotak's raw rows for one date, precomputing the BSE exchange traded fund allowlist first.

Parameters:

Name Type Description Default
mapping_date date

The raw snapshot date to map.

required

Returns:

Type Description
dict

The run summary, as described in BrokerMappingAdapter.run.

Example usage

From example_2_mapping_one_day.py
summary = self.adapter.run(self.mapping_date)
Source code in stock_brokers/instruments/mapping/kotak.py
def run(self, mapping_date):
    """
    Map Kotak's raw rows for one date, precomputing the BSE exchange traded fund allowlist first.

    Args:
        mapping_date (datetime.date): The raw snapshot date to map.

    Returns:
        dict: The run summary, as described in BrokerMappingAdapter.run.
    """
    with self.engine.connect() as connection:
        self.bse_etf_symbols = known_bse_etf_symbols(connection, mapping_date)
    return super().run(mapping_date)

_field

_field(raw_row, specification)

Read one raw column value, adding Kotak's two broker-local field forms to the shared ones.

Parameters:

Name Type Description Default
raw_row dict

One raw row from kotak.instruments.

required
specification str | dict

A bare column name, a {column, transform} pair, a {constant} value, or a {columns, transform} pair.

required

Returns:

Type Description
Any

The resolved value.

Raises:

Type Description
ValueError

If a multi-column specification names a transform this adapter does not implement.

Source code in stock_brokers/instruments/mapping/kotak.py
def _field(self, raw_row, specification):
    """
    Read one raw column value, adding Kotak's two broker-local field forms to the shared ones.

    Args:
        raw_row (dict): One raw row from kotak.instruments.
        specification (str | dict): A bare column name, a {column, transform} pair, a {constant} value, or a {columns, transform} pair.

    Returns:
        Any: The resolved value.

    Raises:
        ValueError: If a multi-column specification names a transform this adapter does not implement.
    """
    if isinstance(specification, dict):
        if "constant" in specification:
            return specification["constant"]
        if "columns" in specification:
            transform = specification["transform"]
            if transform != "dynamic_precision_strike":
                raise ValueError(f"kotak: unknown multi-column transform {transform!r}")
            raw_strike = raw_row.get(specification["columns"][0])
            precision = raw_row.get(specification["columns"][1])
            if raw_strike is None or pd.isna(raw_strike) or precision is None or pd.isna(precision):
                return None
            return float(raw_strike) / (10 ** float(precision))
    return super()._field(raw_row, specification)

classify

classify(raw_row)

Classify a raw row, applying the ISIN splits and the cross-broker fund reroutes on top of the rules.

Parameters:

Name Type Description Default
raw_row dict

One raw row from kotak.instruments.

required

Returns:

Type Description
dict | None

The matched segment configuration, or None when no segment matches.

Example usage

From example_1_isin_splits_and_scales.py
segment_configuration = self.adapter.classify(raw_row)
Source code in stock_brokers/instruments/mapping/kotak.py
def classify(self, raw_row):
    """
    Classify a raw row, applying the ISIN splits and the cross-broker fund reroutes on top of the rules.

    Args:
        raw_row (dict): One raw row from kotak.instruments.

    Returns:
        dict | None: The matched segment configuration, or None when no segment matches.
    """
    segment_configuration = super().classify(raw_row)
    if segment_configuration is not None:
        segment = segment_configuration["segment"]
        group = raw_row.get("pgroup")
        isin = raw_row.get("pisin")
        symbol = raw_row.get("ptrdsymbol")

        if segment == "nse_equities":
            if isin_is_fund(isin):
                return self.segment_config("nse_exchange_traded_funds")
            return segment_configuration
        if segment == "bse_equities":
            if group == "B" and symbol in self.bse_etf_symbols:
                return self.segment_config("bse_exchange_traded_funds")
            if isin_is_fund(isin):
                return None
            return segment_configuration
        if segment == "bse_exchange_traded_funds":
            description = str(raw_row.get("pdesc") or "")
            if description.startswith("INAV"):
                return None
            return segment_configuration
        if segment == "bse_fixed_income":
            if group == "F" and symbol in self.bse_etf_symbols:
                return self.segment_config("bse_exchange_traded_funds")
            if not isin_valid_bond(isin):
                return None
            return segment_configuration
        return segment_configuration

    if raw_row.get("pexchseg") == "nse_cm":
        group = raw_row.get("pgroup")
        if group is None or pd.isna(group):
            return None
        if group not in NSE_NON_BOND_GROUPS and isin_valid_bond(raw_row.get("pisin")):
            return self.segment_config("nse_fixed_income")
    return None

classify_extra

classify_extra(raw_row)

Return the second segment a BSE row also belongs to when it is both a real security and a confirmed exchange traded fund.

A group B or F row with a real non-fund ISIN whose symbol the other brokers independently confirm as an exchange traded fund is genuinely both things. classify picks the fund classification as primary, being the more specific signal; this restores the equity or bond membership rather than losing it.

Parameters:

Name Type Description Default
raw_row dict

One raw row from kotak.instruments.

required

Returns:

Type Description
list[dict]

The additional segment configuration, or an empty list.

Example usage

From example_1_isin_splits_and_scales.py
self.adapter.classify_extra(raw_row)
Source code in stock_brokers/instruments/mapping/kotak.py
def classify_extra(self, raw_row):
    """
    Return the second segment a BSE row also belongs to when it is both a real security and a confirmed exchange traded fund.

    A group B or F row with a real non-fund ISIN whose symbol the other brokers independently confirm as an exchange traded fund is genuinely both things. ``classify`` picks the fund classification as primary, being the more specific signal; this restores the equity or bond membership rather than losing it.

    Args:
        raw_row (dict): One raw row from kotak.instruments.

    Returns:
        list[dict]: The additional segment configuration, or an empty list.
    """
    if raw_row.get("pexchseg") != "bse_cm":
        return []
    if raw_row.get("ptrdsymbol") not in self.bse_etf_symbols:
        return []
    if not isin_valid_bond(raw_row.get("pisin")):
        return []
    group = raw_row.get("pgroup")
    if group == "B":
        return [
            self.segment_config("bse_equities"),
        ]
    if group == "F":
        return [
            self.segment_config("bse_fixed_income"),
        ]
    return []

to_identity

to_identity(raw_row, segment_configuration)

Build the unified identity fields, stripping Kotak's trading symbol suffix and applying the BSE index alias.

Kotak appends the group to its NSE cash trading symbols, so "NBIFIN-EQ" has to lose the "-EQ" before it can converge with the other brokers' plain symbol.

Parameters:

Name Type Description Default
raw_row dict

One raw row from kotak.instruments.

required
segment_configuration dict

The segment configuration whose identity mapping applies.

required

Returns:

Type Description
dict

Identity fields, as described in BrokerMappingAdapter.to_identity.

Raises:

Type Description
ValueError

If an expiry value is numeric with no explicit transform.

Example usage

From example_1_isin_splits_and_scales.py
identity = self.adapter.to_identity(raw_row, segment_configuration)
Source code in stock_brokers/instruments/mapping/kotak.py
def to_identity(self, raw_row, segment_configuration):
    """
    Build the unified identity fields, stripping Kotak's trading symbol suffix and applying the BSE index alias.

    Kotak appends the group to its NSE cash trading symbols, so "NBIFIN-EQ" has to lose the "-EQ" before it can converge with the other brokers' plain symbol.

    Args:
        raw_row (dict): One raw row from kotak.instruments.
        segment_configuration (dict): The segment configuration whose identity mapping applies.

    Returns:
        dict: Identity fields, as described in BrokerMappingAdapter.to_identity.

    Raises:
        ValueError: If an expiry value is numeric with no explicit transform.
    """
    identity = super().to_identity(raw_row, segment_configuration)
    segment = segment_configuration["segment"]
    if segment in NSE_CASH_SUFFIX_SEGMENTS:
        symbol = raw_row.get("ptrdsymbol")
        group = raw_row.get("pgroup")
        if symbol and group and str(symbol).endswith(f"-{group}"):
            identity["symbol"] = str(symbol)[: -(len(str(group)) + 1)]
    elif segment == "bse_equity_indices":
        identity["symbol"] = BSE_INDEX_ALIASES.get(identity["symbol"], identity["symbol"])
    return identity

uncategorised_exchange

uncategorised_exchange(raw_row)

Determine the canonical exchange for an unmatched Kotak row from its exchange segment column.

Parameters:

Name Type Description Default
raw_row dict

One raw row from kotak.instruments.

required

Returns:

Type Description
str | None

"nse", "bse", or "mcx", or None for any other value.

Example usage

From example_1_isin_splits_and_scales.py
exchange = self.adapter.uncategorised_exchange(raw_row)
Source code in stock_brokers/instruments/mapping/kotak.py
def uncategorised_exchange(self, raw_row):
    """
    Determine the canonical exchange for an unmatched Kotak row from its exchange segment column.

    Args:
        raw_row (dict): One raw row from kotak.instruments.

    Returns:
        str | None: "nse", "bse", or "mcx", or None for any other value.
    """
    exchange_segment = raw_row.get("pexchseg")
    if exchange_segment in ("nse_cm", "nse_fo", "nse_com", "cde_fo"):
        return "nse"
    if exchange_segment in ("bse_cm", "bse_fo"):
        return "bse"
    if exchange_segment == "mcx_fo":
        return "mcx"
    return None

_validate_config

_validate_config()

Check the loaded rules file against the canonical vocabulary.

Every configured segment must be a real canonical segment for its exchange with the matching shape, and the segments must appear in the canonical asset-class order. The file must end with the unprefixed uncategorised entry on exchange unknown, which is the guaranteed fallback for rows whose exchange cannot be determined; unknown is allowed for that one entry only, since it is the value stored in the exchange column of the mapped table for those rows.

Raises:

Type Description
ValueError

On any invalid exchange, segment, shape, ordering, or missing or misplaced uncategorised entry.

Source code in stock_brokers/instruments/mapping/base.py
def _validate_config(self):
    """
    Check the loaded rules file against the canonical vocabulary.

    Every configured segment must be a real canonical segment for its exchange with the matching shape, and the segments must appear in the canonical asset-class order. The file must end with the unprefixed ``uncategorised`` entry on exchange ``unknown``, which is the guaranteed fallback for rows whose exchange cannot be determined; ``unknown`` is allowed for that one entry only, since it is the value stored in the exchange column of the mapped table for those rows.

    Raises:
        ValueError: On any invalid exchange, segment, shape, ordering, or missing or misplaced uncategorised entry.
    """
    previous_rank = None
    has_plain_uncategorised = False
    for segment_configuration in self.config["segments"]:
        exchange = segment_configuration["exchange"]
        segment = segment_configuration["segment"]
        shape = segment_configuration["shape"]
        is_plain_uncategorised = segment == "uncategorised" and exchange == "unknown"
        if is_plain_uncategorised:
            has_plain_uncategorised = True
            previous_rank = (1000000000, 1000000000)
            continue
        if exchange not in CANONICAL_EXCHANGES:
            raise ValueError(
                f"{self.BROKER_NAME}: {exchange!r} is not a canonical exchange, "
                f"expected one of {CANONICAL_EXCHANGES} or 'unknown' on the plain "
                f"'uncategorised' entry"
            )
        bare_segment = segment
        if segment.startswith(f"{exchange}_"):
            bare_segment = segment[len(exchange) + 1:]
        try:
            declared_shape = segment_shape(bare_segment)
        except ValueError:
            raise ValueError(
                f"{self.BROKER_NAME}: {segment!r} is not a canonical segment for exchange "
                f"{exchange!r}; use the canonical segment value instead"
            )
        if declared_shape != shape:
            raise ValueError(
                f"{self.BROKER_NAME}: segment {segment!r} has shape {declared_shape!r} "
                f"in the canonical vocabulary, not {shape!r} as configured here"
            )
        rank = segment_rank(exchange, bare_segment)
        if previous_rank is not None and rank < previous_rank:
            raise ValueError(
                f"{self.BROKER_NAME}: segment {segment!r} appears out of canonical order; "
                f"segments must be listed fixed income, equities, currencies, commodities, "
                f"then the catch-alls, then the uncategorised buckets, and within a class "
                f"simple instruments, futures, options, indices, index futures, index options"
            )
        previous_rank = rank
    if not has_plain_uncategorised:
        raise ValueError(
            f"{self.BROKER_NAME}: the rules file must end with the unprefixed "
            f"'uncategorised' entry on exchange 'unknown'"
        )

segment_config

segment_config(segment)

Look up one segment configuration by its segment value.

Parameters:

Name Type Description Default
segment str

The exchange-prefixed segment value, for example "nse_equities".

required

Returns:

Type Description
dict | None

The matching segment configuration, or None when the rules file does not configure that segment.

Example usage

From example_1_classifying_rows_by_rules.py
equities = self.adapter.segment_config('nse_equities')
From example_1_classifying_rows_by_rules.py
segment_configuration = self.adapter.segment_config('uncategorised')
From example_1_classifying_rows_by_rules.py
print(f'Unconfigured segment: {self.adapter.segment_config("nse_bonds")}')
Source code in stock_brokers/instruments/mapping/base.py
def segment_config(self, segment):
    """
    Look up one segment configuration by its segment value.

    Args:
        segment (str): The exchange-prefixed segment value, for example "nse_equities".

    Returns:
        dict | None: The matching segment configuration, or None when the rules file does not configure that segment.
    """
    for segment_configuration in self.config["segments"]:
        if segment_configuration["segment"] == segment:
            return segment_configuration
    return None

_row_matches

_row_matches(raw_row, match)

Check one equality rule against a raw row.

Parameters:

Name Type Description Default
raw_row dict

One raw row from the broker's instrument table.

required
match dict

Mapping of raw column name to expected value, or to a list of acceptable values.

required

Returns:

Type Description
bool

True when every column in the rule matches.

Source code in stock_brokers/instruments/mapping/base.py
def _row_matches(self, raw_row, match):
    """
    Check one equality rule against a raw row.

    Args:
        raw_row (dict): One raw row from the broker's instrument table.
        match (dict): Mapping of raw column name to expected value, or to a list of acceptable values.

    Returns:
        bool: True when every column in the rule matches.
    """
    for column_name, expected in match.items():
        actual = raw_row.get(column_name)
        if isinstance(expected, list):
            if actual not in expected:
                return False
        elif actual != expected:
            return False
    return True

to_broker_fields

to_broker_fields(raw_row, segment_configuration)

Build the per-broker mapping fields for a raw row under one segment.

A tick size of zero or below is stored as None, because no instrument moves in steps of nothing, and brokers send 0 or -1 where they have no tick for a row.

Parameters:

Name Type Description Default
raw_row dict

One raw row from the broker's instrument table.

required
segment_configuration dict

The segment configuration whose broker field mapping applies.

required

Returns:

Type Description
dict

Keys "broker_token" (str), "broker_symbol", "order_symbol", "lot_size" (float | None), and "tick_size" (float | None).

Example usage

From example_1_classifying_rows_by_rules.py
broker_fields = self.adapter.to_broker_fields(raw_row, segment_configuration)
Source code in stock_brokers/instruments/mapping/base.py
def to_broker_fields(self, raw_row, segment_configuration):
    """
    Build the per-broker mapping fields for a raw row under one segment.

    A tick size of zero or below is stored as None, because no instrument moves in steps of nothing, and brokers send 0 or -1 where they have no tick for a row.

    Args:
        raw_row (dict): One raw row from the broker's instrument table.
        segment_configuration (dict): The segment configuration whose broker field mapping applies.

    Returns:
        dict: Keys "broker_token" (str), "broker_symbol", "order_symbol", "lot_size" (float | None), and "tick_size" (float | None).
    """
    broker_field_specifications = segment_configuration["broker_fields"]
    lot_size = self._field(raw_row, broker_field_specifications["lot_size"])
    tick_size = self._field(raw_row, broker_field_specifications["tick_size"])
    if tick_size is None or pd.isna(tick_size) or float(tick_size) <= 0:
        tick_size = None
    else:
        tick_size = float(tick_size)
    order_symbol_specification = broker_field_specifications.get("order_symbol")
    if order_symbol_specification is None:
        order_symbol = None
    else:
        order_symbol = self._field(raw_row, order_symbol_specification)
    if order_symbol is not None and pd.isna(order_symbol):
        order_symbol = None
    return {
        "broker_token": str(self._field(raw_row, broker_field_specifications["token"])),
        "broker_symbol": self._field(raw_row, broker_field_specifications["broker_symbol"]),
        "order_symbol": None if order_symbol is None else str(order_symbol).strip(),
        "lot_size": None if lot_size is None or pd.isna(lot_size) else float(lot_size),
        "tick_size": tick_size,
    }

_uncategorised_config

_uncategorised_config(raw_row)

Pick the uncategorised segment configuration a row falls back into.

The per-exchange bucket is used when uncategorised_exchange resolves an exchange and the rules file configures that bucket; otherwise the unprefixed uncategorised entry is used.

Parameters:

Name Type Description Default
raw_row dict

One raw row from the broker's instrument table.

required

Returns:

Type Description
dict

The uncategorised segment configuration.

Raises:

Type Description
ValueError

If no uncategorised configuration exists, which validation should have made impossible.

Source code in stock_brokers/instruments/mapping/base.py
def _uncategorised_config(self, raw_row):
    """
    Pick the uncategorised segment configuration a row falls back into.

    The per-exchange bucket is used when ``uncategorised_exchange`` resolves an exchange and the rules file configures that bucket; otherwise the unprefixed ``uncategorised`` entry is used.

    Args:
        raw_row (dict): One raw row from the broker's instrument table.

    Returns:
        dict: The uncategorised segment configuration.

    Raises:
        ValueError: If no uncategorised configuration exists, which validation should have made impossible.
    """
    exchange = self.uncategorised_exchange(raw_row)
    if exchange is not None:
        preferred = self.segment_config(segment_value(exchange, "uncategorised"))
        if preferred is not None:
            return preferred
    fallback = self.segment_config("uncategorised")
    if fallback is None:
        raise ValueError(
            f"{self.BROKER_NAME}: no uncategorised segment configuration found, "
            f"which validation should have made impossible"
        )
    return fallback

read_raw_rows

read_raw_rows(connection, mapping_date)

Read the broker's raw rows for one date.

Adapters override this where the fetch itself is part of the mapping: to impose a row order the classification depends on, or to bring in rows the plain query would miss.

Parameters:

Name Type Description Default
connection Connection

An open SQLAlchemy connection.

required
mapping_date date

The raw snapshot date to read.

required

Returns:

Type Description
DataFrame

The raw rows for that date.

Example usage

From example_2_mapping_one_day.py
raw = self.adapter.read_raw_rows(self.connection, self.mapping_date)
Source code in stock_brokers/instruments/mapping/base.py
def read_raw_rows(self, connection, mapping_date):
    """
    Read the broker's raw rows for one date.

    Adapters override this where the fetch itself is part of the mapping: to impose a row order the classification depends on, or to bring in rows the plain query would miss.

    Args:
        connection (sqlalchemy.engine.Connection): An open SQLAlchemy connection.
        mapping_date (datetime.date): The raw snapshot date to read.

    Returns:
        pandas.DataFrame: The raw rows for that date.
    """
    raw_table = self.config["raw_table"]
    return pd.read_sql(
        text(f"SELECT * FROM {raw_table} WHERE download_date = :d"),
        connection,
        params={
            "d": mapping_date,
        },
    )

_write_results

_write_results(instrument_rows, broker_rows, mapping_date)

Write one run's rows into the mapped tables inside a single transaction.

Both row lists are sorted by instrument id before the insert so concurrent writers acquire locks in the same order, which is the standard fix for the multi-writer deadlock this design was observed hitting when adapters ran in parallel.

The seen dates widen rather than overwrite, so they do not depend on the order dates happen to be mapped in. Assigning the run's date to the last seen date directly looks equivalent while a backfill walks forward, and is wrong the moment any older date is mapped afterwards: it drags the last seen date backwards, and leaves the first seen date frozen at whichever date was written first rather than the earliest the instrument was actually seen.

Parameters:

Name Type Description Default
instrument_rows dict

Mapping of instrument id to the unified.instruments row.

required
broker_rows dict

Mapping of instrument id to the unified.broker_mappings row.

required
mapping_date date

The mapping date the run covers.

required
Source code in stock_brokers/instruments/mapping/base.py
def _write_results(self, instrument_rows, broker_rows, mapping_date):
    """
    Write one run's rows into the mapped tables inside a single transaction.

    Both row lists are sorted by instrument id before the insert so concurrent writers acquire locks in the same order, which is the standard fix for the multi-writer deadlock this design was observed hitting when adapters ran in parallel.

    The seen dates widen rather than overwrite, so they do not depend on the order dates happen to be mapped in. Assigning the run's date to the last seen date directly looks equivalent while a backfill walks forward, and is wrong the moment any older date is mapped afterwards: it drags the last seen date backwards, and leaves the first seen date frozen at whichever date was written first rather than the earliest the instrument was actually seen.

    Args:
        instrument_rows (dict): Mapping of instrument id to the unified.instruments row.
        broker_rows (dict): Mapping of instrument id to the unified.broker_mappings row.
        mapping_date (datetime.date): The mapping date the run covers.
    """
    sorted_instruments = sorted(instrument_rows.values(), key=lambda row: row["instrument_id"])
    sorted_brokers = sorted(broker_rows.values(), key=lambda row: row["instrument_id"])

    with self.engine.begin() as connection:
        connection.execute(
            text(
                f"DELETE FROM {tables.BROKER_MAPPINGS} "
                "WHERE broker = :b AND mapping_date = :d"
            ),
            {
                "b": self.BROKER_NAME,
                "d": mapping_date,
            },
        )
        if sorted_instruments:
            connection.execute(
                text(
                    f"""
                    INSERT INTO {tables.MASTER} AS master
                        (instrument_id, exchange, segment, shape, symbol, underlying_symbol,
                         expiry_date, strike_price, option_type, first_seen_date, last_seen_date)
                    VALUES
                        (:instrument_id, :exchange, :segment, :shape, :symbol, :underlying_symbol,
                         :expiry_date, :strike_price, :option_type, :first_seen_date, :last_seen_date)
                    ON CONFLICT (instrument_id) DO UPDATE SET
                        first_seen_date = LEAST(master.first_seen_date, EXCLUDED.first_seen_date),
                        last_seen_date = GREATEST(master.last_seen_date, EXCLUDED.last_seen_date)
                    """
                ),
                sorted_instruments,
            )
        if sorted_brokers:
            connection.execute(
                text(
                    f"""
                    INSERT INTO {tables.BROKER_MAPPINGS}
                        (instrument_id, broker, broker_token, broker_symbol, order_symbol, lot_size, tick_size, mapping_date, attributes)
                    VALUES
                        (:instrument_id, :broker, :broker_token, :broker_symbol, :order_symbol, :lot_size, :tick_size, :mapping_date, CAST(:attributes AS jsonb))
                    ON CONFLICT (instrument_id, broker, mapping_date) DO UPDATE SET
                        broker_token = EXCLUDED.broker_token, broker_symbol = EXCLUDED.broker_symbol,
                        order_symbol = EXCLUDED.order_symbol,
                        lot_size = EXCLUDED.lot_size, tick_size = EXCLUDED.tick_size,
                        attributes = EXCLUDED.attributes
                    """
                ),
                sorted_brokers,
            )

isin_is_fund

isin_is_fund(isin)

Check whether an ISIN belongs to the fund family, which India marks with an INF prefix.

Parameters:

Name Type Description Default
isin str | None

The raw ISIN value from a Kotak row.

required

Returns:

Type Description
bool

True when the ISIN is present and starts with "INF".

Source code in stock_brokers/instruments/mapping/kotak.py
def isin_is_fund(isin):
    """
    Check whether an ISIN belongs to the fund family, which India marks with an INF prefix.

    Args:
        isin (str | None): The raw ISIN value from a Kotak row.

    Returns:
        bool: True when the ISIN is present and starts with "INF".
    """
    if isin is None or pd.isna(isin):
        return False
    return str(isin).startswith("INF")

isin_valid_bond

isin_valid_bond(isin)

Check whether an ISIN can identify a bond, meaning it is present and is not a fund ISIN.

Parameters:

Name Type Description Default
isin str | None

The raw ISIN value from a Kotak row.

required

Returns:

Type Description
bool

True when the ISIN is usable as a fixed income identity.

Source code in stock_brokers/instruments/mapping/kotak.py
def isin_valid_bond(isin):
    """
    Check whether an ISIN can identify a bond, meaning it is present and is not a fund ISIN.

    Args:
        isin (str | None): The raw ISIN value from a Kotak row.

    Returns:
        bool: True when the ISIN is usable as a fixed income identity.
    """
    if isin is None or pd.isna(isin):
        return False
    return not str(isin).startswith("INF")