diff --git a/404.html b/404.html index 23cdd22..9ca1e69 100644 --- a/404.html +++ b/404.html @@ -24,10 +24,6 @@ - - - - @@ -59,6 +55,8 @@ + + @@ -66,6 +64,8 @@ + + @@ -106,6 +106,40 @@ +
src/tclf/classical_classifier.py
39 - 40 + 40 41 42 43 @@ -1203,25 +1236,7 @@ API reference 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598class ClassicalClassifier(ClassifierMixin, BaseEstimator): +580class ClassicalClassifier(ClassifierMixin, BaseEstimator): """ClassicalClassifier implements several trade classification rules. Including: @@ -1240,6 +1255,8 @@ API reference base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` """ + X_ = pd.DataFrame + def __init__( self, layers: list[ @@ -1580,59 +1597,32 @@ API reference """ return np.full(shape=(self.X_.shape[0],), fill_value=np.nan) - def _validate_columns(self, found_cols: list[str]) -> None: + def _validate_columns(self, missing_columns: list) -> None: """Validate if all required columns are present. Args: - found_cols (list[str]): columns present in dataframe. - """ - - def lookup_columns(func_str: str, sub: str) -> list[str]: - LR_LIKE = [ - "trade_price", - f"price_{sub}_lag", - f"ask_{sub}", - f"bid_{sub}", - ] - REV_LR_LIKE = [ - "trade_price", - f"price_{sub}_lead", - f"ask_{sub}", - f"bid_{sub}", - ] + missing_columns (list): list of missing columns. - LUT_REQUIRED_COLUMNS: dict[str, list[str]] = { - "nan": [], - "clnv": LR_LIKE, - "depth": [ - "trade_price", - f"ask_{sub}", - f"bid_{sub}", - f"ask_size_{sub}", - f"bid_size_{sub}", - ], - "emo": LR_LIKE, - "lr": LR_LIKE, - "quote": ["trade_price", f"ask_{sub}", f"bid_{sub}"], - "rev_clnv": REV_LR_LIKE, - "rev_emo": REV_LR_LIKE, - "rev_lr": REV_LR_LIKE, - "rev_tick": ["trade_price", f"price_{sub}_lead"], - "tick": ["trade_price", f"price_{sub}_lag"], - "trade_size": ["trade_size", f"ask_size_{sub}", f"bid_size_{sub}"], - } - return LUT_REQUIRED_COLUMNS[func_str] - - required_cols_set = set() - for func_str, sub in self._layers: - func_col = lookup_columns(func_str, sub) - required_cols_set.update(func_col) - - missing_cols = sorted(required_cols_set - set(found_cols)) - if missing_cols: + Raises: + ValueError: columns missing in dataframe. + """ + columns = self.columns_ + missing_columns if self.columns_ else missing_columns + self.X_ = pd.DataFrame(np.zeros(shape=(1, len(columns))), columns=columns) + try: + self._predict() + except KeyError as e: + result = re.search(r"'([^']+)'", str(e)) + if result: + add_missing = result.group(1) + if add_missing: + missing_columns.append(add_missing) + return self._validate_columns(missing_columns) + if missing_columns: raise ValueError( - f"Expected to find columns: {missing_cols}. Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/" + f"Expected to find columns: {sorted(missing_columns)}. Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/" ) + del self.X_ + return None def fit( self, @@ -1690,7 +1680,7 @@ API reference self.classes_ = np.array([-1, 1]) # if no features are provided or inferred, use default - if not self.columns_: + if self.columns_ is None: self.columns_ = [str(i) for i in range(X.shape[1])] if len(self.columns_) > 0 and X.shape[1] != len(self.columns_): @@ -1706,9 +1696,7 @@ API reference f"expected one of {ALLOWED_FUNC_STR}." ) - columns = self.columns_ - self._validate_columns(columns) - + self._validate_columns([]) return self def predict(self, X: MatrixLike) -> npt.NDArray: @@ -1731,15 +1719,7 @@ API reference rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -1752,6 +1732,22 @@ API reference del self.X_ return pred + def _predict(self) -> npt.NDArray: + """Predict with rule stack. + + Returns: + npt.NDArray: prediction + """ + pred = np.full(shape=(self.X_.shape[0],), fill_value=np.nan) + for func_str, subset in self._layers: + func = self.func_mapping_[func_str] + pred = np.where( + np.isnan(pred), + func(subset=subset), + pred, + ) + return pred + def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. @@ -1906,10 +1902,7 @@ Source code in src/tclf/classical_classifier.py - 58 - 59 - 60 - 61 + 61 62 63 64 @@ -1948,7 +1941,10 @@ 97 98 99 -100def __init__( +100 +101 +102 +103def __init__( self, layers: list[ tuple[ @@ -2141,7 +2137,31 @@ Source code in src/tclf/classical_classifier.py - 452 + 428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 453 454 455 @@ -2190,33 +2210,7 @@ 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 -527def fit( +501def fit( self, X: MatrixLike, y: ArrayLike | None = None, @@ -2272,7 +2266,7 @@ self.classes_ = np.array([-1, 1]) # if no features are provided or inferred, use default - if not self.columns_: + if self.columns_ is None: self.columns_ = [str(i) for i in range(X.shape[1])] if len(self.columns_) > 0 and X.shape[1] != len(self.columns_): @@ -2288,9 +2282,7 @@ f"expected one of {ALLOWED_FUNC_STR}." ) - columns = self.columns_ - self._validate_columns(columns) - + self._validate_columns([]) return self @@ -2370,46 +2362,38 @@ Source code in src/tclf/classical_classifier.py - 529 + 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 -555 -556 -557 -558 -559 -560 -561 -562 -563 -564 -565 -566 -567 -568def predict(self, X: MatrixLike) -> npt.NDArray: +534def predict(self, X: MatrixLike) -> npt.NDArray: """Perform classification on test vectors `X`. Args: @@ -2429,15 +2413,7 @@ rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -2529,7 +2505,25 @@ Source code in src/tclf/classical_classifier.py - 570 + 552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -736,11 +770,11 @@ A Primer on Trade Classification As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation¶ We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security. -For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 +For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 Basic Rules¶ This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm. Quote Rule¶ -The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. +The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by: \[ \operatorname{quote}\colon \mathcal{A} \to \mathcal{Y},\quad @@ -757,7 +791,7 @@ Quote Ruleclf.fit(X) Tick Test¶ -A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. +A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. The tick test is defined as: \[ \operatorname{tick}\colon \mathbb{N}^2 \to \mathcal{Y},\quad @@ -884,7 +918,7 @@ Chakrabarty-Li-Nguyen-Van-Ness Me Stacked Rule¶ The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. -The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. +The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
40 41 42 43 @@ -1203,25 +1236,7 @@ API reference 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598
class ClassicalClassifier(ClassifierMixin, BaseEstimator): +580
class ClassicalClassifier(ClassifierMixin, BaseEstimator): """ClassicalClassifier implements several trade classification rules. Including: @@ -1240,6 +1255,8 @@ API reference base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` """ + X_ = pd.DataFrame + def __init__( self, layers: list[ @@ -1580,59 +1597,32 @@ API reference """ return np.full(shape=(self.X_.shape[0],), fill_value=np.nan) - def _validate_columns(self, found_cols: list[str]) -> None: + def _validate_columns(self, missing_columns: list) -> None: """Validate if all required columns are present. Args: - found_cols (list[str]): columns present in dataframe. - """ - - def lookup_columns(func_str: str, sub: str) -> list[str]: - LR_LIKE = [ - "trade_price", - f"price_{sub}_lag", - f"ask_{sub}", - f"bid_{sub}", - ] - REV_LR_LIKE = [ - "trade_price", - f"price_{sub}_lead", - f"ask_{sub}", - f"bid_{sub}", - ] + missing_columns (list): list of missing columns. - LUT_REQUIRED_COLUMNS: dict[str, list[str]] = { - "nan": [], - "clnv": LR_LIKE, - "depth": [ - "trade_price", - f"ask_{sub}", - f"bid_{sub}", - f"ask_size_{sub}", - f"bid_size_{sub}", - ], - "emo": LR_LIKE, - "lr": LR_LIKE, - "quote": ["trade_price", f"ask_{sub}", f"bid_{sub}"], - "rev_clnv": REV_LR_LIKE, - "rev_emo": REV_LR_LIKE, - "rev_lr": REV_LR_LIKE, - "rev_tick": ["trade_price", f"price_{sub}_lead"], - "tick": ["trade_price", f"price_{sub}_lag"], - "trade_size": ["trade_size", f"ask_size_{sub}", f"bid_size_{sub}"], - } - return LUT_REQUIRED_COLUMNS[func_str] - - required_cols_set = set() - for func_str, sub in self._layers: - func_col = lookup_columns(func_str, sub) - required_cols_set.update(func_col) - - missing_cols = sorted(required_cols_set - set(found_cols)) - if missing_cols: + Raises: + ValueError: columns missing in dataframe. + """ + columns = self.columns_ + missing_columns if self.columns_ else missing_columns + self.X_ = pd.DataFrame(np.zeros(shape=(1, len(columns))), columns=columns) + try: + self._predict() + except KeyError as e: + result = re.search(r"'([^']+)'", str(e)) + if result: + add_missing = result.group(1) + if add_missing: + missing_columns.append(add_missing) + return self._validate_columns(missing_columns) + if missing_columns: raise ValueError( - f"Expected to find columns: {missing_cols}. Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/" + f"Expected to find columns: {sorted(missing_columns)}. Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/" ) + del self.X_ + return None def fit( self, @@ -1690,7 +1680,7 @@ API reference self.classes_ = np.array([-1, 1]) # if no features are provided or inferred, use default - if not self.columns_: + if self.columns_ is None: self.columns_ = [str(i) for i in range(X.shape[1])] if len(self.columns_) > 0 and X.shape[1] != len(self.columns_): @@ -1706,9 +1696,7 @@ API reference f"expected one of {ALLOWED_FUNC_STR}." ) - columns = self.columns_ - self._validate_columns(columns) - + self._validate_columns([]) return self def predict(self, X: MatrixLike) -> npt.NDArray: @@ -1731,15 +1719,7 @@ API reference rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -1752,6 +1732,22 @@ API reference del self.X_ return pred + def _predict(self) -> npt.NDArray: + """Predict with rule stack. + + Returns: + npt.NDArray: prediction + """ + pred = np.full(shape=(self.X_.shape[0],), fill_value=np.nan) + for func_str, subset in self._layers: + func = self.func_mapping_[func_str] + pred = np.where( + np.isnan(pred), + func(subset=subset), + pred, + ) + return pred + def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. @@ -1906,10 +1902,7 @@ Source code in src/tclf/classical_classifier.py - 58 - 59 - 60 - 61 + 61 62 63 64 @@ -1948,7 +1941,10 @@ 97 98 99 -100def __init__( +100 +101 +102 +103def __init__( self, layers: list[ tuple[ @@ -2141,7 +2137,31 @@ Source code in src/tclf/classical_classifier.py - 452 + 428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 453 454 455 @@ -2190,33 +2210,7 @@ 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 -527def fit( +501def fit( self, X: MatrixLike, y: ArrayLike | None = None, @@ -2272,7 +2266,7 @@ self.classes_ = np.array([-1, 1]) # if no features are provided or inferred, use default - if not self.columns_: + if self.columns_ is None: self.columns_ = [str(i) for i in range(X.shape[1])] if len(self.columns_) > 0 and X.shape[1] != len(self.columns_): @@ -2288,9 +2282,7 @@ f"expected one of {ALLOWED_FUNC_STR}." ) - columns = self.columns_ - self._validate_columns(columns) - + self._validate_columns([]) return self @@ -2370,46 +2362,38 @@ Source code in src/tclf/classical_classifier.py - 529 + 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 -555 -556 -557 -558 -559 -560 -561 -562 -563 -564 -565 -566 -567 -568def predict(self, X: MatrixLike) -> npt.NDArray: +534def predict(self, X: MatrixLike) -> npt.NDArray: """Perform classification on test vectors `X`. Args: @@ -2429,15 +2413,7 @@ rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -2529,7 +2505,25 @@ Source code in src/tclf/classical_classifier.py - 570 + 552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -736,11 +770,11 @@ A Primer on Trade Classification As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation¶ We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security. -For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 +For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 Basic Rules¶ This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm. Quote Rule¶ -The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. +The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by: \[ \operatorname{quote}\colon \mathcal{A} \to \mathcal{Y},\quad @@ -757,7 +791,7 @@ Quote Ruleclf.fit(X) Tick Test¶ -A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. +A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. The tick test is defined as: \[ \operatorname{tick}\colon \mathbb{N}^2 \to \mathcal{Y},\quad @@ -884,7 +918,7 @@ Chakrabarty-Li-Nguyen-Van-Ness Me Stacked Rule¶ The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. -The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. +The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
58 - 59 - 60 - 61 + 61 62 63 64 @@ -1948,7 +1941,10 @@ 97 98 99 -100def __init__( +100 +101 +102 +103def __init__( self, layers: list[ tuple[ @@ -2141,7 +2137,31 @@ Source code in src/tclf/classical_classifier.py - 452 + 428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 453 454 455 @@ -2190,33 +2210,7 @@ 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 -527def fit( +501def fit( self, X: MatrixLike, y: ArrayLike | None = None, @@ -2272,7 +2266,7 @@ self.classes_ = np.array([-1, 1]) # if no features are provided or inferred, use default - if not self.columns_: + if self.columns_ is None: self.columns_ = [str(i) for i in range(X.shape[1])] if len(self.columns_) > 0 and X.shape[1] != len(self.columns_): @@ -2288,9 +2282,7 @@ f"expected one of {ALLOWED_FUNC_STR}." ) - columns = self.columns_ - self._validate_columns(columns) - + self._validate_columns([]) return self @@ -2370,46 +2362,38 @@ Source code in src/tclf/classical_classifier.py - 529 + 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 -555 -556 -557 -558 -559 -560 -561 -562 -563 -564 -565 -566 -567 -568def predict(self, X: MatrixLike) -> npt.NDArray: +534def predict(self, X: MatrixLike) -> npt.NDArray: """Perform classification on test vectors `X`. Args: @@ -2429,15 +2413,7 @@ rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -2529,7 +2505,25 @@ Source code in src/tclf/classical_classifier.py - 570 + 552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -736,11 +770,11 @@ A Primer on Trade Classification As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation¶ We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security. -For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 +For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 Basic Rules¶ This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm. Quote Rule¶ -The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. +The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by: \[ \operatorname{quote}\colon \mathcal{A} \to \mathcal{Y},\quad @@ -757,7 +791,7 @@ Quote Ruleclf.fit(X) Tick Test¶ -A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. +A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. The tick test is defined as: \[ \operatorname{tick}\colon \mathbb{N}^2 \to \mathcal{Y},\quad @@ -884,7 +918,7 @@ Chakrabarty-Li-Nguyen-Van-Ness Me Stacked Rule¶ The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. -The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. +The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
61 62 63 64 @@ -1948,7 +1941,10 @@ 97 98 99 -100
def __init__( +100 +101 +102 +103
def __init__( self, layers: list[ tuple[ @@ -2141,7 +2137,31 @@ Source code in src/tclf/classical_classifier.py - 452 + 428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 453 454 455 @@ -2190,33 +2210,7 @@ 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 -527def fit( +501def fit( self, X: MatrixLike, y: ArrayLike | None = None, @@ -2272,7 +2266,7 @@ self.classes_ = np.array([-1, 1]) # if no features are provided or inferred, use default - if not self.columns_: + if self.columns_ is None: self.columns_ = [str(i) for i in range(X.shape[1])] if len(self.columns_) > 0 and X.shape[1] != len(self.columns_): @@ -2288,9 +2282,7 @@ f"expected one of {ALLOWED_FUNC_STR}." ) - columns = self.columns_ - self._validate_columns(columns) - + self._validate_columns([]) return self @@ -2370,46 +2362,38 @@ Source code in src/tclf/classical_classifier.py - 529 + 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 -555 -556 -557 -558 -559 -560 -561 -562 -563 -564 -565 -566 -567 -568def predict(self, X: MatrixLike) -> npt.NDArray: +534def predict(self, X: MatrixLike) -> npt.NDArray: """Perform classification on test vectors `X`. Args: @@ -2429,15 +2413,7 @@ rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -2529,7 +2505,25 @@ Source code in src/tclf/classical_classifier.py - 570 + 552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -736,11 +770,11 @@ A Primer on Trade Classification As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation¶ We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security. -For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 +For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 Basic Rules¶ This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm. Quote Rule¶ -The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. +The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by: \[ \operatorname{quote}\colon \mathcal{A} \to \mathcal{Y},\quad @@ -757,7 +791,7 @@ Quote Ruleclf.fit(X) Tick Test¶ -A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. +A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. The tick test is defined as: \[ \operatorname{tick}\colon \mathbb{N}^2 \to \mathcal{Y},\quad @@ -884,7 +918,7 @@ Chakrabarty-Li-Nguyen-Van-Ness Me Stacked Rule¶ The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. -The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. +The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
452 + 428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 453 454 455 @@ -2190,33 +2210,7 @@ 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 -527def fit( +501def fit( self, X: MatrixLike, y: ArrayLike | None = None, @@ -2272,7 +2266,7 @@ self.classes_ = np.array([-1, 1]) # if no features are provided or inferred, use default - if not self.columns_: + if self.columns_ is None: self.columns_ = [str(i) for i in range(X.shape[1])] if len(self.columns_) > 0 and X.shape[1] != len(self.columns_): @@ -2288,9 +2282,7 @@ f"expected one of {ALLOWED_FUNC_STR}." ) - columns = self.columns_ - self._validate_columns(columns) - + self._validate_columns([]) return self @@ -2370,46 +2362,38 @@ Source code in src/tclf/classical_classifier.py - 529 + 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 -555 -556 -557 -558 -559 -560 -561 -562 -563 -564 -565 -566 -567 -568def predict(self, X: MatrixLike) -> npt.NDArray: +534def predict(self, X: MatrixLike) -> npt.NDArray: """Perform classification on test vectors `X`. Args: @@ -2429,15 +2413,7 @@ rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -2529,7 +2505,25 @@ Source code in src/tclf/classical_classifier.py - 570 + 552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -736,11 +770,11 @@ A Primer on Trade Classification As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation¶ We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security. -For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 +For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 Basic Rules¶ This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm. Quote Rule¶ -The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. +The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by: \[ \operatorname{quote}\colon \mathcal{A} \to \mathcal{Y},\quad @@ -757,7 +791,7 @@ Quote Ruleclf.fit(X) Tick Test¶ -A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. +A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. The tick test is defined as: \[ \operatorname{tick}\colon \mathbb{N}^2 \to \mathcal{Y},\quad @@ -884,7 +918,7 @@ Chakrabarty-Li-Nguyen-Van-Ness Me Stacked Rule¶ The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. -The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. +The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 453 454 455 @@ -2190,33 +2210,7 @@ 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
def fit( +501
def fit( self, X: MatrixLike, y: ArrayLike | None = None, @@ -2272,7 +2266,7 @@ self.classes_ = np.array([-1, 1]) # if no features are provided or inferred, use default - if not self.columns_: + if self.columns_ is None: self.columns_ = [str(i) for i in range(X.shape[1])] if len(self.columns_) > 0 and X.shape[1] != len(self.columns_): @@ -2288,9 +2282,7 @@ f"expected one of {ALLOWED_FUNC_STR}." ) - columns = self.columns_ - self._validate_columns(columns) - + self._validate_columns([]) return self
529 + 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 -555 -556 -557 -558 -559 -560 -561 -562 -563 -564 -565 -566 -567 -568def predict(self, X: MatrixLike) -> npt.NDArray: +534def predict(self, X: MatrixLike) -> npt.NDArray: """Perform classification on test vectors `X`. Args: @@ -2429,15 +2413,7 @@ rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -2529,7 +2505,25 @@ Source code in src/tclf/classical_classifier.py - 570 + 552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -736,11 +770,11 @@ A Primer on Trade Classification As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation¶ We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security. -For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 +For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 Basic Rules¶ This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm. Quote Rule¶ -The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. +The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by: \[ \operatorname{quote}\colon \mathcal{A} \to \mathcal{Y},\quad @@ -757,7 +791,7 @@ Quote Ruleclf.fit(X) Tick Test¶ -A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. +A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. The tick test is defined as: \[ \operatorname{tick}\colon \mathbb{N}^2 \to \mathcal{Y},\quad @@ -884,7 +918,7 @@ Chakrabarty-Li-Nguyen-Van-Ness Me Stacked Rule¶ The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. -The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. +The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
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 -555 -556 -557 -558 -559 -560 -561 -562 -563 -564 -565 -566 -567 -568
def predict(self, X: MatrixLike) -> npt.NDArray: +534
def predict(self, X: MatrixLike) -> npt.NDArray: """Perform classification on test vectors `X`. Args: @@ -2429,15 +2413,7 @@ rs = check_random_state(self.random_state) self.X_ = pd.DataFrame(data=X, columns=self.columns_) - pred = np.full(shape=(X.shape[0],), fill_value=np.nan) - - for func_str, subset in self._layers: - func = self.func_mapping_[func_str] - pred = np.where( - np.isnan(pred), - func(subset=subset), - pred, - ) + pred = self._predict() # fill NaNs randomly with -1 and 1 or with constant zero mask = np.isnan(pred) @@ -2529,7 +2505,25 @@ Source code in src/tclf/classical_classifier.py - 570 + 552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -736,11 +770,11 @@ A Primer on Trade Classification As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation¶ We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security. -For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 +For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 Basic Rules¶ This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm. Quote Rule¶ -The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. +The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by: \[ \operatorname{quote}\colon \mathcal{A} \to \mathcal{Y},\quad @@ -757,7 +791,7 @@ Quote Ruleclf.fit(X) Tick Test¶ -A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. +A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. The tick test is defined as: \[ \operatorname{tick}\colon \mathbb{N}^2 \to \mathcal{Y},\quad @@ -884,7 +918,7 @@ Chakrabarty-Li-Nguyen-Van-Ness Me Stacked Rule¶ The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. -The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. +The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
570 + 552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -736,11 +770,11 @@ A Primer on Trade Classification As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation¶ We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security. -For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 +For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵 Basic Rules¶ This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm. Quote Rule¶ -The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. +The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3. Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by: \[ \operatorname{quote}\colon \mathcal{A} \to \mathcal{Y},\quad @@ -757,7 +791,7 @@ Quote Ruleclf.fit(X) Tick Test¶ -A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. +A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45. The tick test is defined as: \[ \operatorname{tick}\colon \mathbb{N}^2 \to \mathcal{Y},\quad @@ -884,7 +918,7 @@ Chakrabarty-Li-Nguyen-Van-Ness Me Stacked Rule¶ The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. -The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. +The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7. In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ
552 +553 +554 +555 +556 +557 +558 +559 +560 +561 +562 +563 +564 +565 +566 +567 +568 +569 +570 571 572 573 @@ -2539,25 +2533,7 @@ 577 578 579 -580 -581 -582 -583 -584 -585 -586 -587 -588 -589 -590 -591 -592 -593 -594 -595 -596 -597 -598
def predict_proba(self, X: MatrixLike) -> npt.NDArray: +580
def predict_proba(self, X: MatrixLike) -> npt.NDArray: """Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. diff --git a/rules/index.html b/rules/index.html index bd45599..dd0e5a7 100644 --- a/rules/index.html +++ b/rules/index.html @@ -26,10 +26,6 @@ - - - - @@ -61,6 +57,8 @@ + + @@ -68,6 +66,8 @@ + + @@ -113,6 +113,40 @@
As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.
We denote the predicted class by \(y \in \mathcal{Y}\) with \(\mathcal{Y}=\{-1,1\}\), whereby \(y=-1\) is indicating a seller-initiated and \(y=1\) a buyer-initiated trade. We denote the sequence of trade prices of the \(i\)-th security by \((P_{i,t})_{t=1}^{T}\) and the corresponding ask at \(t\) by \(A_{i,t}\) and bid by \(B_{i,t}\). The midpoint of the bid-ask spread is denoted by \(M_{i,t} = \tfrac{1}{2}(B_{i,t} + A_{i,t})\). Moreover, we denote the quoted size at the ask with \(\tilde{A}_{i,t}\), \(\tilde{B}_{i,t}\) of the bid, and \(P_{i,t}\) the trade price at \(t\) of the \(i\)-th security.
For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.🥵
This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm.
The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \(M_{i,t}\), the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41)3.
Thus, the classification rule on \(\mathcal{A} = \left\{(i, t) \in \mathbb{N}^2: P_{i,t} \neq M_{i,t}\right\}\) is given by:
A common alternative to the quote rule is the tick test. Based on the rationale that buys increase trade prices and sells lower them, the tick test classifies trades by the change in trade price. It was first applied in (Hasbrouck, 1988, p. 240; Holthausen, Leftwich, & Mayers, 1987, p. 244)45.
The tick test is defined as:
The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15)7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering.
The most basic application is in the LR algorithm, combining \(\operatorname{quote}\) and \(\operatorname{tick}\). For a more complex example consider the hybrid rule consisting of \(\operatorname{tsize}_{\mathrm{ex}}\), \(\operatorname{quote}_{\mathrm{nbbo}}\), \(\operatorname{quote}_{\mathrm{ex}}\), \(\operatorname{depth}_{\mathrm{nbbo}}\), \(\operatorname{depth}_{\mathrm{ex}}\) and \(\operatorname{rtick}_{\mathrm{all}}\) popularized in Grauer et al. (2023, p. 15)7.
In practice, rules may be ordered greedily and new rules added if there are unclassified trades.
Code
from tclf.classical_classifier import ClassicalClassifier @@ -967,7 +1001,7 @@ Comments : "light" // Instruct Giscus to set theme - giscus.setAttribute("data-theme", theme) + giscus.setAttribute("data-theme", theme) } // Register event handlers after documented loaded diff --git a/search/search_index.json b/search/search_index.json index d7db24f..4e1eafc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , found_cols : list [ str ]) -> None : \"\"\"Validate if all required columns are present. Args: found_cols (list[str]): columns present in dataframe. \"\"\" def lookup_columns ( func_str : str , sub : str ) -> list [ str ]: LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lag\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] REV_LR_LIKE = [ \"trade_price\" , f \"price_ { sub } _lead\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , ] LUT_REQUIRED_COLUMNS : dict [ str , list [ str ]] = { \"nan\" : [], \"clnv\" : LR_LIKE , \"depth\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" , ], \"emo\" : LR_LIKE , \"lr\" : LR_LIKE , \"quote\" : [ \"trade_price\" , f \"ask_ { sub } \" , f \"bid_ { sub } \" ], \"rev_clnv\" : REV_LR_LIKE , \"rev_emo\" : REV_LR_LIKE , \"rev_lr\" : REV_LR_LIKE , \"rev_tick\" : [ \"trade_price\" , f \"price_ { sub } _lead\" ], \"tick\" : [ \"trade_price\" , f \"price_ { sub } _lag\" ], \"trade_size\" : [ \"trade_size\" , f \"ask_size_ { sub } \" , f \"bid_size_ { sub } \" ], } return LUT_REQUIRED_COLUMNS [ func_str ] required_cols_set = set () for func_str , sub in self . _layers : func_col = lookup_columns ( func_str , sub ) required_cols_set . update ( func_col ) missing_cols = sorted ( required_cols_set - set ( found_cols )) if missing_cols : raise ValueError ( f \"Expected to find columns: { missing_cols } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if not self . columns_ : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) columns = self . columns_ self . _validate_columns ( columns ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = np . full ( shape = ( X . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file +{"config":{"indexing":"full","lang":["en"],"min_search_length":3,"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"Trade Classification With Python \u00b6 Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks. Installation \u00b6 python -m pip install tclf Supported Algorithms \u00b6 (Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3 Minimal Example \u00b6 Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades. Advanced Example \u00b6 Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section . Citation \u00b6 If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } } Development \u00b6 We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test Footnotes \u00b6 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Home"},{"location":"#trade-classification-with-python","text":"Documentation \u2712\ufe0f: https://karelze.github.io/tclf/ Source Code \ud83d\udc0d: https://github.com/KarelZe/tclf tclf is a scikit-learn -compatible implementation of trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. The key features are: Easy : Easy to use and learn. Sklearn-compatible : Compatible to the sklearn API. Use sklearn metrics and visualizations. Feature complete : Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.","title":"Trade Classification With Python"},{"location":"#installation","text":"python -m pip install tclf","title":"Installation"},{"location":"#supported-algorithms","text":"(Rev.) CLNV rule 1 (Rev.) EMO rule 2 (Rev.) LR algorithm 6 (Rev.) Tick test 5 Depth rule 3 Quote rule 4 Tradesize rule 3","title":"Supported Algorithms"},{"location":"#minimal-example","text":"Let's start simple: classify all trades by the quote rule and all other trades, which cannot be classified by the quote rule, randomly. Create a main.py with: main.py import numpy as np import pandas as pd from tclf.classical_classifier import ClassicalClassifier X = pd . DataFrame ( [ [ 1.5 , 1 , 3 ], [ 2.5 , 1 , 3 ], [ 1.5 , 3 , 1 ], [ 2.5 , 3 , 1 ], [ 1 , np . nan , 1 ], [ 3 , np . nan , np . nan ], ], columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ) clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"random\" ) clf . fit ( X ) probs = clf . predict_proba ( X ) Run your script with $ python main.py In this example, input data is available as a pd.DataFrame with columns conforming to our naming conventions . The parameter layers=[(\"quote\", \"ex\")] sets the quote rule at the exchange level and strategy=\"random\" specifies the fallback strategy for unclassified trades.","title":"Minimal Example"},{"location":"#advanced-example","text":"Often it is desirable to classify both on exchange level data and nbbo data. Also, data might only be available as a numpy array. So let's extend the previous example by classifying using the quote rule at exchange level, then at nbbo and all other trades randomly. main.py import numpy as np from sklearn.metrics import accuracy_score from tclf.classical_classifier import ClassicalClassifier X = np . array ( [ [ 1.5 , 1 , 3 , 2 , 2.5 ], [ 2.5 , 1 , 3 , 1 , 3 ], [ 1.5 , 3 , 1 , 1 , 3 ], [ 2.5 , 3 , 1 , 1 , 3 ], [ 1 , np . nan , 1 , 1 , 3 ], [ 3 , np . nan , np . nan , 1 , 3 ], ] ) y_true = np . array ([ - 1 , 1 , 1 , - 1 , - 1 , 1 ]) features = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" , \"bid_best\" , \"ask_best\" ] clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" ), ( \"quote\" , \"best\" )], strategy = \"random\" , features = features ) clf . fit ( X ) acc = accuracy_score ( y_true , clf . predict ( X )) In this example, input data is available as np.arrays with both exchange ( \"ex\" ) and nbbo data ( \"best\" ). We set the layers parameter to layers=[(\"quote\", \"ex\"), (\"quote\", \"best\")] to classify trades first on subset \"ex\" and remaining trades on subset \"best\" . Additionally, we have to set ClassicalClassifier(..., features=features) to pass column information to the classifier. Like before, column/feature names must follow our naming conventions . For more practical examples, see our examples section .","title":"Advanced Example"},{"location":"#citation","text":"If you are using the package in publications, please cite as: @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = jan, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.5 } , year = { 2024 } }","title":"Citation"},{"location":"#development","text":"We are using pixi as a dependency management and workflow tool. pixi install pixi run postinstall pixi run test","title":"Development"},{"location":"#footnotes","text":"Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Hasbrouck, J. (2009). Trading costs and returns for U.s. Equities: Estimating effective costs from daily data. The Journal of Finance , 64 (3), 1445\u20131477. https://doi.org/10.1111/j.1540-6261.2009.01469.x \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9","title":"Footnotes"},{"location":"naming_conventions/","text":"For tclf to work, we impose constraints on the column names. The following input is required by each rule. Data requirements are additive, if multiple rules are applied. Rule Layer Name Columns No classification (\"nan\",\"sub\") None Tick test (\"tick\",\"sub\") trade_price , price_{sub}_lag Reverse tick Test (\"rev_tick\",\"sub\") trade_price , price_{sub}_lead Quote Rule (\"quote\",\"sub\") trade_price , ask_{sub} , bid_{sub} Lee-Ready Algorithm (\"lr\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} EMO Algorithm (\"emo\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} CLNV Rule (\"clnv\",\"sub\") trade_price , price_{sub}_lag , ask_{sub} , bid_{sub} Reverse Lee-Ready Algorithm (\"rev_lr\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse EMO Algorithm (\"rev_emo\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Reverse CLNV Rule (\"rev_clnv\",\"sub\") trade_price , price_{sub}_lead , ask_{sub} , bid_{sub} Depth rule (\"depth\",\"sub\") trade_price , ask_{sub} , bid_{sub} , ask_size_{sub} , bid_size_{sub} Trade size rule (\"trade_size\",\"sub\") trade_size , ask_size_{sub} , bid_size_{sub}","title":"Naming conventions"},{"location":"nan_handling/","text":"We take care to treat NaN values correctly. If features relevant for classification like the trade price or quoted bid/ask prices are missing, no classification is performed and classification of the trade is deferred to the subsequent rule or fallback strategy. Alternatively, you can provide imputed data. See sklearn.impute for details.","title":"Handling of NaNs"},{"location":"option_trade_classification/","text":"Setup Rules \u00b6 This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) Prepare Dataset \u00b6 Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]] Generate Results \u00b6 Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 ) Plot Results \u00b6 We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42 Footnotes \u00b6 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Option trade classification"},{"location":"option_trade_classification/#setup-rules","text":"This tutorial aims to reproduce plots from a working paper by Grauer et al. (2023) 1 , which achieves state-of-the-art performance in option trade classification. The authors recommend to classify option trades by: [...] our new trade size rule together with quote rules successively applied to NBBO and quotes on the trading venue. Quotes at the midpoint on both the NBBO and the exchange should be classified first with the depth rule and any remaining trades with the reverse tick test. There's a lot going on.\ud83e\udd75 To match the author's description, we first set up layers . We use the tclf implementation of the tradesize , quote , and depth rule , as well as reverse tick test . The subset named \"ex\" refers to exchange-specific data, \"best\" to the NBBO and \"all\" for inter-exchange level data. Identical to the paper, the reverse tick test is applied at the inter-exchange level, due to the devastating results of tick-based algorithms at the exchange level. The authors perform random classification on unclassified trades, hence we choose strategy=\"random\" . from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" )","title":"Setup Rules"},{"location":"option_trade_classification/#prepare-dataset","text":"Next, we need to load a dataset of option trades. I chose one, which was recorded at the ISE and used in the paper to evaluate the trade classification rules. I access it from a google cloud bucket and load it into a pandas dataframe X . import gcsfs import pandas as pd fs = gcsfs . GCSFileSystem () gcs_loc = fs . glob ( \"gs://tclf/bucket_name/dir_name/*\" ) X = pd . read_parquet ( gcs_loc , engine = \"pyarrow\" , filesystem = fs ) Unfortunately, the dataset does not yet follow the naming conventions and is missing columns required by tclf . We take care of this next.\ud83d\ude05 clf . fit ( X ) >>> ValueError : Expected to find columns : [ 'ask_best' , 'ask_size_best' , 'bid_best' , 'bid_size_best' , 'trade_price' , 'trade_size' ] . Check the naming / presence of columns . See : https : // karelze . github . io / tclf / naming_conventions / The calculation of the depth rule requires the columns ask_{subset} , bid_{subset} , and trade_price , as well as ask_size_{subset} , bid_size_{subset} and trade_size . The columns BEST_ASK , BEST_BID , TRADE_PRICE , and TRADE_SIZE are renamed to match our naming conventions of ask_{subset} , bid_{subset} , trade_price , and trade_size . As there is no {ask/bid}_size_best at the NBBO level ( subset=\"best\" ), I copy the columns from the trading venue. This allows us to mimic the author's decision to filter for mid-spread at the NBBO level, but classify by the trade size relative to the ask/bid size at the exchange. We save the true label y_true and the timestamp of the trade QUOTE_DATETIME to a new dataframe, named X_meta , which we use for plotting. We remove these columns from the original dataframe. X = X . rename ( { \"TRADE_PRICE\" : \"trade_price\" , \"TRADE_SIZE\" : \"trade_size\" , \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" , \"buy_sell\" : \"y_true\" , }, axis = 1 , ) features_meta = [ \"QUOTE_DATETIME\" , \"y_true\" ] X_meta = X [ features_meta ] X = X . drop ( columns = features_meta ) X [[ \"ask_size_best\" , \"bid_size_best\" ]] = X [[ \"ask_size_ex\" , \"bid_size_ex\" ]]","title":"Prepare Dataset"},{"location":"option_trade_classification/#generate-results","text":"Next, we can simply pass the prepared dataframe X to the classifier and append the results to our dataframe X_meta . X_meta [ \"y_pred\" ] = clf . fit ( X ) . predict ( X ) To estimate the accuracy over time, we group by date and estimate the accuracy for each group. We make use of sklearn.metrics.accuracy_score . from sklearn.metrics import accuracy_score df_plot = X_meta . groupby ( X_meta . QUOTE_DATETIME . dt . date ) . apply ( lambda x : accuracy_score ( x [ \"y_true\" ], x [ \"y_pred\" ]) * 100 )","title":"Generate Results"},{"location":"option_trade_classification/#plot-results","text":"We use matplotlib to match the plots from the paper as closely as possible. import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter from matplotlib.ticker import PercentFormatter plt . rcParams [ \"font.family\" ] = \"serif\" plt . figure ( figsize = ( 9 , 3 )) plt . grid ( True , axis = \"y\" ) # line plot plt . plot ( df_plot , color = \"tab:orange\" , linewidth = 1.5 , label = \"ISE\" ) # y-axis + x-axis plt . ylim ( 0 , 100 ) plt . ylabel ( \"Overall success rate\" ) ax = plt . gca () ax . yaxis . set_major_formatter ( PercentFormatter ( 100 , decimals = 0 )) ax . xaxis . set_major_formatter ( DateFormatter ( \"%b-%y\" )) # title + legend plt . title ( \"C: Performance of trade classification based on \\n trade size rule + depth rule + reverse LR (NBBO,exchange)\" , loc = \"left\" , ) plt . legend ( loc = \"lower left\" , frameon = False ) plt . show () Output: Pretty close to the author's work. Just spanning a shorter period of time.\ud83d\ude42","title":"Plot Results"},{"location":"option_trade_classification/#footnotes","text":"Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Footnotes"},{"location":"reference/","text":"Welcome to the reference. Bases: ClassifierMixin , BaseEstimator ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Parameters: Name Type Description Default classifier mixin (ClassifierMixin mixin for classifier functionality, such as predict_proba() required base estimator (BaseEstimator base estimator for basic functionality, such as transform() required Source code in src/tclf/classical_classifier.py 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: Tick test, Reverse tick test, Quote rule, LR algorithm, EMO algorithm, CLNV algorithm, Trade size rule, Depth rule, and nan Args: classifier mixin (ClassifierMixin): mixin for classifier functionality, such as `predict_proba()` base estimator (BaseEstimator): base estimator for basic functionality, such as `transform()` \"\"\" X_ = pd . DataFrame def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy def _more_tags ( self ) -> dict [ str , bool | dict [ str , str ]]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" return { \"allow_nan\" : True , \"binary_only\" : True , \"requires_y\" : False , \"poor_score\" : True , \"_xfail_checks\" : { \"check_classifiers_classes\" : \"Disabled due to partly random classification.\" , \"check_classifiers_train\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_one_label\" : \"Disabled due to partly random classification.\" , \"check_methods_subset_invariance\" : \"No check, as unsupervised classifier.\" , \"check_methods_sample_order_invariance\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_no_nan\" : \"No check, as unsupervised classifier.\" , \"check_supervised_y_2d\" : \"No check, as unsupervised classifier.\" , \"check_classifiers_regression_target\" : \"No check, as unsupervised classifier.\" , }, } def _tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the closest different price of a previous trade. Args: subset (str): subset i.e., 'all' or 'ex'. Returns: npt.NDArray: result of tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ \"trade_price\" ] > self . X_ [ f \"price_ { subset } _lag\" ], 1 , np . where ( self . X_ [ \"trade_price\" ] < self . X_ [ f \"price_ { subset } _lag\" ], - 1 , np . nan ), ) def _rev_tick ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a sell (buy) if its trade price is below (above) the closest different price of a subsequent trade. Args: subset (str): subset i.e.,'all' or 'ex'. Returns: npt.NDArray: result of reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"price_ { subset } _lead\" ] > self . X_ [ \"trade_price\" ], - 1 , np . where ( self . X_ [ f \"price_ { subset } _lead\" ] < self . X_ [ \"trade_price\" ], 1 , np . nan ), ) def _quote ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its trade price is above (below) the midpoint of the bid and ask spread. Trades executed at the midspread are not classified. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of quote rule. Can be np.NaN. \"\"\" mid = self . _mid ( subset ) return np . where ( self . X_ [ \"trade_price\" ] > mid , 1 , np . where ( self . X_ [ \"trade_price\" ] < mid , - 1 , np . nan ), ) def _lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.ndarray: result of the lee and ready algorithm with tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _tick ( subset )) def _rev_lr ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the reverse tick test to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the lee and ready algorithm with reverse tick rule. Can be np.NaN. \"\"\" q_r = self . _quote ( subset ) return np . where ( ~ np . isnan ( q_r ), q_r , self . _rev_tick ( subset )) def _mid ( self , subset : str ) -> npt . NDArray : \"\"\"Calculate the midpoint of the bid and ask spread. Midpoint is calculated as the average of the bid and ask spread if the spread is positive. Otherwise, np.NaN is returned. Args: subset (str): subset i.e., 'ex' or 'best' Returns: npt.NDArray: midpoints. Can be np.NaN. \"\"\" return np . where ( self . X_ [ f \"ask_ { subset } \" ] >= self . X_ [ f \"bid_ { subset } \" ], 0.5 * ( self . X_ [ f \"ask_ { subset } \" ] + self . X_ [ f \"bid_ { subset } \" ]), np . nan , ) def _is_at_ask_xor_bid ( self , subset : str ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex' or 'best'. Returns: pd.Series: boolean series with result. \"\"\" at_ask = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"ask_ { subset } \" ], atol = 1e-4 ) at_bid = np . isclose ( self . X_ [ \"trade_price\" ], self . X_ [ f \"bid_ { subset } \" ], atol = 1e-4 ) return at_ask ^ at_bid def _is_at_upper_xor_lower_quantile ( self , subset : str , quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (str): subset i.e., 'ex'. quantiles (float, optional): percentage of quantiles. Defaults to 0.3. Returns: pd.Series: boolean series with result. \"\"\" in_upper = ( ( 1.0 - quantiles ) * self . X_ [ f \"ask_ { subset } \" ] + quantiles * self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ] ) & ( self . X_ [ \"trade_price\" ] <= self . X_ [ f \"ask_ { subset } \" ]) in_lower = ( self . X_ [ f \"bid_ { subset } \" ] <= self . X_ [ \"trade_price\" ]) & ( self . X_ [ \"trade_price\" ] <= quantiles * self . X_ [ f \"ask_ { subset } \" ] + ( 1.0 - quantiles ) * self . X_ [ f \"bid_ { subset } \" ] ) return in_upper ^ in_lower def _emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test to classify all other trades. Adapted from Ellis et al. (2000). Args: subset (Literal["ex", "best"]): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _tick ( subset ) ) def _rev_emo ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the reverse tick test to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with reverse tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_ask_xor_bid ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ) ) def _clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). Args: subset (str): subset i.e.,'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( subset ), ) def _rev_clnv ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade based on deciles of the bid and ask spread. Spread is divided into ten deciles and trades are classified as follows: - use quote rule for at ask until 30 % below ask (upper 3 deciles) - use quote rule for at bid until 30 % above bid (lower 3 deciles) - use reverse tick rule for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Similar to extension of emo algorithm proposed Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the emo algorithm with tick rule. Can be np.NaN. \"\"\" return np . where ( self . _is_at_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( subset ), ) def _trade_size ( self , subset : str ) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) the trade size matches exactly either the bid (ask) quote size. Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ f \"ask_size_ { subset } \" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"bid_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"trade_size\" ], self . X_ [ f \"ask_size_ { subset } \" ], atol = 1e-4 ) & ~ bid_eq_ask ) return np . where ( ts_eq_bid , 1 , np . where ( ts_eq_ask , - 1 , np . nan )) def _depth ( self , subset : str ) -> npt . NDArray : \"\"\"Classify midspread trades as buy (sell), if the ask size (bid size) exceeds the bid size (ask size). Adapted from Grauer et al. (2022). Args: subset (str): subset i.e., 'ex' or 'best'. Returns: npt.NDArray: result of depth rule. Can be np.NaN. \"\"\" at_mid = np . isclose ( self . _mid ( subset ), self . X_ [ \"trade_price\" ], atol = 1e-4 ) return np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] > self . X_ [ f \"bid_size_ { subset } \" ]), 1 , np . where ( at_mid & ( self . X_ [ f \"ask_size_ { subset } \" ] < self . X_ [ f \"bid_size_ { subset } \" ]), - 1 , np . nan , ), ) def _nan ( self , subset : str ) -> npt . NDArray : \"\"\"Classify nothing. Fast forward results from previous classifier. Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" return np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) def _validate_columns ( self , missing_columns : list ) -> None : \"\"\"Validate if all required columns are present. Args: missing_columns (list): list of missing columns. Raises: ValueError: columns missing in dataframe. \"\"\" columns = self . columns_ + missing_columns if self . columns_ else missing_columns self . X_ = pd . DataFrame ( np . zeros ( shape = ( 1 , len ( columns ))), columns = columns ) try : self . _predict () except KeyError as e : result = re . search ( r \"'([^']+)'\" , str ( e )) if result : add_missing = result . group ( 1 ) if add_missing : missing_columns . append ( add_missing ) return self . _validate_columns ( missing_columns ) if missing_columns : raise ValueError ( f \"Expected to find columns: { sorted ( missing_columns ) } . Check naming/presenence of columns. See: https://karelze.github.io/tclf/naming_conventions/\" ) del self . X_ return None def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred def _predict ( self ) -> npt . NDArray : \"\"\"Predict with rule stack. Returns: npt.NDArray: prediction \"\"\" pred = np . full ( shape = ( self . X_ . shape [ 0 ],), fill_value = np . nan ) for func_str , subset in self . _layers : func = self . func_mapping_ [ func_str ] pred = np . where ( np . isnan ( pred ), func ( subset = subset ), pred , ) return pred def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob __init__ ( layers = None , * , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy fit ( X , y = None , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred predict_proba ( X ) \u00b6 Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"API reference"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.__init__","text":"Initialize a ClassicalClassifier. Examples: >>> X = pd . DataFrame ( ... [ ... [ 1.5 , 1 , 3 ], ... [ 2.5 , 1 , 3 ], ... [ 1.5 , 3 , 1 ], ... [ 2.5 , 3 , 1 ], ... [ 1 , np . nan , 1 ], ... [ 3 , np . nan , np . nan ], ... ], ... columns = [ \"trade_price\" , \"bid_ex\" , \"ask_ex\" ], ... ) >>> clf = ClassicalClassifier ( layers = [( \"quote\" , \"ex\" )], strategy = \"const\" ) >>> clf . fit ( X ) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf . predict_proba ( X ) Parameters: Name Type Description Default layers List [ tuple [ ALLOWED_FUNC_LITERALS , str ]] Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. None features List [ str ] | None List of feature names in order of columns. Required to match columns in feature matrix with label. Can be None , if pd.DataFrame is passed. Defaults to None. None random_state float | None random seed. Defaults to 42. 42 strategy Literal["random", "const"] Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to \"random\". 'random' Source code in src/tclf/classical_classifier.py 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 def __init__ ( self , layers : list [ tuple [ ALLOWED_FUNC_LITERALS , str , ] ] | None = None , * , features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Examples: >>> X = pd.DataFrame( ... [ ... [1.5, 1, 3], ... [2.5, 1, 3], ... [1.5, 3, 1], ... [2.5, 3, 1], ... [1, np.nan, 1], ... [3, np.nan, np.nan], ... ], ... columns=[\"trade_price\", \"bid_ex\", \"ask_ex\"], ... ) >>> clf = ClassicalClassifier(layers=[(\"quote\", \"ex\")], strategy=\"const\") >>> clf.fit(X) ClassicalClassifier(layers=[('quote', 'ex')], strategy='const') >>> pred = clf.predict_proba(X) Args: layers (List[tuple[ALLOWED_FUNC_LITERALS, str]]): Layers of classical rule and subset name. Supported rules: \"tick\", \"rev_tick\", \"quote\", \"lr\", \"rev_lr\", \"emo\", \"rev_emo\", \"trade_size\", \"depth\", and \"nan\". Defaults to None, which results in classification by 'strategy' parameter. features (List[str] | None, optional): List of feature names in order of columns. Required to match columns in feature matrix with label. Can be `None`, if `pd.DataFrame` is passed. Defaults to None. random_state (float | None, optional): random seed. Defaults to 42. strategy (Literal["random", "const"], optional): Strategy to fill unclassfied. Randomly with uniform probability or with constant 0. Defaults to "random". \"\"\" self . layers = layers self . random_state = random_state self . features = features self . strategy = strategy","title":"__init__()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.fit","text":"Fit the classifier. Parameters: Name Type Description Default X MatrixLike features required y ArrayLike | None ignored, present here for API consistency by convention. None sample_weight NDArray | None Sample weights. Defaults to None. None Raises: Type Description ValueError Unknown subset e. g., 'ise' ValueError Unknown function string e. g., 'lee-ready' ValueError Multi output is not supported. Returns: Name Type Description ClassicalClassifier ClassicalClassifier Instance of itself. Source code in src/tclf/classical_classifier.py 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 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 def fit ( self , X : MatrixLike , y : ArrayLike | None = None , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (MatrixLike): features y (ArrayLike | None, optional): ignored, present here for API consistency by convention. sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' ValueError: Unknown function string e. g., 'lee-ready' ValueError: Multi output is not supported. Returns: ClassicalClassifier: Instance of itself. \"\"\" _check_sample_weight ( sample_weight , X ) funcs = ( self . _tick , self . _rev_tick , self . _quote , self . _lr , self . _rev_lr , self . _emo , self . _rev_emo , self . _clnv , self . _rev_clnv , self . _trade_size , self . _depth , self . _nan , ) self . func_mapping_ = dict ( zip ( ALLOWED_FUNC_STR , funcs )) # create working copy to be altered and try to get columns from df self . columns_ = self . features if isinstance ( X , pd . DataFrame ): self . columns_ = X . columns . tolist () X = self . _validate_data ( X , y = \"no_validation\" , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) self . classes_ = np . array ([ - 1 , 1 ]) # if no features are provided or inferred, use default if self . columns_ is None : self . columns_ = [ str ( i ) for i in range ( X . shape [ 1 ])] if len ( self . columns_ ) > 0 and X . shape [ 1 ] != len ( self . columns_ ): raise ValueError ( f \"Expected { len ( self . columns_ ) } columns, got { X . shape [ 1 ] } .\" ) self . _layers = self . layers if self . layers is not None else [] for func_str , _ in self . _layers : if func_str not in ALLOWED_FUNC_STR : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { ALLOWED_FUNC_STR } .\" ) self . _validate_columns ([]) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X MatrixLike feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (MatrixLike): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) X = self . _validate_data ( X , dtype = [ np . float64 , np . float32 ], accept_sparse = False , force_all_finite = False , ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) pred = self . _predict () # fill NaNs randomly with -1 and 1 or with constant zero mask = np . isnan ( pred ) if self . strategy == \"random\" : pred [ mask ] = rs . choice ( self . classes_ , pred . shape )[ mask ] else : pred [ mask ] = np . zeros ( pred . shape )[ mask ] # reset self.X_ to avoid persisting it del self . X_ return pred","title":"predict()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict_proba","text":"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Parameters: Name Type Description Default X MatrixLike feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 def predict_proba ( self , X : MatrixLike ) -> npt . NDArray : \"\"\"Predict class probabilities for X. Probabilities are either 0 or 1 depending on the class. For strategy 'constant' probabilities are (0.5,0.5) for unclassified classes. Args: X (MatrixLike): feature matrix Returns: npt.NDArray: probabilities \"\"\" # assign 0.5 to all classes. Required for strategy 'constant'. prob = np . full (( len ( X ), 2 ), 0.5 ) # Class can be assumed to be -1 or 1 for strategy 'random'. # Class might be zero though for strategy constant. Mask non-zeros. preds = self . predict ( X ) mask = np . flatnonzero ( preds ) # get index of predicted class and one-hot encode it indices = np . nonzero ( preds [ mask , None ] == self . classes_ [ None , :])[ 1 ] n_classes = np . max ( self . classes_ ) + 1 # overwrite defaults with one-hot encoded classes. # For strategy 'constant' probabilities are (0.5,0.5). prob [ mask ] = np . identity ( n_classes )[ indices ] return prob","title":"predict_proba()"},{"location":"rules/","text":"A Primer on Trade Classification Rules \u00b6 The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification. Notation \u00b6 We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75 Basic Rules \u00b6 This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm . Quote Rule \u00b6 The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Reverse Tick Test \u00b6 The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X ) Depth Rule \u00b6 The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X ) Trade Size Rule \u00b6 The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X ) Hybrid Rules \u00b6 The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering. Lee and Ready Algorithm \u00b6 The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X ) Ellis-Michaely-O'Hara Rule \u00b6 Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X ) Chakrabarty-Li-Nguyen-Van-Ness Method \u00b6 Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X ) Stacked Rule \u00b6 The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X ) Footnotes \u00b6 Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Rules"},{"location":"rules/#a-primer-on-trade-classification-rules","text":"The goal of trade classification algorithms is to identify the initiator of a trade . While definitions for the trade initiator differ in literature (cp. Lee & Radhakrishna, 2000, pp. 94--97; Odders-White, 2000, p. 262) 1 2 the trade initiator is binary and either the buyer or the seller. As the trade initiator is frequently absent in datasets, it must be inferred using trade classification algorithms or other approaches. This article introduces basic rules for trade classification.","title":"A Primer on Trade Classification Rules"},{"location":"rules/#notation","text":"We denote the predicted class by \\(y \\in \\mathcal{Y}\\) with \\(\\mathcal{Y}=\\{-1,1\\}\\) , whereby \\(y=-1\\) is indicating a seller-initiated and \\(y=1\\) a buyer-initiated trade. We denote the sequence of trade prices of the \\(i\\) -th security by \\((P_{i,t})_{t=1}^{T}\\) and the corresponding ask at \\(t\\) by \\(A_{i,t}\\) and bid by \\(B_{i,t}\\) . The midpoint of the bid-ask spread is denoted by \\(M_{i,t} = \\tfrac{1}{2}(B_{i,t} + A_{i,t})\\) . Moreover, we denote the quoted size at the ask with \\(\\tilde{A}_{i,t}\\) , \\(\\tilde{B}_{i,t}\\) of the bid, and \\(P_{i,t}\\) the trade price at \\(t\\) of the \\(i\\) -th security. For simplicity we assume an ideal data regime, where quote data is complete and spreads are positive.\ud83e\udd75","title":"Notation"},{"location":"rules/#basic-rules","text":"This section presents basic classification rules, that may be used for trade classification independently or integrated into a hybrid algorithm .","title":"Basic Rules"},{"location":"rules/#quote-rule","text":"The quote rule classifies a trade by comparing the trade price against the corresponding quotes at the time of the trade. If the trade price is above the midpoint of the bid-ask spread, \\(M_{i,t}\\) , the trade is classified as a buy and if it is below the midpoint, as a sell (Harris, 1989, p. 41) 3 . Thus, the classification rule on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} \\neq M_{i,t}\\right\\}\\) is given by: \\[ \\operatorname{quote}\\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{quote}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t}>M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t}P_{i, t-1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t-1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t=1 \\\\ \\operatorname{tick}(i, t-1), & \\mathrm{else}. \\end{cases} \\] Considering the cases the trade price is higher than the previous price (uptick) the trade is classified as a buy. Reversely, if it is below the previous price (downtick), the trade is classified as a sell. If the price change is zero (zero tick), the signing uses the last price different from the current price (Lee & Ready, 1991, p. 735) 6 . To end recursion at \\(t=1\\) , we sign the trades randomly as buyer- or seller-initiated to simplify notation \ud83e\udd13. The tick rule can sign all trades as long as a last differing trade price exists, but the overall precision can be impacted by infrequent trading. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Tick Test"},{"location":"rules/#reverse-tick-test","text":"The reverse tick test is a variant of the tick test proposed in (Hasbrouck, 1988, p. 241) 5 . It is similar to the tick rule but classifies based on the next, distinguishable trade price. \\[ \\operatorname{rtick} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad \\operatorname{rtick}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > P_{i, t+1} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < P_{i, t+1} \\\\ Y\\sim\\mathrm{Uniform}(\\mathcal{Y}), & \\mathrm{if}\\ t+1=T \\\\ \\operatorname{rtick}(i, t+1), & \\mathrm{else} \\end{cases} \\] As denoted in the equation, the trade is classified as seller-initiated, if the next trade is on an uptick or a zero uptick, and classified as buyer-initiated for trades at a downtick or a zero downtick (Lee & Ready, 1991, pp. 735--736) 6 . Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"rev_tick\" , \"subset\" )], strategy = \"random\" ) clf . fit ( X )","title":"Reverse Tick Test"},{"location":"rules/#depth-rule","text":"The depth rule gauges the trade initiator from the quoted size at the best bid and ask. Based on the observation that an exceeding bid or ask size relates to higher liquidity at one trade side, trades are classified as a buy (sell) for a larger ask (bid) size (Grauer, Schuster, & Uhrig-Homburg, 2023, pp. 14--15) 7 . We set the domain as \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: P_{i,t} = M_{i,t} \\land \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\right\\}\\) . The depth rule is now calculated as: \\[ \\operatorname{depth} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{depth}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{A}_{i,t} > \\tilde{B}_{i,t}. \\\\ -1, & \\mathrm{if}\\ \\tilde{A}_{i,t} < \\tilde{B}_{i,t}\\\\ \\end{cases} \\] The depth rule classifies midspread trades only, if the ask size is different from the bid size, as the ratio between the ask and bid size is the sole criterion for inferring the trade's initiator. Due to these restrictive conditions in \\(\\mathcal{A}\\) , the depth rule can sign only a fraction of all trades and must be best followed by other rules. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"depth\" , \"subset\" )]) clf . fit ( X )","title":"Depth Rule"},{"location":"rules/#trade-size-rule","text":"The trade size rule classifies based on a match between the size of the trade \\(\\tilde{P}_{i, t}\\) and the quoted bid and ask sizes. The rationale is, that the market maker tries to fill the limit order of a customer, which results in the trade being executed at the contemporaneous bid or ask, with a trade size equaling the quoted size (Grauer, Schuster, & Uhrig-Homburg, 2023) 7 . The trade size rule is defined on \\(\\mathcal{A} = \\left\\{(i, t) \\in \\mathbb{N}^2: \\tilde{P}_{i,t} = \\tilde{A}_{i,t} \\neq \\tilde{B}_{i,t} \\lor \\tilde{P}_{i,t} \\neq\\tilde{A}_{i,t} = \\tilde{B}_{i,t} \\right\\}\\) as: \\[ \\operatorname{tsize} \\colon \\mathcal{A} \\to \\mathcal{Y},\\quad \\operatorname{tsize}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{B}_{i, t} \\neq \\tilde{A}_{i, t} \\\\ -1, & \\mathrm{if}\\ \\tilde{P}_{i, t} = \\tilde{A}_{i, t} \\neq \\tilde{B}_{i, t}. \\\\ \\end{cases} \\] When both the size of the ask and bid correspond with the trade size or the trade size does not match the quoted sizes, the result is ambiguous. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"trade_size\" , \"subset\" )]) clf . fit ( X )","title":"Trade Size Rule"},{"location":"rules/#hybrid-rules","text":"The basic trade classification rules from basic rules can be combined into a hybrid algorithm to enforce universal applicability to all trades and improve the classification performance. Popular variants include the LR algorithm , the EMO rule , and the CLNV method . All three algorithms utilize the quote and tick rule to a varying extent. Basic rules are selected based on the proximity of the trade price to the quotes. As put forth by Grauer et al. (2023) 7 , basic or hybrid rules can be combined through stacking. This approach generalizes the aforementioned algorithms, as the applied rule is no longer dependent on the proximity to the quotes, but rather on the classifiability of the trade with the primary rules given by the domains and their ordering.","title":"Hybrid Rules"},{"location":"rules/#lee-and-ready-algorithm","text":"The LR algorithm (Lee & Ready, 1991, p. 745) 6 combines the (reverse) tick test and quote rule into a single rule, which is derived from two observations. First, Lee and Ready (1991, pp. 735--745) 6 observe a higher precision of the quote rule over the tick rule, which makes it their preferred choice. Second, by the means of a simple model, the authors demonstrate that the tick test can correctly classify on average 85.4 % of all midspread trades if the model's assumptions of constant quotes between trades and the arrival of the market and standing orders following a Poisson process are met. Outside the model's tight assumptions, the expected accuracy of the tick test can be unmet. In combination, the algorithm primarily signs trades according to the quote rule. Trades at the midpoint of the spread, unclassifiable by the quote rule, are classified by the tick test. Overall: \\[ \\operatorname{lr} \\colon \\mathbb{N}^2 \\to \\mathcal{Y},\\quad\\operatorname{lr}(i,t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} > M_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} < M_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"lr\" , \"subset\" )]) clf . fit ( X )","title":"Lee and Ready Algorithm"},{"location":"rules/#ellis-michaely-ohara-rule","text":"Ellis et al. (2000, pp. 535--536) 8 examine the performance of the previous algorithms for stocks traded at NASDAQ. By analyzing miss-classified trades with regard to the proximity of the trade to the quotes, they observe, that the quote rule and by extension, the LR algorithm , perform particularly well at classifying trades executed at the bid and the ask price but trail the performance of the tick rule for trades inside or outside the spread (Ellis, Michaely, & O'Hara, 2000, pp. 535--536) 8 . The authors combine these observations into a single rule, known as the EMO algorithm. The EMO algorithm extends the tick rule by classifying trades at the quotes using the quote rule, and all other trades with the tick test. Formally, the classification rule is given by: \\[ \\operatorname{emo} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{emo}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} = A_{i, t} \\\\ -1, & \\mathrm{if}\\ P_{i, t} = B_{i, t} \\\\ \\operatorname{tick}(i, t), & \\mathrm{else}. \\end{cases} \\] The EMO algorithm embeds both the quote and tick rule. As trades off the quotes are classified by the tick rule, the algorithm's overall success rate is dominated by the tick test assuming most trades are off-the-quotes. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"emo\" , \"subset\" )]) clf . fit ( X )","title":"Ellis-Michaely-O'Hara Rule"},{"location":"rules/#chakrabarty-li-nguyen-van-ness-method","text":"Like the previous two algorithms, the CLNV method (Chakrabarty, Li, Nguyen, & Van Ness, 2007, pp. 3811--3812) 9 is a hybrid of the quote and tick rule and extends the EMO rule by a differentiated treatment of trades inside the quotes, which are notoriously hard to classify. The authors segment the bid-ask spread into deciles (ten equal-width bins) and classify trades around the midpoint (fourth to seventh decile) by the tick rule and trades close or outside the quotes are categorized by the tick rule. \\[ \\operatorname{clnv} \\colon \\mathbb{N}^2 \\to \\mathcal{Y}, \\quad \\operatorname{clnv}(i, t)= \\begin{cases} 1, & \\mathrm{if}\\ P_{i, t} \\in \\left(\\frac{3}{10} B_{i,t} + \\frac{7}{10} A_{i,t}, A_{i, t}\\right] \\\\ -1, & \\mathrm{if}\\ P_{i, t} \\in \\left[ B_{i,t}, \\frac{7}{10} B_{i,t} + \\frac{3}{10} A_{i,t}\\right) \\\\ \\operatorname{tick}(i, t), & \\mathrm{else} \\end{cases} \\] It is derived from a performance comparison of the tick rule ( EMO rule ) against the quote rule ( LR algorithm ) on stock data, whereby the accuracy was assessed separately for each decile. Code from tclf.classical_classifier import ClassicalClassifier clf = ClassicalClassifier ( layers = [( \"clnv\" , \"subset\" )]) clf . fit ( X )","title":"Chakrabarty-Li-Nguyen-Van-Ness Method"},{"location":"rules/#stacked-rule","text":"The previous algorithms are static concerning the used base rules and their alignment. Combining arbitrary rules into a single algorithm requires a generic procedure. Grauer et al. (2023, p. 15) 7 combine basic and hybrid rules through stacking. In this setting, the trade traverses a stack of pre-defined rules until a rule can classify the trade or the end of the stack is reached. The classification is now dependent on the employed rules but also on their relative ordering. The most basic application is in the LR algorithm , combining \\(\\operatorname{quote}\\) and \\(\\operatorname{tick}\\) . For a more complex example consider the hybrid rule consisting of \\(\\operatorname{tsize}_{\\mathrm{ex}}\\) , \\(\\operatorname{quote}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{quote}_{\\mathrm{ex}}\\) , \\(\\operatorname{depth}_{\\mathrm{nbbo}}\\) , \\(\\operatorname{depth}_{\\mathrm{ex}}\\) and \\(\\operatorname{rtick}_{\\mathrm{all}}\\) popularized in Grauer et al. (2023, p. 15) 7 . In practice, rules may be ordered greedily and new rules added if there are unclassified trades. Code from tclf.classical_classifier import ClassicalClassifier layers = [ ( \"trade_size\" , \"ex\" ), ( \"quote\" , \"best\" ), ( \"quote\" , \"ex\" ), ( \"depth\" , \"best\" ), ( \"depth\" , \"ex\" ), ( \"rev_tick\" , \"all\" ), ] clf = ClassicalClassifier ( layers = layers , strategy = \"random\" ) clf . fit ( X )","title":"Stacked Rule"},{"location":"rules/#footnotes","text":"Lee, C., & Radhakrishna, B. (2000). Inferring investor behavior: Evidence from TORQ data. Journal of Financial Markets , 3 (2), 83\u2013111. https://doi.org/10.1016/S1386-4181(00)00002-1 \u21a9 Odders-White, E. R. (2000). On the occurrence and consequences of inaccurate trade classification. Journal of Financial Markets , 3 (3), 259\u2013286. https://doi.org/10.1016/S1386-4181(00)00006-9 \u21a9 Harris, L. (1989). A day-end transaction price anomaly. The Journal of Financial and Quantitative Analysis , 24 (1), 29. https://doi.org/10.2307/2330746 \u21a9 Holthausen, R. W., Leftwich, R. W., & Mayers, D. (1987). The effect of large block transactions on security prices: A cross-sectional analysis. Journal of Financial Economics , 19 (2), 237\u2013267. https://doi.org/10.1016/0304-405X(87)90004-3 \u21a9 Hasbrouck, J. (1988). Trades, quotes, inventories, and information. Journal of Financial Economics , 22 (2), 229\u2013252. https://doi.org/10.1016/0304-405X(88)90070-0 \u21a9 \u21a9 Lee, C., & Ready, M. J. (1991). Inferring trade direction from intraday data. The Journal of Finance , 46 (2), 733\u2013746. https://doi.org/10.1111/j.1540-6261.1991.tb02683.x \u21a9 \u21a9 \u21a9 \u21a9 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9 \u21a9 \u21a9 \u21a9 \u21a9 Ellis, K., Michaely, R., & O\u2019Hara, M. (2000). The accuracy of trade classification rules: Evidence from nasdaq. The Journal of Financial and Quantitative Analysis , 35 (4), 529\u2013551. https://doi.org/10.2307/2676254 \u21a9 \u21a9 Chakrabarty, B., Li, B., Nguyen, V., & Van Ness, R. A. (2007). Trade classification algorithms for electronic communications network trades. Journal of Banking & Finance , 31 (12), 3806\u20133821. https://doi.org/10.1016/j.jbankfin.2007.03.003 \u21a9","title":"Footnotes"}]} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 7dc3590..c497924 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -2,32 +2,32 @@ https://karelze.github.io/tclf/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/naming_conventions/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/nan_handling/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/option_trade_classification/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/reference/ - 2024-01-12 + 2024-01-13 daily https://karelze.github.io/tclf/rules/ - 2024-01-12 + 2024-01-13 daily \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index 71f90c4..5cf2b3e 100644 Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ