From 2472136030caed936c3b2dc07543be555c18e89c Mon Sep 17 00:00:00 2001 From: Markus Bilz Date: Mon, 20 Nov 2023 18:06:46 +0100 Subject: [PATCH] Deployed fb518b9 with MkDocs version: 1.5.3 --- reference/index.html | 56 +++++++++++++++------------------------ search/search_index.json | 2 +- sitemap.xml.gz | Bin 217 -> 217 bytes 3 files changed, 23 insertions(+), 35 deletions(-) diff --git a/reference/index.html b/reference/index.html index c30b233..8e79d5a 100644 --- a/reference/index.html +++ b/reference/index.html @@ -899,10 +899,7 @@

API reference

520 521 522 -523 -524 -525 -526
class ClassicalClassifier(ClassifierMixin, BaseEstimator):
+523
class ClassicalClassifier(ClassifierMixin, BaseEstimator):
     """ClassicalClassifier implements several trade classification rules.
 
     Including:
@@ -942,9 +939,7 @@ 

API reference

Args: layers (List[ tuple[ str, str, ] ]): Layers of classical rule. - 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. + 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". """ @@ -1257,8 +1252,7 @@

API reference

Args: X (npt.NDArray | pd.DataFrame): features y (npt.NDArray | pd.Series): ground truth (ignored) - sample_weight (npt.NDArray | None, optional): Sample weights. - Defaults to None. + sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' @@ -1458,7 +1452,7 @@

-

List of feature names in order of

+

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.

@@ -1522,9 +1516,7 @@

80 81 82 -83 -84 -85
def __init__(
+83
def __init__(
     self,
     *,
     layers: list[
@@ -1541,9 +1533,7 @@ 

Args: layers (List[ tuple[ str, str, ] ]): Layers of classical rule. - 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. + 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". """ @@ -1621,7 +1611,7 @@

-

Sample weights.

+

Sample weights. Defaults to None.

@@ -1701,7 +1691,9 @@

Source code in src/tclf/classical_classifier.py -
380
+            
378
+379
+380
 381
 382
 383
@@ -1774,10 +1766,7 @@ 

450 451 452 -453 -454 -455 -456

def fit(
+453
def fit(
     self,
     X: npt.NDArray | pd.DataFrame,
     y: npt.NDArray | pd.Series,
@@ -1788,8 +1777,7 @@ 

Args: X (npt.NDArray | pd.DataFrame): features y (npt.NDArray | pd.Series): ground truth (ignored) - sample_weight (npt.NDArray | None, optional): Sample weights. - Defaults to None. + sample_weight (npt.NDArray | None, optional): Sample weights. Defaults to None. Raises: ValueError: Unknown subset e. g., 'ise' @@ -1932,7 +1920,10 @@

Source code in src/tclf/classical_classifier.py -
458
+            
455
+456
+457
+458
 459
 460
 461
@@ -1967,10 +1958,7 @@ 

490 491 492 -493 -494 -495 -496

def predict(self, X: npt.NDArray | pd.DataFrame) -> npt.NDArray:
+493
def predict(self, X: npt.NDArray | pd.DataFrame) -> npt.NDArray:
     """Perform classification on test vectors `X`.
 
     Args:
@@ -2089,7 +2077,10 @@ 

Source code in src/tclf/classical_classifier.py -
498
+            
495
+496
+497
+498
 499
 500
 501
@@ -2114,10 +2105,7 @@ 

520 521 522 -523 -524 -525 -526

def predict_proba(self, X: npt.NDArray | pd.DataFrame) -> npt.NDArray:
+523
def predict_proba(self, X: npt.NDArray | pd.DataFrame) -> npt.NDArray:
     """Predict class probabilities for X.
 
     Probabilities are either 0 or 1 depending on the class.
diff --git a/search/search_index.json b/search/search_index.json
index d5c1cac..5fc1852 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 for python \u00b6 scikit-learn -compatible implementation of popular trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. Algorithms \u00b6 Tick test Quote rule LR algorithm EMO rule CLNV rule Depth rule Tradesize rule References \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 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 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 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 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 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","title":"Home"},{"location":"#trade-classification-for-python","text":"scikit-learn -compatible implementation of popular trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades.","title":"Trade classification for python"},{"location":"#algorithms","text":"Tick test Quote rule LR algorithm EMO rule CLNV rule Depth rule Tradesize rule","title":"Algorithms"},{"location":"#references","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 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 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 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 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 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","title":"References"},{"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 * LR algorithm with reverse tick test * EMO algorithm * EMO algorithm with reverse tick test * CLNV algorithm * CLNV algorithm with reverse tick test * Trade size rule * Depth rule * nan ClassifierMixin ( _type_ ): ClassifierMixin BaseEstimator ( _type_ ): Baseestimator Source code in src/tclf/classical_classifier.py 36 37 38 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 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: * Tick test * Reverse tick test * Quote rule * LR algorithm * LR algorithm with reverse tick test * EMO algorithm * EMO algorithm with reverse tick test * CLNV algorithm * CLNV algorithm with reverse tick test * Trade size rule * Depth rule * nan Args: ---- ClassifierMixin (_type_): ClassifierMixin BaseEstimator (_type_): Baseestimator \"\"\" def __init__ ( self , * , layers : list [ tuple [ str , str , ] ], features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Args: layers (List[ tuple[ str, str, ] ]): Layers of classical rule. 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 ]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" # FIXME: Try enabling _skip_test again. Skip tests, as prediction is not # invariant and parameters immutable. return { \"allow_nan\" : True , \"binary_only\" : True , \"_skip_test\" : True , \"poor_score\" : True , } def _tick ( self , subset : Literal [ \"all\" , \"ex\" ]) -> 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 (Literal["all", "ex"]): 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 : Literal [ \"all\" , \"ex\" ]) -> 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 (Literal["all", "ex"]): 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 : Literal [ \"best\" , \"ex\" ]) -> 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 (Literal["ex", "best"]): 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 : Literal [ \"best\" , \"ex\" ]) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test (all) to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (Literal["ex", "best"]): 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 ( \"all\" )) def _rev_lr ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (all) to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (Literal["ex", "best"]): 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 ( \"all\" )) def _mid ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (Literal["best", "ex"]): 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 : Literal [ \"best\" , \"ex\" ]) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (Literal["ex", "best"]): 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 : Literal [ \"best\" , \"ex\" ], quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (Literal["best", "ex"]): 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 : Literal [ \"best\" , \"ex\" ]) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test (all) 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 ( \"all\" ) ) def _rev_emo ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (all) to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (Literal["ex", "best"]): 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 ( \"all\" ) ) def _clnv ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (all) for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). 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_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( \"all\" ), ) def _rev_clnv ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (all) 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 (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_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( \"all\" ), ) def _trade_size ( self , * args : Any ) -> 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). Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ \"ask_size_ex\" ], self . X_ [ \"bid_size_ex\" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"TRADE_SIZE\" ], self . X_ [ \"bid_size_ex\" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"TRADE_SIZE\" ], self . X_ [ \"ask_size_ex\" ], 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 : Literal [ \"best\" , \"ex\" ]) -> 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 (Literal["best", "ex"]): subset 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_ [ \"ask_size_ex\" ] > self . X_ [ \"bid_size_ex\" ]), 1 , np . where ( at_mid & ( self . X_ [ \"ask_size_ex\" ] < self . X_ [ \"bid_size_ex\" ]), - 1 , np . nan , ), ) def _nan ( self , * args : Any ) -> 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 fit ( self , X : npt . NDArray | pd . DataFrame , y : npt . NDArray | pd . Series , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (npt.NDArray | pd.DataFrame): features y (npt.NDArray | pd.Series): ground truth (ignored) 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 () check_classification_targets ( y ) X , y = check_X_y ( X , y , multi_output = False , accept_sparse = False , force_all_finite = False ) # FIXME: make flexible if open-sourced # self.classes_ = np.unique(y) 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 ] } .\" ) for func_str , subset in self . layers : if subset not in allowed_subsets : raise ValueError ( f \"Unknown subset: { subset } , expected one of { allowed_subsets } .\" ) if func_str not in allowed_func_str : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { allowed_func_str } .\" ) return self def predict ( self , X : npt . NDArray | pd . DataFrame ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (npt.NDArray | pd.DataFrame): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) mapping_cols = { \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" } self . X_ = self . X_ . rename ( columns = mapping_cols ) 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 ), 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 : npt . NDArray | pd . DataFrame ) -> 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 (npt.NDArray | pd.DataFrame): 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 . where ( 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 , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Parameters: Name Type Description Default layers List [ tuple [ str , str ]] Layers of classical rule. required features List [ str ] | None List of feature names in order of 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 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 def __init__ ( self , * , layers : list [ tuple [ str , str , ] ], features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Args: layers (List[ tuple[ str, str, ] ]): Layers of classical rule. 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 , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X NDArray | DataFrame features required y NDArray | Series ground truth (ignored) required sample_weight NDArray | None Sample weights. 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 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 def fit ( self , X : npt . NDArray | pd . DataFrame , y : npt . NDArray | pd . Series , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (npt.NDArray | pd.DataFrame): features y (npt.NDArray | pd.Series): ground truth (ignored) 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 () check_classification_targets ( y ) X , y = check_X_y ( X , y , multi_output = False , accept_sparse = False , force_all_finite = False ) # FIXME: make flexible if open-sourced # self.classes_ = np.unique(y) 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 ] } .\" ) for func_str , subset in self . layers : if subset not in allowed_subsets : raise ValueError ( f \"Unknown subset: { subset } , expected one of { allowed_subsets } .\" ) if func_str not in allowed_func_str : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { allowed_func_str } .\" ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X NDArray | DataFrame feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : npt . NDArray | pd . DataFrame ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (npt.NDArray | pd.DataFrame): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) mapping_cols = { \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" } self . X_ = self . X_ . rename ( columns = mapping_cols ) 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 ), 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 NDArray | DataFrame feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 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 def predict_proba ( self , X : npt . NDArray | pd . DataFrame ) -> 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 (npt.NDArray | pd.DataFrame): 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 . where ( 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. Parameters: Name Type Description Default layers List [ tuple [ str , str ]] Layers of classical rule. required features List [ str ] | None List of feature names in order of 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 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 def __init__ ( self , * , layers : list [ tuple [ str , str , ] ], features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Args: layers (List[ tuple[ str, str, ] ]): Layers of classical rule. 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 NDArray | DataFrame features required y NDArray | Series ground truth (ignored) required sample_weight NDArray | None Sample weights. 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 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 def fit ( self , X : npt . NDArray | pd . DataFrame , y : npt . NDArray | pd . Series , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (npt.NDArray | pd.DataFrame): features y (npt.NDArray | pd.Series): ground truth (ignored) 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 () check_classification_targets ( y ) X , y = check_X_y ( X , y , multi_output = False , accept_sparse = False , force_all_finite = False ) # FIXME: make flexible if open-sourced # self.classes_ = np.unique(y) 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 ] } .\" ) for func_str , subset in self . layers : if subset not in allowed_subsets : raise ValueError ( f \"Unknown subset: { subset } , expected one of { allowed_subsets } .\" ) if func_str not in allowed_func_str : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { allowed_func_str } .\" ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X NDArray | DataFrame feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : npt . NDArray | pd . DataFrame ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (npt.NDArray | pd.DataFrame): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) mapping_cols = { \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" } self . X_ = self . X_ . rename ( columns = mapping_cols ) 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 ), 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 NDArray | DataFrame feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 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 def predict_proba ( self , X : npt . NDArray | pd . DataFrame ) -> 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 (npt.NDArray | pd.DataFrame): 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 . where ( 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 for python \u00b6 scikit-learn -compatible implementation of popular trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades. Algorithms \u00b6 Tick test Quote rule LR algorithm EMO rule CLNV rule Depth rule Tradesize rule References \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 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 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 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 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 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","title":"Home"},{"location":"#trade-classification-for-python","text":"scikit-learn -compatible implementation of popular trade classification algorithms to classify financial markets transactions into buyer- and seller-initiated trades.","title":"Trade classification for python"},{"location":"#algorithms","text":"Tick test Quote rule LR algorithm EMO rule CLNV rule Depth rule Tradesize rule","title":"Algorithms"},{"location":"#references","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 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 Grauer, C., Schuster, P., & Uhrig-Homburg, M. (2023). Option trade classification . https://doi.org/10.2139/ssrn.4098475 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 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 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","title":"References"},{"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 * LR algorithm with reverse tick test * EMO algorithm * EMO algorithm with reverse tick test * CLNV algorithm * CLNV algorithm with reverse tick test * Trade size rule * Depth rule * nan ClassifierMixin ( _type_ ): ClassifierMixin BaseEstimator ( _type_ ): Baseestimator Source code in src/tclf/classical_classifier.py 36 37 38 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 class ClassicalClassifier ( ClassifierMixin , BaseEstimator ): \"\"\"ClassicalClassifier implements several trade classification rules. Including: * Tick test * Reverse tick test * Quote rule * LR algorithm * LR algorithm with reverse tick test * EMO algorithm * EMO algorithm with reverse tick test * CLNV algorithm * CLNV algorithm with reverse tick test * Trade size rule * Depth rule * nan Args: ---- ClassifierMixin (_type_): ClassifierMixin BaseEstimator (_type_): Baseestimator \"\"\" def __init__ ( self , * , layers : list [ tuple [ str , str , ] ], features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Args: layers (List[ tuple[ str, str, ] ]): Layers of classical rule. 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 ]: \"\"\"Set tags for sklearn. See: https://scikit-learn.org/stable/developers/develop.html#estimator-tags \"\"\" # FIXME: Try enabling _skip_test again. Skip tests, as prediction is not # invariant and parameters immutable. return { \"allow_nan\" : True , \"binary_only\" : True , \"_skip_test\" : True , \"poor_score\" : True , } def _tick ( self , subset : Literal [ \"all\" , \"ex\" ]) -> 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 (Literal["all", "ex"]): 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 : Literal [ \"all\" , \"ex\" ]) -> 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 (Literal["all", "ex"]): 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 : Literal [ \"best\" , \"ex\" ]) -> 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 (Literal["ex", "best"]): 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 : Literal [ \"best\" , \"ex\" ]) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if its price is above (below) the midpoint (quote rule), and use the tick test (all) to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (Literal["ex", "best"]): 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 ( \"all\" )) def _rev_lr ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (all) to classify midspread trades. Adapted from Lee and Ready (1991). Args: subset (Literal["ex", "best"]): 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 ( \"all\" )) def _mid ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (Literal["best", "ex"]): 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 : Literal [ \"best\" , \"ex\" ]) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (Literal["ex", "best"]): 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 : Literal [ \"best\" , \"ex\" ], quantiles : float = 0.3 ) -> pd . Series : \"\"\"Check if the trade price is at the ask xor bid. Args: subset (Literal["best", "ex"]): 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 : Literal [ \"best\" , \"ex\" ]) -> npt . NDArray : \"\"\"Classify a trade as a buy (sell) if the trade takes place at the ask (bid) quote, and use the tick test (all) 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 ( \"all\" ) ) def _rev_emo ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (all) to classify all other trades. Adapted from Grauer et al. (2022). Args: subset (Literal["ex", "best"]): 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 ( \"all\" ) ) def _clnv ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (all) for all other trades (\u00b12 deciles from midpoint; outside bid or ask). Adapted from Chakrabarty et al. (2007). 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_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _tick ( \"all\" ), ) def _rev_clnv ( self , subset : Literal [ \"best\" , \"ex\" ]) -> 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 (all) 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 (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_upper_xor_lower_quantile ( subset ), self . _quote ( subset ), self . _rev_tick ( \"all\" ), ) def _trade_size ( self , * args : Any ) -> 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). Returns: npt.NDArray: result of the trade size rule. Can be np.NaN. \"\"\" bid_eq_ask = np . isclose ( self . X_ [ \"ask_size_ex\" ], self . X_ [ \"bid_size_ex\" ], atol = 1e-4 ) ts_eq_bid = ( np . isclose ( self . X_ [ \"TRADE_SIZE\" ], self . X_ [ \"bid_size_ex\" ], atol = 1e-4 ) & ~ bid_eq_ask ) ts_eq_ask = ( np . isclose ( self . X_ [ \"TRADE_SIZE\" ], self . X_ [ \"ask_size_ex\" ], 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 : Literal [ \"best\" , \"ex\" ]) -> 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 (Literal["best", "ex"]): subset 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_ [ \"ask_size_ex\" ] > self . X_ [ \"bid_size_ex\" ]), 1 , np . where ( at_mid & ( self . X_ [ \"ask_size_ex\" ] < self . X_ [ \"bid_size_ex\" ]), - 1 , np . nan , ), ) def _nan ( self , * args : Any ) -> 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 fit ( self , X : npt . NDArray | pd . DataFrame , y : npt . NDArray | pd . Series , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (npt.NDArray | pd.DataFrame): features y (npt.NDArray | pd.Series): ground truth (ignored) 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 () check_classification_targets ( y ) X , y = check_X_y ( X , y , multi_output = False , accept_sparse = False , force_all_finite = False ) # FIXME: make flexible if open-sourced # self.classes_ = np.unique(y) 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 ] } .\" ) for func_str , subset in self . layers : if subset not in allowed_subsets : raise ValueError ( f \"Unknown subset: { subset } , expected one of { allowed_subsets } .\" ) if func_str not in allowed_func_str : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { allowed_func_str } .\" ) return self def predict ( self , X : npt . NDArray | pd . DataFrame ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (npt.NDArray | pd.DataFrame): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) mapping_cols = { \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" } self . X_ = self . X_ . rename ( columns = mapping_cols ) 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 ), 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 : npt . NDArray | pd . DataFrame ) -> 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 (npt.NDArray | pd.DataFrame): 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 . where ( 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 , features = None , random_state = 42 , strategy = 'random' ) \u00b6 Initialize a ClassicalClassifier. Parameters: Name Type Description Default layers List [ tuple [ str , str ]] Layers of classical rule. required 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 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 def __init__ ( self , * , layers : list [ tuple [ str , str , ] ], features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Args: layers (List[ tuple[ str, str, ] ]): Layers of classical rule. 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 , sample_weight = None ) \u00b6 Fit the classifier. Parameters: Name Type Description Default X NDArray | DataFrame features required y NDArray | Series ground truth (ignored) required 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 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 def fit ( self , X : npt . NDArray | pd . DataFrame , y : npt . NDArray | pd . Series , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (npt.NDArray | pd.DataFrame): features y (npt.NDArray | pd.Series): ground truth (ignored) 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 () check_classification_targets ( y ) X , y = check_X_y ( X , y , multi_output = False , accept_sparse = False , force_all_finite = False ) # FIXME: make flexible if open-sourced # self.classes_ = np.unique(y) 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 ] } .\" ) for func_str , subset in self . layers : if subset not in allowed_subsets : raise ValueError ( f \"Unknown subset: { subset } , expected one of { allowed_subsets } .\" ) if func_str not in allowed_func_str : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { allowed_func_str } .\" ) return self predict ( X ) \u00b6 Perform classification on test vectors X . Parameters: Name Type Description Default X NDArray | DataFrame feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : npt . NDArray | pd . DataFrame ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (npt.NDArray | pd.DataFrame): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) mapping_cols = { \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" } self . X_ = self . X_ . rename ( columns = mapping_cols ) 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 ), 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 NDArray | DataFrame feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 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 def predict_proba ( self , X : npt . NDArray | pd . DataFrame ) -> 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 (npt.NDArray | pd.DataFrame): 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 . where ( 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. Parameters: Name Type Description Default layers List [ tuple [ str , str ]] Layers of classical rule. required 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 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 def __init__ ( self , * , layers : list [ tuple [ str , str , ] ], features : list [ str ] | None = None , random_state : float | None = 42 , strategy : Literal [ \"random\" , \"const\" ] = \"random\" , ): \"\"\"Initialize a ClassicalClassifier. Args: layers (List[ tuple[ str, str, ] ]): Layers of classical rule. 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 NDArray | DataFrame features required y NDArray | Series ground truth (ignored) required 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 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 def fit ( self , X : npt . NDArray | pd . DataFrame , y : npt . NDArray | pd . Series , sample_weight : npt . NDArray | None = None , ) -> ClassicalClassifier : \"\"\"Fit the classifier. Args: X (npt.NDArray | pd.DataFrame): features y (npt.NDArray | pd.Series): ground truth (ignored) 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 () check_classification_targets ( y ) X , y = check_X_y ( X , y , multi_output = False , accept_sparse = False , force_all_finite = False ) # FIXME: make flexible if open-sourced # self.classes_ = np.unique(y) 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 ] } .\" ) for func_str , subset in self . layers : if subset not in allowed_subsets : raise ValueError ( f \"Unknown subset: { subset } , expected one of { allowed_subsets } .\" ) if func_str not in allowed_func_str : raise ValueError ( f \"Unknown function string: { func_str } ,\" f \"expected one of { allowed_func_str } .\" ) return self","title":"fit()"},{"location":"reference/#tclf.classical_classifier.ClassicalClassifier.predict","text":"Perform classification on test vectors X . Parameters: Name Type Description Default X NDArray | DataFrame feature matrix. required Returns: Type Description NDArray npt.NDArray: Predicted traget values for X. Source code in src/tclf/classical_classifier.py 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 def predict ( self , X : npt . NDArray | pd . DataFrame ) -> npt . NDArray : \"\"\"Perform classification on test vectors `X`. Args: X (npt.NDArray | pd.DataFrame): feature matrix. Returns: npt.NDArray: Predicted traget values for X. \"\"\" check_is_fitted ( self ) rs = check_random_state ( self . random_state ) self . X_ = pd . DataFrame ( data = X , columns = self . columns_ ) mapping_cols = { \"BEST_ASK\" : \"ask_best\" , \"BEST_BID\" : \"bid_best\" } self . X_ = self . X_ . rename ( columns = mapping_cols ) 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 ), 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 NDArray | DataFrame feature matrix required Returns: Type Description NDArray npt.NDArray: probabilities Source code in src/tclf/classical_classifier.py 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 def predict_proba ( self , X : npt . NDArray | pd . DataFrame ) -> 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 (npt.NDArray | pd.DataFrame): 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 . where ( 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 da4be2d4ed549b9dc143d41ea349125fe2d0b741..96cb1fc15df327ba32daa1638767998a72d06671 100644
GIT binary patch
delta 14
Vcmcb~c$1M$zMF$XZPG-x%K#zU1eX8+

delta 14
Vcmcb~c$1M$zMF%icH%^~%K#&a1nmF-