spforge 0.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. spforge-0.0.0/LICENSE +201 -0
  2. spforge-0.0.0/MANIFEST.in +3 -0
  3. spforge-0.0.0/PKG-INFO +155 -0
  4. spforge-0.0.0/README.md +127 -0
  5. spforge-0.0.0/examples/__init__.py +2 -0
  6. spforge-0.0.0/examples/lol/__init__.py +0 -0
  7. spforge-0.0.0/examples/lol/data/__init__.py +0 -0
  8. spforge-0.0.0/examples/lol/data/subsample_lol_data.parquet +0 -0
  9. spforge-0.0.0/examples/lol/data/utils.py +20 -0
  10. spforge-0.0.0/examples/lol/pipeline_transformer_example.py +158 -0
  11. spforge-0.0.0/examples/nba/__init__.py +0 -0
  12. spforge-0.0.0/examples/nba/cross_validation_example.py +131 -0
  13. spforge-0.0.0/examples/nba/data/__init__.py +0 -0
  14. spforge-0.0.0/examples/nba/data/game_player_subsample.parquet +0 -0
  15. spforge-0.0.0/examples/nba/data/utils.py +19 -0
  16. spforge-0.0.0/examples/nba/game_winner_example.py +94 -0
  17. spforge-0.0.0/requirements.txt +10 -0
  18. spforge-0.0.0/setup.cfg +4 -0
  19. spforge-0.0.0/setup.py +21 -0
  20. spforge-0.0.0/spforge/__init__.py +3 -0
  21. spforge-0.0.0/spforge/cross_validator/__init__.py +2 -0
  22. spforge-0.0.0/spforge/cross_validator/_base.py +47 -0
  23. spforge-0.0.0/spforge/cross_validator/cross_validator.py +203 -0
  24. spforge-0.0.0/spforge/data_structures.py +195 -0
  25. spforge-0.0.0/spforge/pipeline.py +293 -0
  26. spforge-0.0.0/spforge/pipeline_factory.py +87 -0
  27. spforge-0.0.0/spforge/pipeline_transformer.py +129 -0
  28. spforge-0.0.0/spforge/predictor/__init__.py +8 -0
  29. spforge-0.0.0/spforge/predictor/_base.py +239 -0
  30. spforge-0.0.0/spforge/predictor/classifier.py +196 -0
  31. spforge-0.0.0/spforge/predictor/predictor.py +586 -0
  32. spforge-0.0.0/spforge/predictor/sklearn_estimator.py +77 -0
  33. spforge-0.0.0/spforge/predictor_transformer/__init__.py +5 -0
  34. spforge-0.0.0/spforge/predictor_transformer/_simple_transformer.py +120 -0
  35. spforge-0.0.0/spforge/predictor_transformer/transformer.py +111 -0
  36. spforge-0.0.0/spforge/ratings/__init__.py +15 -0
  37. spforge-0.0.0/spforge/ratings/enums.py +43 -0
  38. spforge-0.0.0/spforge/ratings/league_identifier.py +108 -0
  39. spforge-0.0.0/spforge/ratings/match_generator.py +399 -0
  40. spforge-0.0.0/spforge/ratings/performance_generator/__init__.py +6 -0
  41. spforge-0.0.0/spforge/ratings/performance_generator/_performances_generator.py +250 -0
  42. spforge-0.0.0/spforge/ratings/rating_calculators/__init__.py +6 -0
  43. spforge-0.0.0/spforge/ratings/rating_calculators/match_rating_generator.py +526 -0
  44. spforge-0.0.0/spforge/ratings/rating_calculators/performance_predictor.py +356 -0
  45. spforge-0.0.0/spforge/ratings/rating_calculators/start_rating_generator.py +199 -0
  46. spforge-0.0.0/spforge/ratings/rating_generator.py +158 -0
  47. spforge-0.0.0/spforge/ratings/update_rating_generator.py +908 -0
  48. spforge-0.0.0/spforge/scorer/__init__.py +1 -0
  49. spforge-0.0.0/spforge/scorer/_score.py +493 -0
  50. spforge-0.0.0/spforge/transformation_pipeline.py +0 -0
  51. spforge-0.0.0/spforge/transformers/__init__.py +12 -0
  52. spforge-0.0.0/spforge/transformers/_lag.py +225 -0
  53. spforge-0.0.0/spforge/transformers/_rolling_mean.py +237 -0
  54. spforge-0.0.0/spforge/transformers/_rolling_mean_binary.py +272 -0
  55. spforge-0.0.0/spforge/transformers/_rolling_mean_days.py +222 -0
  56. spforge-0.0.0/spforge/transformers/base_transformer.py +513 -0
  57. spforge-0.0.0/spforge/transformers/performances_transformers.py +525 -0
  58. spforge-0.0.0/spforge/transformers/transformers.py +332 -0
  59. spforge-0.0.0/spforge/tuner/__init__.py +5 -0
  60. spforge-0.0.0/spforge/tuner/base_tuner.py +13 -0
  61. spforge-0.0.0/spforge/tuner/performances_generator_tuner.py +208 -0
  62. spforge-0.0.0/spforge/tuner/pipeline_tuner.py +306 -0
  63. spforge-0.0.0/spforge/tuner/predictor_tuner.py +253 -0
  64. spforge-0.0.0/spforge/tuner/rating_generator_tuner.py +403 -0
  65. spforge-0.0.0/spforge/tuner/start_rating_optimizer.py +287 -0
  66. spforge-0.0.0/spforge/tuner/utils.py +171 -0
  67. spforge-0.0.0/spforge/utils.py +70 -0
  68. spforge-0.0.0/spforge.egg-info/PKG-INFO +155 -0
  69. spforge-0.0.0/spforge.egg-info/SOURCES.txt +72 -0
  70. spforge-0.0.0/spforge.egg-info/dependency_links.txt +1 -0
  71. spforge-0.0.0/spforge.egg-info/requires.txt +10 -0
  72. spforge-0.0.0/spforge.egg-info/top_level.txt +2 -0
  73. spforge-0.0.0/tests/test_pipeline.py +487 -0
  74. spforge-0.0.0/tests/test_pipeline_transformer.py +92 -0
spforge-0.0.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ include requirements.txt
2
+ recursive-include examples/nba/data *.parquet
3
+ recursive-include examples/lol/data *.parquet
spforge-0.0.0/PKG-INFO ADDED
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: spforge
3
+ Version: 0.0.0
4
+ Summary: A flexible framework for generating features, ratings, and building machine learning or other models for training and inference on sports data.
5
+ Home-page: https://github.com/Hiderdk/player-performance-ratings
6
+ Author: Mathias Holmstrøm
7
+ Author-email: mathiasholmstom@gmail.com
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: numpy>=1.23.4
11
+ Requires-Dist: optuna>=3.4.0
12
+ Requires-Dist: pandas>=2.0.0
13
+ Requires-Dist: pendulum>=1.0.0
14
+ Requires-Dist: scikit_learn>=1.3.1
15
+ Requires-Dist: lightgbm>=4.0.0
16
+ Requires-Dist: narwhals>=1.31.0
17
+ Requires-Dist: polars>=1.17.0
18
+ Requires-Dist: pytest>=8.0.0
19
+ Requires-Dist: pyarrow>=19.0.0
20
+ Dynamic: author
21
+ Dynamic: author-email
22
+ Dynamic: description
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: license-file
26
+ Dynamic: requires-dist
27
+ Dynamic: summary
28
+
29
+ # spforge
30
+
31
+ Framework designed to predict outcomes in sports games using player-based ratings or other forms of engineered features such as rolling means.
32
+ Ratings can be used to predict game-winner, but also other outcomes such as total points scored, total yards gained, etc.
33
+
34
+ ## Installation
35
+
36
+ ```
37
+ pip install spforge
38
+ ```
39
+
40
+
41
+ ## Examples
42
+ Ensure you have a dataset where each row is a unique combination of game_ids and player_ids.
43
+ There are multiple different use-cases for the framework, such as:
44
+ 1. Creating ratings for players/teams.
45
+ 2. Predicting the outcome.
46
+ 3. Creating features or other types of data-transformations
47
+
48
+ ### Predicting Game-Winner
49
+
50
+ Ensure you have a dataset where each row is a unique combination of game_ids and player_ids.
51
+ Even if the concept of a player doesn't exist in the dataset, you can use team_id instead of player_id.
52
+
53
+ Utilizing a rating model can be as simple as:
54
+
55
+ ```
56
+ import pandas as pd
57
+ from sklearn.linear_model import LogisticRegression
58
+
59
+ from spforge.pipeline import Pipeline
60
+ from spforge.predictor import GameTeamPredictor, SklearnPredictor
61
+
62
+ from spforge.ratings import UpdateRatingGenerator
63
+
64
+ from spforge.data_structures import ColumnNames
65
+ from spforge.ratings.rating_calculators import MatchRatingGenerator
66
+
67
+ df = pd.read_parquet("data/game_player_subsample.parquet")
68
+
69
+ # Defines the column names as they appear in the dataframe
70
+ column_names = ColumnNames(
71
+ team_id="team_id",
72
+ match_id="game_id",
73
+ start_date="start_date",
74
+ player_id="player_name",
75
+ )
76
+ # Sorts the dataframe. The dataframe must always be sorted as below
77
+ df = df.sort_values(
78
+ by=[
79
+ column_names.start_date,
80
+ column_names.match_id,
81
+ column_names.team_id,
82
+ column_names.player_id,
83
+ ]
84
+ )
85
+
86
+ # Drops games with less or more than 2 teams
87
+ df = (
88
+ df.assign(
89
+ team_count=df.groupby(column_names.match_id)[column_names.team_id].transform(
90
+ "nunique"
91
+ )
92
+ )
93
+ .loc[lambda x: x.team_count == 2]
94
+ .drop(columns=["team_count"])
95
+ )
96
+
97
+ # Pretends the last 10 games are future games. The most will be trained on everything before that.
98
+ most_recent_10_games = df[column_names.match_id].unique()[-10:]
99
+ historical_df = df[~df[column_names.match_id].isin(most_recent_10_games)]
100
+ future_df = df[df[column_names.match_id].isin(most_recent_10_games)].drop(
101
+ columns=["won"]
102
+ )
103
+
104
+ # Defining a simple rating-generator. It will use the "won" column to update the ratings.
105
+ # In contrast to a typical Elo, ratings will follow players.
106
+
107
+ match_rating_generator = MatchRatingGenerator(rating_change_multiplier=30)
108
+
109
+ rating_generator = UpdateRatingGenerator(
110
+ performance_column="won", match_rating_generator=match_rating_generator
111
+ )
112
+
113
+ # Defines the predictor. A machine-learning model will be used to predict game winner on a game-team-level.
114
+ # Mean team-ratings will be calculated (from player-level) and rating-difference between the 2 teams calculated.
115
+ # It will also use the location of the game as a feature.
116
+ predictor = GameTeamPredictor(
117
+ game_id_colum=column_names.match_id,
118
+ team_id_column=column_names.team_id,
119
+ predictor=SklearnPredictor(
120
+ estimator_features=["location"], target="won", estimator=LogisticRegression()
121
+ ),
122
+ one_hot_encode_cat_features=True,
123
+ )
124
+
125
+ # Pipeline is whether we define all the steps. Other transformations can take place as well.
126
+ # However, in our simple example we only have a simple rating-generator and a predictor.
127
+ pipeline = Pipeline(
128
+ rating_generators=rating_generator,
129
+ predictor=predictor,
130
+ column_names=column_names,
131
+ )
132
+
133
+ # Trains the model and returns historical predictions
134
+ pipeline.train(df=historical_df)
135
+
136
+ # Future predictions on future results
137
+ future_predictions = pipeline.predict(df=future_df)
138
+
139
+ # Grouping predictions from game-player level to game-level.
140
+ team_grouped_predictions = future_predictions.groupby(column_names.match_id).first()[
141
+ [
142
+ column_names.start_date,
143
+ column_names.team_id,
144
+ "team_id_opponent",
145
+ predictor.pred_column,
146
+ ]
147
+ ]
148
+
149
+ print(team_grouped_predictions)
150
+
151
+ ```
152
+
153
+ ## Further Examples
154
+
155
+
@@ -0,0 +1,127 @@
1
+ # spforge
2
+
3
+ Framework designed to predict outcomes in sports games using player-based ratings or other forms of engineered features such as rolling means.
4
+ Ratings can be used to predict game-winner, but also other outcomes such as total points scored, total yards gained, etc.
5
+
6
+ ## Installation
7
+
8
+ ```
9
+ pip install spforge
10
+ ```
11
+
12
+
13
+ ## Examples
14
+ Ensure you have a dataset where each row is a unique combination of game_ids and player_ids.
15
+ There are multiple different use-cases for the framework, such as:
16
+ 1. Creating ratings for players/teams.
17
+ 2. Predicting the outcome.
18
+ 3. Creating features or other types of data-transformations
19
+
20
+ ### Predicting Game-Winner
21
+
22
+ Ensure you have a dataset where each row is a unique combination of game_ids and player_ids.
23
+ Even if the concept of a player doesn't exist in the dataset, you can use team_id instead of player_id.
24
+
25
+ Utilizing a rating model can be as simple as:
26
+
27
+ ```
28
+ import pandas as pd
29
+ from sklearn.linear_model import LogisticRegression
30
+
31
+ from spforge.pipeline import Pipeline
32
+ from spforge.predictor import GameTeamPredictor, SklearnPredictor
33
+
34
+ from spforge.ratings import UpdateRatingGenerator
35
+
36
+ from spforge.data_structures import ColumnNames
37
+ from spforge.ratings.rating_calculators import MatchRatingGenerator
38
+
39
+ df = pd.read_parquet("data/game_player_subsample.parquet")
40
+
41
+ # Defines the column names as they appear in the dataframe
42
+ column_names = ColumnNames(
43
+ team_id="team_id",
44
+ match_id="game_id",
45
+ start_date="start_date",
46
+ player_id="player_name",
47
+ )
48
+ # Sorts the dataframe. The dataframe must always be sorted as below
49
+ df = df.sort_values(
50
+ by=[
51
+ column_names.start_date,
52
+ column_names.match_id,
53
+ column_names.team_id,
54
+ column_names.player_id,
55
+ ]
56
+ )
57
+
58
+ # Drops games with less or more than 2 teams
59
+ df = (
60
+ df.assign(
61
+ team_count=df.groupby(column_names.match_id)[column_names.team_id].transform(
62
+ "nunique"
63
+ )
64
+ )
65
+ .loc[lambda x: x.team_count == 2]
66
+ .drop(columns=["team_count"])
67
+ )
68
+
69
+ # Pretends the last 10 games are future games. The most will be trained on everything before that.
70
+ most_recent_10_games = df[column_names.match_id].unique()[-10:]
71
+ historical_df = df[~df[column_names.match_id].isin(most_recent_10_games)]
72
+ future_df = df[df[column_names.match_id].isin(most_recent_10_games)].drop(
73
+ columns=["won"]
74
+ )
75
+
76
+ # Defining a simple rating-generator. It will use the "won" column to update the ratings.
77
+ # In contrast to a typical Elo, ratings will follow players.
78
+
79
+ match_rating_generator = MatchRatingGenerator(rating_change_multiplier=30)
80
+
81
+ rating_generator = UpdateRatingGenerator(
82
+ performance_column="won", match_rating_generator=match_rating_generator
83
+ )
84
+
85
+ # Defines the predictor. A machine-learning model will be used to predict game winner on a game-team-level.
86
+ # Mean team-ratings will be calculated (from player-level) and rating-difference between the 2 teams calculated.
87
+ # It will also use the location of the game as a feature.
88
+ predictor = GameTeamPredictor(
89
+ game_id_colum=column_names.match_id,
90
+ team_id_column=column_names.team_id,
91
+ predictor=SklearnPredictor(
92
+ estimator_features=["location"], target="won", estimator=LogisticRegression()
93
+ ),
94
+ one_hot_encode_cat_features=True,
95
+ )
96
+
97
+ # Pipeline is whether we define all the steps. Other transformations can take place as well.
98
+ # However, in our simple example we only have a simple rating-generator and a predictor.
99
+ pipeline = Pipeline(
100
+ rating_generators=rating_generator,
101
+ predictor=predictor,
102
+ column_names=column_names,
103
+ )
104
+
105
+ # Trains the model and returns historical predictions
106
+ pipeline.train(df=historical_df)
107
+
108
+ # Future predictions on future results
109
+ future_predictions = pipeline.predict(df=future_df)
110
+
111
+ # Grouping predictions from game-player level to game-level.
112
+ team_grouped_predictions = future_predictions.groupby(column_names.match_id).first()[
113
+ [
114
+ column_names.start_date,
115
+ column_names.team_id,
116
+ "team_id_opponent",
117
+ predictor.pred_column,
118
+ ]
119
+ ]
120
+
121
+ print(team_grouped_predictions)
122
+
123
+ ```
124
+
125
+ ## Further Examples
126
+
127
+
@@ -0,0 +1,2 @@
1
+ from .nba.data.utils import get_sub_sample_nba_data
2
+ from .lol.data.utils import get_sub_sample_lol_data
File without changes
File without changes
@@ -0,0 +1,20 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Union
4
+
5
+ import polars as pl
6
+ import pandas as pd
7
+
8
+
9
+ def get_sub_sample_lol_data(
10
+ as_pandas: bool = True, as_polars: bool = False
11
+ ) -> Union[pd.DataFrame]:
12
+ script_dir = Path(__file__).parent
13
+ file_path = os.path.join(script_dir, "subsample_lol_data.parquet")
14
+
15
+ if as_polars:
16
+ return pl.read_parquet(file_path)
17
+ elif as_pandas:
18
+ return pd.read_parquet(file_path)
19
+ else:
20
+ raise ValueError("Must specify either as_pandas or as_polars")
@@ -0,0 +1,158 @@
1
+ from lightgbm import LGBMRegressor
2
+ from sklearn.linear_model import LogisticRegression
3
+
4
+ from examples import get_sub_sample_lol_data
5
+ from spforge import ColumnNames
6
+ from spforge.cross_validator import MatchKFoldCrossValidator
7
+ from spforge.pipeline_transformer import PipelineTransformer
8
+ from spforge.predictor import (
9
+ GameTeamPredictor,
10
+ SklearnPredictor,
11
+ )
12
+ from spforge.predictor.classifier import NegativeBinomialPredictor
13
+ from spforge.ratings import (
14
+ UpdateRatingGenerator,
15
+ RatingKnownFeatures,
16
+ )
17
+ from spforge.ratings.performance_generator import (
18
+ PerformancesGenerator,
19
+ Performance,
20
+ ColumnWeight,
21
+ )
22
+ from spforge.transformers import LagTransformer
23
+ from spforge.transformers import (
24
+ RollingMeanTransformer,
25
+ )
26
+
27
+ column_names = ColumnNames(
28
+ team_id="teamname",
29
+ match_id="gameid",
30
+ start_date="date",
31
+ player_id="playername",
32
+ league="league",
33
+ position="position",
34
+ )
35
+ df = get_sub_sample_lol_data(as_pandas=True)
36
+ df = (
37
+ df.loc[lambda x: x.position != "team"]
38
+ .assign(team_count=df.groupby("gameid")["teamname"].transform("nunique"))
39
+ .loc[lambda x: x.team_count == 2]
40
+ .assign(
41
+ player_count=df.groupby(["gameid", "teamname"])["playername"].transform(
42
+ "nunique"
43
+ )
44
+ )
45
+ .loc[lambda x: x.player_count == 5]
46
+ )
47
+ df = df.assign(team_count=df.groupby("gameid")["teamname"].transform("nunique")).loc[
48
+ lambda x: x.team_count == 2
49
+ ]
50
+
51
+ df = df.drop_duplicates(subset=["gameid", "playername"])
52
+
53
+ # Pretends the last 10 games are future games. The most will be trained on everything before that.
54
+ most_recent_10_games = df[column_names.match_id].unique()[-10:]
55
+ historical_df = df[~df[column_names.match_id].isin(most_recent_10_games)]
56
+ future_df = df[df[column_names.match_id].isin(most_recent_10_games)].drop(
57
+ columns=["result"]
58
+ )
59
+
60
+ rating_generator_result = UpdateRatingGenerator(
61
+ features_out=[RatingKnownFeatures.RATING_DIFFERENCE_PROJECTED],
62
+ performance_column="result",
63
+ )
64
+
65
+ rating_generator_player_kills = UpdateRatingGenerator(
66
+ features_out=[RatingKnownFeatures.RATING_MEAN_PROJECTED],
67
+ performances_generator=PerformancesGenerator(
68
+ performances=Performance(
69
+ name="performance_kills",
70
+ weights=[
71
+ ColumnWeight(name="kills", weight=1),
72
+ ],
73
+ ),
74
+ ),
75
+ )
76
+
77
+ lag_generators = [
78
+ LagTransformer(
79
+ features=["kills", "deaths", "result"], lag_length=3, granularity=["playername"]
80
+ ),
81
+ RollingMeanTransformer(
82
+ features=["kills", "deaths", "result"],
83
+ window=20,
84
+ min_periods=1,
85
+ granularity=["playername"],
86
+ ),
87
+ ]
88
+
89
+ transformer = PipelineTransformer(
90
+ column_names=column_names,
91
+ rating_generators=[rating_generator_result, rating_generator_player_kills],
92
+ lag_transformers=lag_generators,
93
+ )
94
+
95
+ historical_df = transformer.fit_transform(historical_df)
96
+
97
+ game_winner_predictor = GameTeamPredictor(
98
+ predictor=SklearnPredictor(
99
+ estimator=LogisticRegression(),
100
+ target="result",
101
+ features=[RatingKnownFeatures.RATING_DIFFERENCE_PROJECTED],
102
+ ),
103
+ one_hot_encode_cat_features=True,
104
+ impute_missing_values=True,
105
+ game_id_colum=column_names.match_id,
106
+ team_id_column=column_names.team_id,
107
+ )
108
+
109
+ player_kills_predictor = SklearnPredictor(
110
+ estimator=LGBMRegressor(verbose=-100),
111
+ target="kills",
112
+ features=[game_winner_predictor.pred_column],
113
+ features_contain_str=["rolling_mean_kills", "lag_kills"],
114
+ )
115
+
116
+ cross_validator_game_winner = MatchKFoldCrossValidator(
117
+ date_column_name=column_names.start_date,
118
+ match_id_column_name=column_names.match_id,
119
+ predictor=game_winner_predictor,
120
+ )
121
+
122
+ game_winner_predictor.train(historical_df)
123
+ historical_df = cross_validator_game_winner.generate_validation_df(
124
+ historical_df, column_names
125
+ )
126
+
127
+ cross_validator_player_kills = MatchKFoldCrossValidator(
128
+ date_column_name=column_names.start_date,
129
+ match_id_column_name=column_names.match_id,
130
+ predictor=player_kills_predictor,
131
+ )
132
+
133
+ player_kills_predictor.train(historical_df)
134
+ print(player_kills_predictor.features)
135
+ historical_df = cross_validator_player_kills.generate_validation_df(
136
+ historical_df, column_names
137
+ )
138
+
139
+ future_df = transformer.transform(future_df)
140
+ future_df = game_winner_predictor.predict(future_df)
141
+ future_df = player_kills_predictor.predict(future_df)
142
+
143
+ probability_predictor = NegativeBinomialPredictor(
144
+ target="kills",
145
+ point_estimate_pred_column=player_kills_predictor.pred_column,
146
+ relative_error_predictor=SklearnPredictor(
147
+ estimator=LGBMRegressor(),
148
+ target=None,
149
+ features=["position"],
150
+ convert_cat_features_to_cat_dtype=True,
151
+ ),
152
+ max_value=15,
153
+ )
154
+
155
+ probability_predictor.train(historical_df)
156
+ future_df = probability_predictor.predict(future_df)
157
+
158
+ print(future_df.head(10))
File without changes