From c82caee07f4c00ac630e4fcaac351b436f9f170c Mon Sep 17 00:00:00 2001 From: Markus Bilz Date: Thu, 4 Jan 2024 19:21:35 +0100 Subject: [PATCH] Deployed 4a3ed8e with MkDocs version: 1.5.3 --- index.html | 4 +--- search/search_index.json | 2 +- sitemap.xml.gz | Bin 263 -> 263 bytes 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index e89aefd..2669891 100644 --- a/index.html +++ b/index.html @@ -520,9 +520,7 @@

Trade classification with python 🐍<
  • Feature complete: Wide range of supported algorithms. Use the algorithms individually or stack them like LEGO blocks.
  • Installation

    -
    $ python -m pip install tclf
    ----> 100%
    -Successfully installed tclf-0.0.2
    +
    python -m pip install tclf
     

    Supported Algorithms

      diff --git a/search/search_index.json b/search/search_index.json index 4ff6400..1336788 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 \ud83d\udc0d \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 ---> 100% Successfully installed tclf-0.0.2 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 @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = dec, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.2 } , year = { 2023 } } 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 \ud83d\udc0d"},{"location":"#installation","text":"$ python -m pip install tclf ---> 100% Successfully installed tclf-0.0.2","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":"@software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = dec, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.2 } , year = { 2023 } }","title":"Citation"},{"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 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 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 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 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Plot Results"},{"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()"}]} \ 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 \ud83d\udc0d \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 @software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = dec, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.2 } , year = { 2023 } } 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 \ud83d\udc0d"},{"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":"@software { bilz _ tclf _ 2023, author = { Bilz, Markus } , license = { BSD 3 } , month = dec, title = {{ tclf } -- trade classification with python } , url = { https://github.com/KarelZe/tclf } , version = { 0.0.2 } , year = { 2023 } }","title":"Citation"},{"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 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 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 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 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 \u21a9","title":"Plot Results"},{"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()"}]} \ No newline at end of file diff --git a/sitemap.xml.gz b/sitemap.xml.gz index a71433d658f3b953b5212ba172ff81346007f412..36bed243f19bfcf9b354dc40d75ee442c9edb49e 100644 GIT binary patch delta 15 WcmZo?YG-1T@8;mp`@WHlkr4nMngg)_ delta 15 WcmZo?YG-1T@8;n68Mcv)kr4nOHv`)M