cointoss.instrument¶
instrument
¶
Instrument identity: minting Instrument Ids and establishing identity by External Reference.
Implements ADR-0004. Pure: no network, no clock, no database. Observations carry their own observation date and their own FIGI Resolution outcome, so every rule here is testable without a resolver. The module cannot compel a FIGI attempt; ADR-0004's "resolution attempt is mandatory at creation" is an ingest-orchestration invariant enforced where Observations are constructed.
Chain vocabulary (permanent, baked into Instrument Ids): the scope of an on-chain token is the
short symbolic form of its chain -- eth, not ethereum and not the numeric chain id 1.
Other chains follow the same convention (sol, bsc, avax); native is reserved for a
chain's own coin, so BTC is crypto.native.btc. The vocabulary is Chain below and is
deliberately small: a new chain is a code change, because an Instrument Id minted under a name
can never be reminted under another.
Instrument Id grammar: {type}.{scope}.{symbol}[_{qualifier}]. Symbols are normalised to
alphanumerics separated by -, so the first _ in the third part always starts the Qualifier.
Source attribution (the ADR-0004 amendment): a symbol is one source's lease on a name, so
every Ticker History record names the source that reported it and every symbol lookup takes
one. An Instrument states the Identity Source its displayed name and symbol come from and the
ordered Price Sources its Bars should come from, both defaulted from its type when it is
minted. A stable provider slug such as a CoinGecko id is an External Reference instead --
it is identity and never changes, whereas a ticker is a lease.
Note for the next reader: stock.us.fb denotes Meta permanently, because the id is minted from
the symbol first seen and never changed. This reads backwards and is the deliberate price of
immutable readable ids -- see ADR-0004.
InstrumentError
¶
UnknownScope
¶
Bases: InstrumentError
Scope is not a known chain or a plausible ISO country.
AmbiguousSymbol
¶
Bases: InstrumentError
More than one Instrument traded under a symbol on the given date.
SupersessionCycle
¶
Bases: InstrumentError
A Supersession chain does not terminate. Always a defect.
Chain
¶
Bases: StrEnum
Controlled vocabulary for crypto Scope. Short symbolic chain names, plus native.
Source code in src/cointoss/instrument.py
Source
¶
Bases: StrEnum
Controlled vocabulary for the sources cointoss ingests from.
Deliberately small and closed, like Chain: a source is named in stored Ticker History,
in an Instrument's Identity Source and Price Sources, and later on every Bar, so adding
one is a code change rather than a free-text value drifting into the data.
Source code in src/cointoss/instrument.py
FigiResolution
¶
Bases: StrEnum
Outcome of attempting to anchor an Instrument to a FIGI.
NOT_FOUND is a coverage gap; NOT_ATTEMPTED is a missing ingestion step. Both are
retryable and both appear in the unresolved work queue.
Source code in src/cointoss/instrument.py
ReferenceKind
¶
Bases: StrEnum
Kinds of External Reference. SHARE_CLASS_FIGI is stored but never used for matching.
Source code in src/cointoss/instrument.py
Outcome
¶
ScopeKind
¶
Scope
¶
Bases: str
A validated Scope: the authority under which a symbol is unique.
Construction is validation, so a Scope cannot hold an unchecked value and there is no
way to reach one that was never checked. It is a str, so its stored and printed form is
the scope itself.
>>> Scope(InstrumentType.STOCK, "US")
Scope('us')
>>> Scope(InstrumentType.CRYPTO, "eth").kind
<ScopeKind.CHAIN: 'chain'>
>>> Scope(InstrumentType.CRYPTO, "ethereum")
Traceback (most recent call last):
...
cointoss.instrument.UnknownScope: 'ethereum' is not in the chain vocabulary...
Source code in src/cointoss/instrument.py
__reduce__()
¶
Rebuild from the validated value and its kind.
The default str reduction would call __new__ with one argument, so a Scope would
be uncopyable and unpicklable. Reconstruction skips revalidation because a Scope that
exists was validated when it was made.
Source code in src/cointoss/instrument.py
InstrumentId
¶
Bases: str
An Instrument Id: {type}.{scope}.{symbol}[_{qualifier}], minted once and immutable.
A str subclass, so the readable slug ADR-0004 chose is exactly what is stored, printed,
and used as a key -- but a distinct type, so a symbol or a name cannot be passed where an
id belongs. Construction parses and validates; there is no partial value.
>>> InstrumentId("stock.us.fb").symbol
'FB'
>>> InstrumentId("stock.us.fb_proshares").qualifier
'proshares'
>>> InstrumentId.mint(InstrumentType.CRYPTO, Scope(InstrumentType.CRYPTO, "eth"), "USDC")
InstrumentId('crypto.eth.usdc')
>>> InstrumentId("AAPL")
Traceback (most recent call last):
...
ValueError: 'AAPL' is not an Instrument Id...
Source code in src/cointoss/instrument.py
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |
mint(instrument_type, scope, symbol, qualifier=None)
classmethod
¶
Compose an id from its parts. The only way to build one that has never existed.
Source code in src/cointoss/instrument.py
__get_pydantic_core_schema__(source, handler)
classmethod
¶
Let Pydantic carry an InstrumentId without it degrading to str.
Without this a model field annotated InstrumentId fails at class construction,
because the custom one-argument __new__ is not a schema Pydantic can infer. Values
are validated by construction on the way in and serialised as the slug on the way out.
Source code in src/cointoss/instrument.py
ExternalReference
dataclass
¶
An identifier issued by an outside authority.
qualifier namespaces the value: the provider for a provider id, the chain for a contract
address, empty for a FIGI, which is globally unique.
Source code in src/cointoss/instrument.py
is_anchor_figi
property
¶
Whether this reference is the FIGI an Instrument of its type anchors on.
contract(chain, address)
classmethod
¶
Chain and contract address. Addresses are compared case-insensitively.
Source code in src/cointoss/instrument.py
group()
¶
Priority tier and comparison key, or None when the reference never matches.
TickerRecord
dataclass
¶
One time-bounded stretch of Ticker History, as reported by one source.
valid_to None means current. Records are not vendor-neutral: Yahoo's BRK-B and another
source's BRK.B are two current records for one Instrument, which is why source is part
of the record and of every lookup against it.
Source code in src/cointoss/instrument.py
Observation
dataclass
¶
A normalised sighting of an asset from some source.
source is required: a sighting with no stated source cannot be recorded as Ticker
History, since the symbol it carries is only that source's name for the asset.
figi_resolution is the outcome the caller obtained, not something this module can compel.
An anchor FIGI reference and a RESOLVED state must agree.
Source code in src/cointoss/instrument.py
Instrument
dataclass
¶
The canonical, stable identity for a tradable asset.
symbol and name are the denormalised display values read from identity_source; they
are that source's account of the asset, not facts. price_sources is an ordered
preference, first holder of a Bar for a date wins.
Source code in src/cointoss/instrument.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | |
ticker_history_from(source)
¶
This Instrument's Ticker History as reported by one source, oldest first.
provider_ids(source)
¶
This Instrument's provider ids from source, in the order they were recorded.
Source code in src/cointoss/instrument.py
provider_id(source)
¶
The first of this Instrument's provider ids from source, if it has one.
absorb(obs)
¶
Fold an Observation this Instrument has been identified with into itself.
Source code in src/cointoss/instrument.py
IdentityResult
dataclass
¶
What an Observation meant. instrument is None exactly when the outcome is FLAGGED.
Source code in src/cointoss/instrument.py
InstrumentRegistry
¶
The identity seam over an in-memory collection of Instruments.
Write side: observe, and anchor for a retry. Read side: resolve_symbol, survivor,
unresolved. Storage is out of scope; the collection is passed in and handed back, and no
ordering beyond mint order -- which the registry tracks itself -- is assumed.
Source code in src/cointoss/instrument.py
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 | |
instruments()
¶
get(instrument_id)
¶
Look up by Instrument Id exactly as stored, without chasing Supersession.
A plain str is parsed first, so a value that is not an Instrument Id at all raises
ValueError or UnknownScope, while an id that is well formed but unknown raises
KeyError. Malformed input and a genuine miss are different failures.
Source code in src/cointoss/instrument.py
survivor(instrument_id)
¶
Chase a Supersession chain to its fixed point.
Source code in src/cointoss/instrument.py
unresolved()
¶
Work queue: surviving Instruments whose FIGI Resolution is not resolved.
resolve_symbol(source, instrument_type, symbol, scope, as_of)
¶
Resolve a symbol supplied by a person or a document, as reported by one source.
The source is required and is not a hint: a symbol recorded under one source does not resolve under another, because vendors name the same asset differently and neither name is canonical. A broker CSV must be read against the source that wrote it.
The date is required too: defaulting it would silently mis-resolve historical statements. Overlapping Ticker History across Instruments is expected -- that is the reused-ticker case -- and is disambiguated by the date, so an overlap within one source on one date is an error.
Source code in src/cointoss/instrument.py
observe(obs)
¶
Turn a source Observation into the Instrument it belongs to.
Identity is established by External Reference in a fixed order: FIGI, then contract address, then a provider's own stable id. Symbol and scope match only between two Instruments that are both still unresolved, and never merge two Instruments.
Source code in src/cointoss/instrument.py
anchor(instrument_id, obs)
¶
Attach a FIGI answer to a named Instrument: the retry of ADR-0004's unresolved flow.
observe cannot do this, because its symbol tier only joins two unresolved parties and a
FIGI answer is resolved, so it would mint a second Instrument beside the one waiting for
that answer. Here the caller names the target instead, and the evidence is checked
against it: the target must be surviving, of the Observation's type and scope, not
already anchored on another FIGI, and not disagreeing on any other External Reference;
and no other Instrument may already hold one of the Observation's References, since
that is a merge question for review rather than a retry. Contrary evidence is flagged and
nothing is changed.
On success the Observation is absorbed like any match: References are added, the FIGI
Resolution becomes RESOLVED, and its symbol is recorded as Ticker History under the
usual forward-only rule, so a retry under a later ticker records the rename.
Source code in src/cointoss/instrument.py
default_identity_source(instrument_type)
¶
The Identity Source an Instrument of this type is minted with.
Source code in src/cointoss/instrument.py
default_price_sources(instrument_type)
¶
The ordered Price Sources an Instrument of this type is minted with.
>>> default_price_sources(InstrumentType.CRYPTO)
(<Source.YAHOO: 'yahoo'>, <Source.COINGECKO: 'coingecko'>)
Source code in src/cointoss/instrument.py
normalize_symbol(symbol)
¶
issuer_qualifier(issuer_name)
¶
Slugify an issuer name into a Qualifier, dropping legal-form words.
>>> issuer_qualifier("ProShares Trust")
'proshares'
>>> issuer_qualifier("Meta Platforms, Inc.")
'meta-platforms'
>>> issuer_qualifier("Trust Inc") is None
True
Source code in src/cointoss/instrument.py
test_instrument_id_round_trips_through_its_string_form()
¶
The readable slug is the stored form; parsing it back must lose nothing.
Source code in src/cointoss/instrument.py
test_malformed_instrument_ids_are_rejected_whole()
¶
A partial parse would be worse than no parse: every part is validated or nothing is.
Source code in src/cointoss/instrument.py
test_a_qualifier_is_separated_from_the_symbol()
¶
A normalised symbol never contains "_", so the first one always starts the Qualifier.
Source code in src/cointoss/instrument.py
test_ids_and_scopes_survive_copying()
¶
A str subclass carrying attributes is uncopyable unless it says how to rebuild, and both types end up inside dataclasses that callers will copy and stores will serialize.
Source code in src/cointoss/instrument.py
test_source_defaults_follow_the_instrument_type()
¶
Yahoo names and prices equities; CoinGecko names coins and backs Yahoo up on prices.
Source code in src/cointoss/instrument.py
test_price_sources_must_be_a_usable_preference()
¶
An empty or repeating preference names nothing, so it is refused at construction.