69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202 | class YahooFantasySportsQuery(object):
"""Yahoo Fantasy Sports REST API query CLASS to retrieve all types of fantasy sports data.
"""
YFO = TypeVar("YFO", bound=YahooFantasyObject)
runtime_environment_is_docker = os.environ.get("RUNTIME_ENVIRONMENT", None) == "docker"
def __init__(self,
league_id: str,
game_code: str,
game_id: Optional[int] = None,
yahoo_consumer_key: Optional[str] = None,
yahoo_consumer_secret: Optional[str] = None,
yahoo_access_token_json: Optional[Union[str, Dict]] = None,
env_var_fallback: bool = True,
env_file_location: Optional[Path] = None,
save_token_data_to_env_file: Optional[bool] = False,
all_output_as_json_str: bool = False,
browser_callback: bool = not runtime_environment_is_docker,
retries: int = 3,
backoff: int = 0,
offline: bool = False):
"""Instantiate a YahooQueryObject for running queries against the Yahoo fantasy REST API.
Args:
league_id (str): League ID of selected Yahoo Fantasy league.
game_code (str): Game code of selected Yahoo Fantasy game corresponding to a specific sport (refers to the
current season if used as the value for game_key), where "nfl" is for fantasy football, "nhl" is for
fantasy hockey, "mlb" is for fantasy baseball, and "nba" is for fantasy basketball.
game_id (:obj:`int`, optional): Game ID of selected Yahoo fantasy game corresponding to a specific year, and
defaulting to the game ID for the current year.
yahoo_consumer_key (:obj:`str`, optional): User defined Yahoo developer app consumer key (must be provided
in conjunction with yahoo_consumer_secret).
yahoo_consumer_secret (:obj:`str`, optional): User defined Yahoo developer app consumer secret (must be
provided in conjunction with yahoo_consumer_key).
yahoo_access_token_json (str | dict, optional): User defined JSON (string or dict) containing refreshable
access token generated by the yahoo-oauth library to avoid having to reauthenticate on every access to
the Yahoo Fantasy Sports API (overrides yahoo_consumer_key/yahoo_consumer_secret and all Yahoo access
token environment variables).
env_var_fallback (:obj:`bool`, optional): Fall back to values retrieved from environment variables for any
missing arguments or access token fields (defaults to True).
env_file_location (:obj:`Path`, optional): Path to directory where existing .env file is located or new .env
file should be generated when provided in conjunction with save_access_token_data_to_env_file=True
(defaults to None).
save_token_data_to_env_file (:obj:`bool`, optional): Boolean to save Yahoo access token data to local .env
file (must be provided in conjunction with env_file_location) (defaults to False)
all_output_as_json_str (:obj:`bool`, optional): Option to automatically convert all query output to JSON
strings.
browser_callback (:obj:`bool`, optional): Enable or disable (enabled by default) whether the yahoo-oauth
library automatically opens a browser window to authenticate (if disabled, it will output the callback
URL).
retries (:obj:`int`, optional): Number of times to retry a query if it fails (defaults to 3).
backoff (:obj:`int`, optional): Multiplier that incrementally increases the wait time before retrying a
failed query request.
offline (:obj:`bool`, optional): Boolean to run in offline mode (Only works if all needed Yahoo Fantasy data
has been previously saved locally using the Data module in data.py).
Attributes:
_env_var_fallback (bool): Fall back to values retrieved from environment variables for any missing
arguments or access token fields.
_yahoo_access_token_dict (dict[str, Any]): Dictionary containing refreshable access token data generated by
the yahoo-oauth library to avoid having to reauthenticate on every access to the Yahoo Fantasy Sports
API.
_yahoo_consumer_key (str): User defined Yahoo developer app consumer key.
_yahoo_consumer_secret (str): User defined Yahoo developer app consumer secret.
_browser_callback (bool): Enable or disable (enabled by default) whether the yahoo-oauth library
automatically opens a browser window to authenticate (if disabled, it will output the callback URL).
_retries (int): Number of times to retry a query if it fails (defaults to 3).
_backoff (int): Multiplier that incrementally increases the wait time before retrying a
failed query request.
_fantasy_content_data_field (str): The initial JSON field in which all Yahoo Fantasy Sports API responses
store the data output of the submitted query.
league_id (str): League ID of selected Yahoo Fantasy league.
game_code (str): Game code of selected Yahoo Fantasy game corresponding to a specific sport (refers to the
current season if used as the value for game_key), where "nfl" is for fantasy football, "nhl" is for
fantasy hockey, "mlb" is for fantasy baseball, and "nba" is for fantasy basketball.
game_id (int): Game ID of selected Yahoo fantasy game corresponding to a specific year, and
defaulting to the game ID for the current year.
league_key (str): The Yahoo Fantasy Sports league key formatted as <game_id>.l.<league_id>.
executed_queries (list[dict[str, Any]]): List of completed queries and their responses.
all_output_as_json_str (bool): Option to automatically convert all query output to JSON strings.
offline (bool): Boolean to run in offline mode (Only works if all needed Yahoo Fantasy data has been
previously saved locally using the Data module in data.py).
"""
self._env_var_fallback = env_var_fallback
# load provided .env file if it exists to read any additional environment variables stored there
if self._env_var_fallback and env_file_location:
env_file_path = env_file_location / ".env"
if env_file_path.is_file():
load_dotenv(env_file_path)
self._yahoo_access_token_dict: Dict[str, Any] = self._get_dict_from_access_token_json(yahoo_access_token_json)
# warn user that providing Yahoo access token JSON or populating a YAHOO_ACCESS_TOKEN_JSON environment variable
# will override any values provided in the yahoo_consumer_key and yahoo_consumer_secret parameters
if self._yahoo_access_token_dict and (yahoo_consumer_key or yahoo_consumer_secret):
logger.warning(
"Providing a yahoo_access_token_json argument or setting env_var_fallback to True and having a "
"YAHOO_ACCESS_TOKEN_JSON will override any values provided for yahoo_consumer_key or "
"yahoo_consumer_secret."
)
# retrieve the Yahoo consumer key and Yahoo consumer secret from the access token dict and fall back to the
# provided parameters if no dict exists
self._yahoo_consumer_key = self._yahoo_access_token_dict.get("consumer_key", yahoo_consumer_key)
self._yahoo_consumer_secret = self._yahoo_access_token_dict.get("consumer_secret", yahoo_consumer_secret)
# catch when a Yahoo consumer key was not provided
if not self._yahoo_consumer_key:
# check for YAHOO_CONSUMER_KEY environment variable value if env_var_fallback is True
if self._env_var_fallback:
if yahoo_consumer_key_env_var := os.environ.get("YAHOO_CONSUMER_KEY"):
self._yahoo_consumer_key = yahoo_consumer_key_env_var
if not self._yahoo_consumer_key:
logger.error(
"Missing required Yahoo consumer key (no yahoo_consumer_key argument provided to "
"YahooFantasySportsQuery, no consumer_key value provided in yahoo_access_token_json, or no "
"YAHOO_CONSUMER_KEY environment variable value found)."
)
sys.exit(1)
# catch when a Yahoo consumer secret was not provided
if not self._yahoo_consumer_secret:
# check for YAHOO_CONSUMER_SECRET environment variable value if env_var_fallback is True
if self._env_var_fallback:
if yahoo_consumer_secret_env_var := os.environ.get("YAHOO_CONSUMER_SECRET"):
self._yahoo_consumer_secret = yahoo_consumer_secret_env_var
if not self._yahoo_consumer_secret:
logger.error(
"Missing required Yahoo consumer secret (no yahoo_consumer_secret argument provided to "
"YahooFantasySportsQuery, no consumer_secret value provided in yahoo_access_token_json, or no "
"YAHOO_CONSUMER_SECRET environment variable value found)."
)
sys.exit(1)
# explicitly check for truthy/falsy value
self._browser_callback: bool = True if browser_callback is True else False
self._retries: int = retries
self._backoff: int = backoff
self._fantasy_content_data_field: str = "fantasy_content"
self.league_id: str = league_id
self.game_code: str = (
game_code if game_code in yahoo_fantasy_sports_game_codes else retrieve_game_code_from_user()
)
self.game_id: int = game_id
self.league_key: str = None
self.executed_queries: List[Dict[str, Any]] = []
# explicitly check for truthy/falsy value
self.all_output_as_json_str: bool = True if all_output_as_json_str is True else False
# explicitly check for truthy/falsy value
self.offline: bool = True if offline is True else False
if not self.offline:
self._authenticate()
if save_token_data_to_env_file:
self.save_access_token_data_to_env_file(env_file_location)
def _get_dict_from_access_token_json(self, yahoo_access_token_json: Union[str, Dict]) -> Dict[str, Any]:
"""Creates a dictionary of Yahoo access token fields extracted from provided JSON (or a provided dictionary).
Args:
yahoo_access_token_json (str | dict): A valid JSON string or Python dictionary containing Yahoo access token
fields and values.
Returns:
dict[str, Any]: A dictionary of key/value pairs containing the required values to authenticate using a Yahoo
access token.
"""
yahoo_access_token_dict: Dict[str, Any] = {}
# check if there is no provided token JSON and attempt to retrieve them from the YAHOO_ACCESS_TOKEN_JSON
# environment variable if fallback to environment variables is True
if not yahoo_access_token_json and self._env_var_fallback:
yahoo_access_token_json = os.environ.get("YAHOO_ACCESS_TOKEN_JSON")
if yahoo_access_token_json:
# parse Yahoo access token JSON as needed
if isinstance(yahoo_access_token_json, str):
try:
yahoo_access_token_dict = json.loads(yahoo_access_token_json)
except JSONDecodeError as e:
logger.error(f"Invalid JSON provided in yahoo_access_token_json:\n{e}")
sys.exit(1)
elif isinstance(yahoo_access_token_json, dict):
yahoo_access_token_dict = yahoo_access_token_json
else:
logger.error(
f"Invalid object type provided in yahoo_access_token_json or YAHOO_ACCESS_TOKEN_JSON environment "
f"variable: {type(yahoo_access_token_json)}"
)
sys.exit(1)
# check if any fields required by a Yahoo access token are missing
yahoo_access_token_required_fields = {
"access_token",
"consumer_key",
"consumer_secret",
"guid",
"refresh_token",
"token_time",
"token_type"
}
if not set(yahoo_access_token_dict.keys()).issuperset(yahoo_access_token_required_fields):
logger.error(
f"Missing required fields in yahoo_access_token_json: "
f"{yahoo_access_token_required_fields.difference(yahoo_access_token_dict.keys())}"
)
sys.exit(1)
return yahoo_access_token_dict
def _authenticate(self) -> None:
"""Authenticate with the Yahoo Fantasy Sports REST API using OAuth2.
Returns:
None
"""
logger.debug("Authenticating with Yahoo.")
# provide Yahoo access token fields if available or search for them in environment variables if env_var_fallback
# is True, and then complete OAuth2 3-legged handshake by either refreshing existing OAuth2 refresh token or
# requesting account access and returning a verification code to input to the command line prompt
self.oauth = OAuth2(
self._yahoo_consumer_key,
self._yahoo_consumer_secret,
access_token=self._yahoo_access_token_dict.get(
"access_token",
os.environ.get("YAHOO_ACCESS_TOKEN", None) if self._env_var_fallback else None
),
guid=self._yahoo_access_token_dict.get(
"guid",
os.environ.get("YAHOO_GUID", None) if self._env_var_fallback else None
),
refresh_token=self._yahoo_access_token_dict.get(
"refresh_token",
os.environ.get("YAHOO_REFRESH_TOKEN", None) if self._env_var_fallback else None
),
token_time=self._yahoo_access_token_dict.get(
"token_time",
float(os.environ.get("YAHOO_TOKEN_TIME", 0.0)) if self._env_var_fallback else 0.0
),
token_type=self._yahoo_access_token_dict.get(
"token_type",
os.environ.get("YAHOO_TOKEN_TYPE", None) if self._env_var_fallback else None
),
browser_callback=self._browser_callback,
store_file=False
)
if not self.oauth.token_is_valid():
self.oauth.refresh_access_token()
self._yahoo_access_token_dict.update(
{
"access_token": self.oauth.access_token,
"consumer_key": self.oauth.consumer_key,
"consumer_secret": self.oauth.consumer_secret,
"guid": self.oauth.guid,
"refresh_token": self.oauth.refresh_token,
"token_time": self.oauth.token_time,
"token_type": self.oauth.token_type,
}
)
@staticmethod
def _retrieve_env_file_contents(env_file_path: Path) -> Dict[str, str]:
"""Creates a dictionary of key/value pairs representing each line of a .env file (stores environment variables).
Args:
env_file_path (Path): The path to the directory where the target .env file is located.
Returns:
dict[str, str]: A dictionary of key/value pairs representing each line of a .env file.
"""
env_file_content = OrderedDict()
if env_file_path.is_file():
with open(env_file_path, "r") as env_file:
for line_num, env_file_line in enumerate(env_file, start=1):
if env_file_line.startswith("\n"):
# track blank lines in .env file using their line number
env_file_content[f"blank_{line_num}"] = "\n"
elif env_file_line.startswith("#"):
# track comments in .env file using their line number
env_file_content[f"comment_{line_num}"] = env_file_line.strip()
else:
# extract and normalize environment variables from .env file
env_var_name, env_var_value = env_file_line.split("=", 1)
env_file_content[env_var_name.lower()] = env_var_value.strip()
return env_file_content
def save_access_token_data_to_env_file(self, env_file_location: Path, env_file_name: str = ".env",
save_json_to_var_only: bool = False) -> None:
"""Saves the fields and values of a Yahoo access token into a .env file.
Args:
env_file_location (:obj:`Path`, optional): Path to directory where existing .env file is located or new .env
file should be generated.
env_file_name (:obj:`str`, optional): The name of the target .env file (defaults to ".env").
save_json_to_var_only (:obj:`bool`, optional): Boolean to determine whether or not to write a JSON string of
Yahoo access token fields to a YAHOO_ACCESS_TOKEN_JSON environment variable in the target .env file
instead of writing Yahoo access token fields to separate environment variables in the target .env file.
(defaults to False).
Returns:
None
"""
if env_file_location:
env_file_path = env_file_location / env_file_name
else:
logger.warning("Missing argument env_file_location. Yahoo access token will NOT be saved to .env file.")
# exit method without saving Yahoo access token data when no env_file_location argument is provided
return
env_file_content = self._retrieve_env_file_contents(env_file_path)
if save_json_to_var_only:
# generate a JSON string with escaped double quotes using nested json.dumps() and write it to a
# YAHOO_ACCESS_TOKEN_JSON environment variable if save_json_to_var_only is set to True instead of writing
# Yahoo access token fields to separate environment variables in target .env file
env_file_content["yahoo_access_token_json"] = json.dumps(json.dumps(self._yahoo_access_token_dict))
else:
# replace values of any matching environment variables in .env file with values from Yahoo access token
# fields or add new environment variables to .env file if any fields are missing
for k, v in self._yahoo_access_token_dict.items():
env_file_content[f"yahoo_{k}"] = v
# write contents to .env file (overwrites contents if file exists or creates a new file if not)
with open(env_file_path, "w") as env_file:
for k, v in env_file_content.items():
if k.startswith("blank"):
env_file.write(v)
elif k.startswith("comment"):
env_file.write(f"{v}\n")
else:
env_file.write(f"{k.upper()}={v}\n")
def get_response(self, url: str) -> Response:
"""Retrieve Yahoo Fantasy Sports data from the REST API.
Args:
url (str): REST API request URL string.
Returns:
Response: API response from Yahoo Fantasy Sports API request.
"""
logger.debug(f"Making request to URL: {url}")
response: Response = self.oauth.session.get(url, params={"format": "json"})
status_code = response.status_code
# when you exceed Yahoo's allowed data request limits, they throw a request status code of 999
if status_code == 999:
raise HTTPError("Yahoo data unavailable due to rate limiting. Please try again later.")
if status_code == 401:
self._authenticate()
response_json = {}
try:
response_json = response.json()
logger.debug(f"Response (JSON): {response_json}")
except JSONDecodeError:
response.raise_for_status()
try:
if (status_code // 100) != 2:
# handle if the yahoo query returns an error
if response_json.get("error"):
response_error_msg = response_json.get("error").get("description")
error_msg = f"Attempt to retrieve data at URL {response.url} failed with error: " \
f"\"{response_error_msg}\""
logger.error(error_msg)
raise YahooFantasySportsDataNotFound(error_msg, url=response.url)
response.raise_for_status()
except HTTPError as e:
# retry with incremental back-off
if self._retries > 0:
self._retries -= 1
self._backoff += 1
logger.warning(f"Request for URL {url} failed with status code {response.status_code}. "
f"Retrying {self._retries} more time{'s' if self._retries > 1 else ''}...")
time.sleep(0.3 * self._backoff)
response = self.get_response(url)
else:
# log error and terminate query if status code is not 200 after 3 retries
logger.error(f"Request failed with status code: {response.status_code} - {e}")
response.raise_for_status()
raw_response_data = response_json.get(self._fantasy_content_data_field)
# extract data from "fantasy_content" field if it exists
if raw_response_data:
logger.debug(f"Data fetched with query URL: {response.url}")
logger.debug(
f"Response (Yahoo fantasy data extracted from: "
f"\"{self._fantasy_content_data_field}\"): {raw_response_data}"
)
else:
error_msg = f"No data found at URL {response.url} when attempting extraction from field: " \
f"\"{self._fantasy_content_data_field}\""
logger.error(error_msg)
raise YahooFantasySportsDataNotFound(error_msg, url=response.url)
return response
# noinspection GrazieInspection
def query(self, url: str, data_key_list: Union[List[str], List[List[str]]], data_type_class: Type = None,
sort_function: Callable = None) -> (Union[str, YFO, List[YFO], Dict[str, YFO]]):
"""Base query class to retrieve requested data from the Yahoo fantasy sports REST API.
Args:
url (str): REST API request URL string.
data_key_list (list[str] | list[list[str]]): List of keys used to extract the specific data desired by the
given query (supports strings and lists of strings). Supports lists containing only key strings such as
["game", "stat_categories"], and also supports lists containing key strings followed by lists of key
strings such as ["team", ["team_points", "team_projected_points"]].
data_type_class (:obj:`Type`, optional): Highest level data model type (if one exists for the retrieved
data).
sort_function (Callable of sort function, optional)): Optional lambda function to return sorted query
results.
Returns:
object: Model class instance from yfpy/models.py, dictionary, or list (depending on query), with unpacked
and parsed response data.
"""
if not self.offline:
response = self.get_response(url)
raw_response_data = response.json().get(self._fantasy_content_data_field)
# print(json.dumps(raw_response_data, indent=2))
# iterate through list of data keys and drill down to final desired data field
for i in range(len(data_key_list)):
if isinstance(raw_response_data, list):
if isinstance(data_key_list[i], list):
reformatted = reformat_json_list(raw_response_data)
raw_response_data = [
{data_key_list[i][0]: reformatted[data_key_list[i][0]]},
{data_key_list[i][1]: reformatted[data_key_list[i][1]]}
]
else:
raw_response_data = reformat_json_list(raw_response_data)[data_key_list[i]]
else:
if isinstance(data_key_list[i], list):
raw_response_data = [
{data_key_list[i][0]: raw_response_data[data_key_list[i][0]]},
{data_key_list[i][1]: raw_response_data[data_key_list[i][1]]}
]
else:
raw_response_data = raw_response_data.get(data_key_list[i])
if raw_response_data:
logger.debug(f"Response (Yahoo fantasy data extracted from: {data_key_list}): {raw_response_data}")
else:
error_msg = f"No data found when attempting extraction from fields: {data_key_list}"
logger.error(error_msg)
raise YahooFantasySportsDataNotFound(error_msg, payload=data_key_list, url=response.url)
# unpack, parse, and assign data types to all retrieved data content
unpacked = unpack_data(raw_response_data, YahooFantasyObject)
logger.debug(
f"Unpacked and parsed JSON (Yahoo fantasy data wth parent type: {data_type_class}):\n{unpacked}")
self.executed_queries.append({
"url": response.url,
"response_status_code": response.status_code,
"response": response
})
# cast the highest level of data to type corresponding to query (if type exists)
query_data = data_type_class(unpacked) if data_type_class else unpacked
# sort data when applicable
if sort_function and not isinstance(query_data, dict):
query_data = sorted(query_data, key=sort_function)
# flatten lists of single-key dicts of objects into lists of those objects
if isinstance(query_data, list):
last_data_key = data_key_list[-1]
if last_data_key.endswith("s"):
query_data = [el[last_data_key[:-1]] for el in query_data]
if self.all_output_as_json_str:
return jsonify_data(query_data)
else:
return query_data
else:
logger.error("Cannot run Yahoo query while using offline mode! Please try again with offline=False.")
def get_all_yahoo_fantasy_game_keys(self) -> List[Game]:
"""Retrieve all Yahoo Fantasy Sports game keys by ID (from year of inception to present), sorted by season/year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_all_yahoo_fantasy_game_keys()
[
Game({
"code": "nfl",
"game_id": "50",
"game_key": "50",
"is_game_over": 1,
"is_offseason": 1,
"is_registration_over": 1,
"name": "Football",
"season": "1999",
"type": "full",
"url": "https://football.fantasysports.yahoo.com/archive/nfl/1999"
}),
...,
Game({...})
]
Returns:
list[Game]: List of YFPY Game instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/games;game_codes={self.game_code}",
["games"],
sort_function=lambda x: x.get("game").season
)
# noinspection PyUnresolvedReferences
def get_game_key_by_season(self, season: int) -> str:
"""Retrieve specific game key by season.
Args:
season (int): User defined season/year for which to retrieve the Yahoo Fantasy Sports game.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_game_key_by_season(2021)
338
Returns:
str: The game key for a Yahoo Fantasy Sports game specified by season.
"""
all_output_as_json = False
if self.all_output_as_json_str:
self.all_output_as_json_str = False
all_output_as_json = True
game_key = self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/games;game_codes={self.game_code};seasons={season}",
["games"]
).get("game").game_key
if all_output_as_json:
self.all_output_as_json_str = True
return game_key
def get_current_game_info(self) -> Game:
"""Retrieve game info for current fantasy season.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_current_game_info()
Game({
"code": "nfl",
"game_id": "390",
"game_key": "390",
"game_weeks": [
{
"game_week": {
"display_name": "1",
"end": "2019-09-09",
"start": "2019-09-05",
"week": "1"
}
},
...
],
"is_game_over": 0,
"is_live_draft_lobby_active": 1,
"is_offseason": 0,
"is_registration_over": 0,
"name": "Football",
"position_types": [
{
"position_type": {
"type": "O",
"display_name": "Offense"
}
},
...
],
"roster_positions": [
{
"roster_position": {
"position": "QB",
"position_type": "O"
}
},
...
],
"season": "2019",
"stat_categories": {
"stats": [
{
"stat": {
"display_name": "GP",
"name": "Games Played",
"sort_order": "1",
"stat_id": 0
}
},
...
},
"type": "full",
"url": "https://football.fantasysports.yahoo.com/f1"
})
Returns:
Game: YFPY Game instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/game/{self.game_code};"
f"out=metadata,players,game_weeks,stat_categories,position_types,roster_positions",
["game"],
Game
)
def get_current_game_metadata(self) -> Game:
"""Retrieve game metadata for current fantasy season.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_current_game_metadata()
Game({
"code": "nfl",
"game_id": "390",
"game_key": "390",
"is_game_over": 0,
"is_live_draft_lobby_active": 1,
"is_offseason": 0,
"is_registration_over": 0,
"name": "Football",
"season": "2019",
"type": "full",
"url": "https://football.fantasysports.yahoo.com/f1"
})
Returns:
Game: YFPY Game instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/game/{self.game_code}/metadata",
["game"],
Game
)
def get_game_info_by_game_id(self, game_id: int) -> Game:
"""Retrieve game info for specific game by ID.
Args:
game_id (int): Game ID of selected Yahoo Fantasy game corresponding to a specific year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_game_info_by_game_id(390)
Game({
"code": "nfl",
"game_id": "390",
"game_key": "390",
"game_weeks": [
{
"game_week": {
"display_name": "1",
"end": "2019-09-09",
"start": "2019-09-05",
"week": "1"
}
},
...
],
"is_game_over": 0,
"is_live_draft_lobby_active": 1,
"is_offseason": 0,
"is_registration_over": 0,
"name": "Football",
"position_types": [
{
"position_type": {
"type": "O",
"display_name": "Offense"
}
},
...
],
"roster_positions": [
{
"roster_position": {
"position": "QB",
"position_type": "O"
}
},
...
],
"season": "2019",
"stat_categories": {
"stats": [
{
"stat": {
"display_name": "GP",
"name": "Games Played",
"sort_order": "1",
"stat_id": 0
}
},
...
},
"type": "full",
"url": "https://football.fantasysports.yahoo.com/f1"
})
Returns:
Game: YFPY Game instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/game/{game_id};"
f"out=metadata,players,game_weeks,stat_categories,position_types,roster_positions",
["game"],
Game
)
def get_game_metadata_by_game_id(self, game_id: int) -> Game:
"""Retrieve game metadata for specific game by ID.
Args:
game_id (int): Game ID of selected Yahoo Fantasy game corresponding to a specific year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_game_metadata_by_game_id(331)
Game({
"code": "nfl",
"game_id": "331",
"game_key": "331",
"is_game_over": 1,
"is_offseason": 1,
"is_registration_over": 1,
"name": "Football",
"season": "2014",
"type": "full",
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2014"
})
Returns:
Game: YFPY Game instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/game/{game_id}/metadata",
["game"],
Game
)
def get_game_weeks_by_game_id(self, game_id: int) -> List[GameWeek]:
"""Retrieve all valid weeks of a specific game by ID.
Args:
game_id (int): Game ID of selected Yahoo Fantasy game corresponding to a specific year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_game_weeks_by_game_id(331)
[
GameWeek({
"display_name": "1",
"end": "2014-09-08",
"start": "2014-09-04",
"week": "1"
}),
...,
GameWeek({
"display_name": "17",
"end": "2014-12-28",
"start": "2014-12-23",
"week": "17"
})
]
Returns:
list[GameWeek]: List of YFPY GameWeek instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/game/{game_id}/game_weeks",
["game", "game_weeks"]
)
def get_game_stat_categories_by_game_id(self, game_id: int) -> StatCategories:
"""Retrieve all valid stat categories of a specific game by ID.
Args:
game_id (int): Game ID of selected Yahoo Fantasy game corresponding to a specific year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_game_stat_categories_by_game_id(331)
StatCategories({
"stats": [
{
"stat": {
"display_name": "GP",
"name": "Games Played",
"sort_order": "1",
"stat_id": 0
}
},
...,
{
"stat": {
"display_name": "Rush 1st Downs",
"name": "Rushing 1st Downs",
"sort_order": "1",
"stat_id": 81
}
}
]
})
Returns:
StatCategories: YFPY StatCategories instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/game/{game_id}/stat_categories",
["game", "stat_categories"],
StatCategories
)
def get_game_position_types_by_game_id(self, game_id: int) -> List[PositionType]:
"""Retrieve all valid position types for specific game by ID sorted alphabetically by type.
Args:
game_id (int): Game ID of selected Yahoo Fantasy game corresponding to a specific year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_game_position_types_by_game_id(331)
[
PositionType({
"type": "O",
"display_name": "Offense"
}),
...,
PositionType({
"type": "K",
"display_name": "Kickers"
})
]
Returns:
list[PositionType]: List of YFPY PositionType instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/game/{game_id}/position_types",
["game", "position_types"],
sort_function=lambda x: x.get("position_type").type
)
def get_game_roster_positions_by_game_id(self, game_id: int) -> List[RosterPosition]:
"""Retrieve all valid roster positions for specific game by ID sorted alphabetically by position.
Args:
game_id (int): Game ID of selected Yahoo Fantasy game corresponding to a specific year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_game_roster_positions_by_game_id(331)
[
{RosterPosition({
"position": "BN"
}),
...,
RosterPosition({
"position": "WR",
"position_type": "O"
})
]
Returns:
list[RosterPosition]: List of YFPY RosterPosition instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/game/{game_id}/roster_positions",
["game", "roster_positions"],
sort_function=lambda x: x.get("roster_position").position
)
def get_league_key(self, season: int = None) -> str:
"""Retrieve league key for selected league.
Args:
season (int): User defined season/year for which to retrieve the Yahoo Fantasy Sports league key.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_key(2021)
331.l.729259
Returns:
str: League key string for selected league.
"""
if not self.league_key:
if season:
return f"{self.get_game_key_by_season(season)}.l.{self.league_id}"
elif self.game_id:
return f"{self.get_game_metadata_by_game_id(self.game_id).game_key}.l.{self.league_id}"
else:
logger.warning(
"No game id or season/year provided, defaulting to current fantasy season.")
return f"{self.get_current_game_metadata().game_key}.l.{self.league_id}"
else:
return self.league_key
def get_current_user(self) -> User:
"""Retrieve metadata for current logged-in user.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_current_user()
User({
"guid": "USER_GUID_STRING"
})
Returns:
User: YFPY User instance.
"""
return self.query(
"https://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/",
["users", "0", "user"],
User
)
def get_user_games(self) -> List[Game]:
"""Retrieve game history for current logged-in user sorted by season/year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_user_games()
[
Game({
"code": "nfl",
"game_id": "359",
"game_key": "359",
"is_game_over": 1,
"is_offseason": 1,
"is_registration_over": 1,
"name": "Football",
"season": "2016",
"type": "full",
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2016"
})
...,
Game({...})
]
Returns:
list[Game]: List of YFPY Game instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;codes={self.game_code}/",
["users", "0", "user", "games"],
sort_function=lambda x: x.get("game").season
)
def get_user_leagues_by_game_key(self, game_key: Union[int, str]) -> List[League]:
"""Retrieve league history for current logged-in user for specific game by game IDs/keys sorted by season/year.
Args:
game_key (int | str): The game_id (int) or game_key (str) for a specific Yahoo Fantasy game.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_user_leagues_by_game_key(331)
[
League({
"allow_add_to_dl_extra_pos": 0,
"current_week": "16",
"draft_status": "postdraft",
"edit_key": "16",
"end_date": "2018-12-24",
"end_week": "16",
"game_code": "nfl",
"iris_group_chat_id": "<group chat id>",
"is_cash_league": "0",
"is_finished": 1,
"is_pro_league": "0",
"league_id": "169896",
"league_key": "380.l.169896",
"league_type": "private",
"league_update_timestamp": "1546498723",
"logo_url": "<logo url>",
"name": "League Name",
"num_teams": 12,
"password": null,
"renew": "371_52364",
"renewed": "390_78725",
"scoring_type": "head",
"season": "2018",
"short_invitation_url": "<invite url>",
"start_date": "2018-09-06",
"start_week": "1",
"url": "<league url>",
"weekly_deadline": null
}),
...,
League({...})
]
Returns:
list[League]: List of YFPY League instances.
"""
leagues = self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;game_keys={game_key}/leagues/",
["users", "0", "user", "games", "0", "game", "leagues"],
sort_function=lambda x: x.get("league").season
)
return leagues if isinstance(leagues, list) else [leagues.get("league")]
def get_user_teams(self) -> List[Game]:
"""Retrieve teams for all leagues for current logged-in user for current game sorted by season/year.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_user_teams()
[
Game({
"code": "nfl",
"game_id": "359",
"game_key": "359",
"is_game_over": 1,
"is_offseason": 1,
"is_registration_over": 1,
"name": "Football",
"season": "2016",
"teams": [
{
"team": {
"draft_grade": "A",
"draft_position": 9,
"draft_recap_url": "<draft recap url>",
"has_draft_grade": 1,
"league_scoring_type": "head",
"managers": [
{
"manager": {
"email": "<manager email>",
"guid": "<manager user guid>",
"image_url": "<manager user image url>",
"is_comanager": "1",
"manager_id": "14",
"nickname": "<manager nickname>"
}
}
],
"name": "Legion",
"number_of_moves": "48",
"number_of_trades": "2",
"roster_adds": {
"coverage_type": "week",
"coverage_value": "17",
"value": "0"
},
"team_id": "1",
"team_key": "359.l.5521.t.1",
"team_logos": {
"team_logo": {
"size": "large",
"url": "<logo url>"
}
},
"url": "<team url>",
"waiver_priority": 11
}
}
],
"type": "full",
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2016"
})
...,
Game({...})
]
Returns:
list[Game]: List of YFPY Game instances with "teams" attribute containing list of YFPY Team instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;codes={self.game_code}/teams/",
["users", "0", "user", "games"],
sort_function=lambda x: x.get("game").season
)
def get_league_info(self) -> League:
"""Retrieve info for chosen league.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_info()
League({
"allow_add_to_dl_extra_pos": 0,
"current_week": "16",
"draft_status": "postdraft",
"edit_key": "16",
"end_date": "2014-12-22",
"end_week": "16",
"game_code": "nfl",
"iris_group_chat_id": null,
"is_cash_league": "0",
"is_finished": 1,
"is_pro_league": "1",
"league_id": "729259",
"league_key": "331.l.729259",
"league_type": "public",
"league_update_timestamp": "1420099793",
"logo_url": "https://s.yimg.com/cv/api/default/20180206/default-league-logo@2x.png",
"name": "Yahoo Public 729259",
"num_teams": 10,
"renew": null,
"renewed": null,
"scoreboard": {
"week": "16",
"matchups": [
...
]
},
"scoring_type": "head",
"season": "2014",
"settings": {
...
},
"standings": {
"teams": [
...,
...
],
...
},
"start_date": "2014-09-04",
"start_week": "1",
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259",
"weekly_deadline": null
})
Returns:
League: YFPY League instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()};"
f"out=metadata,settings,standings,scoreboard,teams,players,draftresults,transactions",
["league"],
League
)
def get_league_metadata(self) -> League:
"""Retrieve metadata for chosen league.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_metadata()
League({
"allow_add_to_dl_extra_pos": 0,
"current_week": "16",
"draft_status": "postdraft",
"edit_key": "16",
"end_date": "2014-12-22",
"end_week": "16",
"game_code": "nfl",
"iris_group_chat_id": null,
"is_cash_league": "0",
"is_finished": 1,
"is_pro_league": "1",
"league_id": "729259",
"league_key": "331.l.729259",
"league_type": "public",
"league_update_timestamp": "1420099793",
"logo_url": "https://s.yimg.com/cv/api/default/20180206/default-league-logo@2x.png",
"name": "Yahoo Public 729259",
"num_teams": 10,
"renew": null,
"renewed": null,
"scoring_type": "head",
"season": "2014",
"start_date": "2014-09-04",
"start_week": "1",
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259",
"weekly_deadline": null
})
Returns:
League: YFPY League instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/metadata",
["league"],
League
)
def get_league_settings(self) -> Settings:
"""Retrieve settings (rules) for chosen league.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_settings()
Settings({
"cant_cut_list": "yahoo",
"draft_time": "1408410000",
"draft_type": "live",
"has_multiweek_championship": 0,
"has_playoff_consolation_games": true,
"is_auction_draft": "0",
"max_teams": "10",
"num_playoff_consolation_teams": 4,
"num_playoff_teams": "4",
"pickem_enabled": "1",
"player_pool": "ALL",
"playoff_start_week": "15",
"post_draft_players": "W",
"roster_positions": [
{
"roster_position": {
"count": 1,
"position": "QB",
"position_type": "O"
}
},
...
],
"scoring_type": "head",
"stat_categories": {
"stats": [
{
"stat": {
"display_name": "Pass Yds",
"enabled": "1",
"name": "Passing Yards",
"position_type": "O",
"sort_order": "1",
"stat_id": 4,
"stat_position_types": {
"stat_position_type": {
"position_type": "O"
}
}
}
},
...
]
},
"stat_modifiers": {
"stats": [
{
"stat": {
"stat_id": 4,
"value": "0.04"
}
},
...
]
},
"trade_end_date": "2014-11-14",
"trade_ratify_type": "yahoo",
"trade_reject_time": "2",
"uses_faab": "0",
"uses_fractional_points": "1",
"uses_lock_eliminated_teams": 1,
"uses_negative_points": "1",
"uses_playoff": "1",
"uses_playoff_reseeding": 0,
"waiver_rule": "gametime",
"waiver_time": "2",
"waiver_type": "R"
})
Returns:
Settings: YFPY Settings instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/settings",
["league", "settings"],
Settings
)
def get_league_standings(self) -> Standings:
"""Retrieve standings for chosen league.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_standings()
Standings({
"teams": [
{
"team": {
"clinched_playoffs": 1,
"draft_grade": "C+",
"draft_position": 7,
"draft_recap_url":
"https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/8/draftrecap",
"has_draft_grade": 1,
"league_scoring_type": "head",
"managers": {
"manager": {
"guid": "PMTCFWSK5U5LI4SKWREUR56B5A",
"manager_id": "8",
"nickname": "--hidden--"
}
},
"name": "clam dam",
"number_of_moves": "27",
"number_of_trades": 0,
"roster_adds": {
"coverage_type": "week",
"coverage_value": "17",
"value": "0"
},
"team_id": "8",
"team_key": "331.l.729259.t.8",
"team_logos": {
"team_logo": {
"size": "large",
"url": "https://s.yimg.com/cv/apiv2/default/nfl/nfl_1.png"
}
},
"team_points": {
"coverage_type": "season",
"season": "2014",
"total": "1507.06"
},
"team_standings": {
"outcome_totals": {
"losses": 2,
"percentage": 0.857,
"ties": 0,
"wins": 12
},
"playoff_seed": "1",
"points_against": 1263.78,
"points_for": 1507.06,
"rank": 1,
"streak": {
"type": "win",
"value": "2"
}
},
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/8",
"waiver_priority": 10
}
},
...
]
})
Returns:
Standings: YFPY Standings instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/standings",
["league", "standings"],
Standings
)
def get_league_teams(self) -> List[Team]:
"""Retrieve teams for chosen league.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_teams()
[
Team({
"clinched_playoffs": 1,
"draft_grade": "B",
"draft_position": 4,
"draft_recap_url":
"https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/1/draftrecap",
"has_draft_grade": 1,
"league_scoring_type": "head",
"managers": {
"manager": {
"guid": "BMACD7S5UXV7JIQX4PGGUVQJAU",
"manager_id": "1",
"nickname": "--hidden--"
}
},
"name": "Hellacious Hill 12",
"number_of_moves": "71",
"number_of_trades": 0,
"roster_adds": {
"coverage_type": "week",
"coverage_value": "17",
"value": "0"
},
"team_id": "1",
"team_key": "331.l.729259.t.1",
"team_logos": {
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/1441/24935131299_a8242dab70_192sq.jpg?ct=fantasy"
}
},
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/1",
"waiver_priority": 9
}),
...,
Team({...})
]
Returns:
list[Team]: List of YFPY Team instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/teams",
["league", "teams"]
)
def get_league_players(self, player_count_limit: int = None, player_count_start: int = 0,
is_retry: bool = False) -> List[Player]:
"""Retrieve valid players for chosen league.
Args:
player_count_limit (int): Maximum number of players to retreive.
player_count_start (int): Index from which to retrieve all subsequent players.
is_retry (bool): Boolean to indicate whether the method is being retried during error handling.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_players(50, 25)
[
Player({
"bye_weeks": {
"week": "10"
},
"display_position": "K",
"editorial_player_key": "nfl.p.3727",
"editorial_team_abbr": "Ind",
"editorial_team_full_name": "Indianapolis Colts",
"editorial_team_key": "nfl.t.11",
"eligible_positions": {
"position": "K"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url":
"https://s.yimg.com/iu/api/res/1.2/OpHvpCHjl_PQvkeQUgsjsA--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt
3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08152019/3727.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Adam",
"ascii_last": "Vinatieri",
"first": "Adam",
"full": "Adam Vinatieri",
"last": "Vinatieri"
},
"player_id": "3727",
"player_key": "331.p.3727",
"player_notes_last_timestamp": 1568758320,
"position_type": "K",
"primary_position": "K",
"uniform_number": "4"
}),
...,
Player({...})
]
Returns:
list[Player]: List of YFPY Player instances.
"""
league_player_count = player_count_start
all_players_retrieved = False
league_player_data = []
league_player_retrieval_limit = 25
while not all_players_retrieved:
try:
league_player_query_data = self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/players;"
f"start={league_player_count};count={league_player_retrieval_limit if not is_retry else 1}",
["league", "players"]
)
league_players = (league_player_query_data if isinstance(league_player_query_data, list) else
[league_player_query_data])
league_player_count_from_query = len(league_players)
if player_count_limit:
if (league_player_count + league_player_count_from_query) < player_count_limit:
league_player_count += league_player_count_from_query
league_player_data.extend(league_players)
else:
for ndx in range(player_count_limit - league_player_count):
league_player_data.append(league_players[ndx])
league_player_count += (player_count_limit - league_player_count)
all_players_retrieved = True
else:
league_player_count += league_player_count_from_query
league_player_data.extend(league_players)
except YahooFantasySportsDataNotFound as yfpy_err:
if not is_retry:
payload = yfpy_err.payload
if payload:
logger.debug("No more league player data available.")
all_players_retrieved = True
else:
logger.warning(
f"Error retrieving player batch: "
f"{league_player_count}-{league_player_count + league_player_retrieval_limit - 1}. "
f"Attempting to retrieve individual players from batch.")
player_retrieval_successes = []
player_retrieval_failures = []
for i in range(25):
try:
player_data = self.get_league_players(
player_count_limit=league_player_count + 1,
player_count_start=league_player_count,
is_retry=True
)
player_retrieval_successes.extend(player_data)
except YahooFantasySportsDataNotFound as nested_yfpy_err:
player_retrieval_failures.append(
{
"failed_player_retrieval_index": league_player_count,
"failed_player_retrieval_url": nested_yfpy_err.url,
"failed_player_retrieval_message": nested_yfpy_err.message
}
)
league_player_count += 1
league_player_data.extend(player_retrieval_successes)
logger.warning(f"Players retrieval failures:\n{prettify_data(player_retrieval_failures)}")
else:
raise yfpy_err
logger.debug(f"League player count: {league_player_count}")
return league_player_data
def get_league_draft_results(self) -> List[DraftResult]:
"""Retrieve draft results for chosen league.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_draft_results()
[
DraftResult({
"pick": 1,
"round": 1,
"team_key": "331.l.729259.t.4",
"player_key": "331.p.9317"
}),
...,
DraftResult({...})
]
Returns:
list[DraftResult]: List of YFPY DraftResult instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/draftresults",
["league", "draft_results"]
)
def get_league_transactions(self) -> List[Transaction]:
"""Retrieve transactions for chosen league.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_transactions()
[
Transaction({
"players": [
{
"player": {
"display_position": "RB",
"editorial_team_abbr": "NO",
"name": {
"ascii_first": "Kerwynn",
"ascii_last": "Williams",
"first": "Kerwynn",
"full": "Kerwynn Williams",
"last": "Williams"
},
"player_id": "26853",
"player_key": "331.p.26853",
"position_type": "O",
"transaction_data": {
"destination_team_key": "331.l.729259.t.1",
"destination_team_name": "Hellacious Hill 12",
"destination_type": "team",
"source_type": "freeagents",
"type": "add"
}
}
}
],
"status": "successful",
"timestamp": "1419188151",
"transaction_id": "282",
"transaction_key": "331.l.729259.tr.282",
"type": "add/drop"
}),
...,
Transaction({...})
]
Returns:
list[Transaction]: List of YFPY Transaction instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/transactions",
["league", "transactions"]
)
def get_league_scoreboard_by_week(self, chosen_week: int) -> Scoreboard:
"""Retrieve scoreboard for chosen league by week.
Args:
chosen_week (int): Selected week for which to retrieve data.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_scoreboard_by_week(1)
Scoreboard({
"week": "1",
"matchups": [
{
"matchup": {
"is_consolation": "0",
"is_matchup_recap_available": 1,
"is_playoffs": "0",
"is_tied": 0,
"matchup_grades": [
{
"matchup_grade": {
"grade": "B",
"team_key": "331.l.729259.t.1"
}
},
{
"matchup_grade": {
"grade": "B",
"team_key": "331.l.729259.t.2"
}
}
],
"matchup_recap_title": "Wax On Wax Off Gets Victory Against Hellacious Hill 12",
"matchup_recap_url":
"https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/recap?
week=1&mid1=1&mid2=2",
"status": "postevent",
"teams": [
{
"team": {
<team data>
}
},
{
"team": {
<team data>
}
}
],
"week": "1",
"week_end": "2014-09-08",
"week_start": "2014-09-04",
"winner_team_key": "331.l.729259.t.2"
}
},
...
]
})
Returns:
Scoreboard: YFPY Scoreboard instance.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/scoreboard;"
f"week={chosen_week}",
["league", "scoreboard"],
Scoreboard
)
def get_league_matchups_by_week(self, chosen_week: int) -> List[Matchup]:
"""Retrieve matchups for chosen league by week.
Args:
chosen_week (int): Selected week for which to retrieve data.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_league_matchups_by_week(1)
[
Matchup({
"is_consolation": "0",
"is_matchup_recap_available": 1,
"is_playoffs": "0",
"is_tied": 0,
"matchup_grades": [
{
"matchup_grade": {
"grade": "B",
"team_key": "331.l.729259.t.1"
}
},
{
"matchup_grade": {
"grade": "B",
"team_key": "331.l.729259.t.2"
}
}
],
"matchup_recap_title": "Wax On Wax Off Gets Victory Against Hellacious Hill 12",
"matchup_recap_url":
"https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/recap?
week=1&mid1=1&mid2=2",
"status": "postevent",
"teams": [
{
"team": {
<team data>
}
},
{
"team": {
<team data>
}
}
],
"week": "1",
"week_end": "2014-09-08",
"week_start": "2014-09-04",
"winner_team_key": "331.l.729259.t.2"
}),
...,
Matchup({...})
]
Returns:
list[Matchup]: List of YFPY Matchup instances.
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/scoreboard;"
f"week={chosen_week}",
["league", "scoreboard", "0", "matchups"]
)
def get_team_info(self, team_id: Union[str, int]) -> Team:
"""Retrieve info of specific team by team_id for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_info(1)
Team({
"clinched_playoffs": 1,
"draft_grade": "B",
"draft_position": 4,
"draft_recap_url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/1/draftrecap",
"draft_results": [
...
],
"has_draft_grade": 1,
"league_scoring_type": "head",
"managers": {
"manager": {
"guid": "BMACD7S5UXV7JIQX4PGGUVQJAU",
"manager_id": "1",
"nickname": "--hidden--"
}
},
"matchups": [
...
],
"name": "Hellacious Hill 12",
"number_of_moves": "71",
"number_of_trades": 0,
"roster": {
...
},
"roster_adds": {
"coverage_type": "week",
"coverage_value": "17",
"value": "0"
},
"team_id": "1",
"team_key": "331.l.729259.t.1",
"team_logos": {
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/1441/24935131299_a8242dab70_192sq.jpg?ct=fantasy"
}
},
"team_points": {
"coverage_type": "season",
"season": "2014",
"total": "1409.24"
},
"team_standings": {
"outcome_totals": {
"losses": 5,
"percentage": 0.643,
"ties": 0,
"wins": 9
},
"playoff_seed": "2",
"points_against": 1266.6599999999999,
"points_for": 1409.24,
"rank": 2,
"streak": {
"type": "win",
"value": "1"
}
},
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/1",
"waiver_priority": 9
})
Returns:
Team: YFPY Team instance.
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key};"
f"out=metadata,stats,standings,roster,draftresults,matchups",
["team"],
Team
)
def get_team_metadata(self, team_id: Union[str, int]) -> Team:
"""Retrieve metadata of specific team by team_id for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_metadata(1)
Team({
"team_key": "331.l.729259.t.1",
"team_id": "1",
"name": "Hellacious Hill 12",
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/1",
"team_logos": {
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/1441/24935131299_a8242dab70_192sq.jpg?ct=fantasy"
}
},
"waiver_priority": 9,
"number_of_moves": "71",
"number_of_trades": 0,
"roster_adds": {
"coverage_type": "week",
"coverage_value": "17",
"value": "0"
},
"clinched_playoffs": 1,
"league_scoring_type": "head",
"draft_position": 4,
"has_draft_grade": 1,
"draft_grade": "B",
"draft_recap_url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/1/draftrecap",
"managers": {
"manager": {
"guid": "BMACD7S5UXV7JIQX4PGGUVQJAU",
"manager_id": "1",
"nickname": "--hidden--"
}
}
})
Returns:
Team: YFPY Team instance.
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/metadata",
["team"],
Team
)
def get_team_stats(self, team_id: Union[str, int]) -> TeamPoints:
"""Retrieve stats of specific team by team_id for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_stats(1)
TeamPoints({
"coverage_type": "season",
"season": "2014",
"total": "1409.24"
})
Returns:
TeamPoints: YFPY TeamPoints instance.
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/stats",
["team", "team_points"],
TeamPoints
)
def get_team_stats_by_week(
self, team_id: Union[str, int], chosen_week: Union[int, str] = "current"
) -> Dict[str, Union[TeamPoints, TeamProjectedPoints]]:
"""Retrieve stats of specific team by team_id and by week for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
chosen_week (int): Selected week for which to retrieve data.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_stats_by_week(1, 1)
{
"team_points": TeamPoints({
"coverage_type": "week",
"total": "95.06",
"week": "1"
}),
"team_projected_points": TeamProjectedPoints({
"coverage_type": "week",
"total": "78.85",
"week": "1"
})
}
Returns:
dict[str, TeamPoints | TeamProjectedPoints]: Dictionary containing keys "team_points" and
"team_projected_points" with respective values YFPY TeamPoints and YFPY TeamProjectedPoints instances.
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/stats;type=week;week={chosen_week}",
["team", ["team_points", "team_projected_points"]]
)
def get_team_standings(self, team_id: Union[str, int]) -> TeamStandings:
"""Retrieve standings of specific team by team_id for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_standings(1)
TeamStandings({
"rank": 2,
"playoff_seed": "2",
"outcome_totals": {
"losses": 5,
"percentage": 0.643,
"ties": 0,
"wins": 9
},
"streak": {
"type": "win",
"value": "1"
},
"points_for": "1409.24",
"points_against": 1266.6599999999999
})
Returns:
TeamStandings: YFPY TeamStandings instance.
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/standings",
["team", "team_standings"],
TeamStandings
)
def get_team_roster_by_week(self, team_id: Union[str, int], chosen_week: Union[int, str] = "current") -> Roster:
"""Retrieve roster of specific team by team_id and by week for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
chosen_week (int): Selected week for which to retrieve data.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_roster_by_week(1, 1)
Roster({
"coverage_type": "week",
"week": "1",
"is_editable": 0,
"players": [
{
"player": {
"bye_weeks": {
"week": "10"
},
"display_position": "QB",
"editorial_player_key": "nfl.p.5228",
"editorial_team_abbr": "NE",
"editorial_team_full_name": "New England Patriots",
"editorial_team_key": "nfl.t.17",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/_U9UJlrYMsJ22DpA..S3zg--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt
3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08212019/5228.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Tom",
"ascii_last": "Brady",
"first": "Tom",
"full": "Tom Brady",
"last": "Brady"
},
"player_id": "5228",
"player_key": "331.p.5228",
"player_notes_last_timestamp": 1568837880,
"position_type": "O",
"primary_position": "QB",
"selected_position": {
"coverage_type": "week",
"is_flex": 0,
"position": "QB",
"week": "1"
},
"uniform_number": "12"
}
},
...
]
})
Returns:
Roster: YFPY Roster instance.
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/roster;week={chosen_week}",
["team", "roster"],
Roster
)
def get_team_roster_player_info_by_week(self, team_id: Union[str, int],
chosen_week: Union[int, str] = "current") -> List[Player]:
"""Retrieve roster with ALL player info of specific team by team_id and by week for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
chosen_week (int): Selected week for which to retrieve data.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_roster_player_info_by_week(1, 1)
[
Player({
"bye_weeks": {
"week": "10"
},
"display_position": "QB",
"draft_analysis": {
"average_pick": "65.9",
"average_round": "7.6",
"average_cost": "5.0",
"percent_drafted": "1.00"
},
"editorial_player_key": "nfl.p.5228",
"editorial_team_abbr": "NE",
"editorial_team_full_name": "New England Patriots",
"editorial_team_key": "nfl.t.17",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/_U9UJlrYMsJ22DpA..S3zg--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/
https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08212019/5228.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Tom",
"ascii_last": "Brady",
"first": "Tom",
"full": "Tom Brady",
"last": "Brady"
},
"ownership": {
"ownership_type": "team",
"owner_team_key": "331.l.729259.t.1",
"owner_team_name": "Hellacious Hill 12"
},
"percent_owned": {
"coverage_type": "week",
"week": "17",
"value": 99,
"delta": "0"
},
"player_id": "5228",
"player_key": "331.p.5228",
"player_notes_last_timestamp": 1568837880,
"player_points": {
"coverage_type": "week",
"week": "1",
"total": 10.26
},
"player_stats": {
"coverage_type": "week",
"week": "1",
"stats": [
{
"stat": {
"stat_id": "4",
"value": "249"
}
},
...
]
},
"position_type": "O",
"primary_position": "QB",
"selected_position": {
"coverage_type": "week",
"is_flex": 0,
"position": "QB",
"week": "1"
},
"uniform_number": "12"
}),
...,
Player({...})
]
Returns:
list[Player]: List of YFPY Player instances containing attributes "draft_analysis", "ownership",
"percent_owned", and "player_stats".
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/roster;week={chosen_week}/players;"
f"out=metadata,stats,ownership,percent_owned,draft_analysis",
["team", "roster", "0", "players"]
)
def get_team_roster_player_info_by_date(self, team_id: Union[str, int],
chosen_date: str = None) -> List[Player]:
"""Retrieve roster with ALL player info of specific team by team_id and by date for chosen league.
Note:
This applies to MLB, NBA, and NHL leagues, but does NOT apply to NFL leagues.
This query will FAIL if you pass it an INVALID date string!
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
chosen_date (str): Selected date for which to retrieve data. REQUIRED FORMAT: YYYY-MM-DD (Ex. 2011-05-01)
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nhl")
>>> query.get_team_roster_player_info_by_date(1, "2011-05-01")
[
Player({
"display_position": "C",
"draft_analysis": {
"average_pick": 33.2,
"average_round": 3.5,
"average_cost": 39.2,
"percent_drafted": 1.0
},
"editorial_player_key": "nhl.p.3981",
"editorial_team_abbr": "Chi",
"editorial_team_full_name": "Chicago Blackhawks",
"editorial_team_key": "nhl.t.4",
"eligible_positions": [
"C",
"F"
],
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/tz.KOMoEiBDch6AJAGaUtg--~C/
YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/
https://s.yimg.com/xe/i/us/sp/v/nhl_cutout/players_l/11032021/3981.png"
},
"is_editable": 0,
"is_undroppable": 0,
"name": {
"ascii_first": "Jonathan",
"ascii_last": "Toews",
"first": "Jonathan",
"full": "Jonathan Toews",
"last": "Toews"
},
"ownership": {
"ownership_type": "team",
"owner_team_key": "303.l.69624.t.2",
"owner_team_name": "The Bateleurs"
},
"percent_owned": {
"coverage_type": "week",
"week": 25,
"value": 98,
"delta": -1.0
},
"player_id": 3981,
"player_key": "303.p.3981",
"player_notes_last_timestamp": 1651606838,
"player_stats": {
"coverage_type": "date",
"stats": [
{
"stat": {
"stat_id": 1,
"value": 1.0
}
},
...
]
},
"position_type": "P",
"primary_position": "C",
"selected_position": {
"coverage_type": "date",
"is_flex": 0,
"position": "C"
},
"uniform_number": 19
}),
...,
Player({...})
]
Returns:
list[Player]: List of YFPY Player instances containing attributes "draft_analysis", "ownership",
"percent_owned", and "player_stats".
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/"
f"roster{';date=' + str(chosen_date) if chosen_date else ''}/players;"
f"out=metadata,stats,ownership,percent_owned,draft_analysis",
["team", "roster", "0", "players"]
)
def get_team_roster_player_stats(self, team_id: Union[str, int]) -> List[Player]:
"""Retrieve roster with ALL player info for the season of specific team by team_id and for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_roster_player_stats(1)
[
Player({
"bye_weeks": {
"week": "10"
},
"display_position": "QB",
"draft_analysis": {
"average_pick": "65.9",
"average_round": "7.6",
"average_cost": "5.0",
"percent_drafted": "1.00"
},
"editorial_player_key": "nfl.p.5228",
"editorial_team_abbr": "NE",
"editorial_team_full_name": "New England Patriots",
"editorial_team_key": "nfl.t.17",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/_U9UJlrYMsJ22DpA..S3zg--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ
2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08212019/5228.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Tom",
"ascii_last": "Brady",
"first": "Tom",
"full": "Tom Brady",
"last": "Brady"
},
"player_id": "5228",
"player_key": "331.p.5228",
"player_notes_last_timestamp": 1568837880,
"player_points": {
"coverage_type": "season",
"total": 287.06
},
"player_stats": {
"coverage_type": "season",
"stats": [
{
"stat": {
"stat_id": "4",
"value": "4109"
}
},
...
]
},
"position_type": "O",
"primary_position": "QB",
"selected_position": {
"coverage_type": "week",
"is_flex": 0,
"position": "QB",
"week": "16"
},
"uniform_number": "12"
}),
...,
Player({...})
]
Returns:
list[Player]: List of YFPY Player instances containing attributes "draft_analysis", "ownership",
"percent_owned", and "player_stats".
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/roster/players/stats;type=season",
["team", "roster", "0", "players"]
)
def get_team_roster_player_stats_by_week(self, team_id: Union[str, int],
chosen_week: Union[int, str] = "current") -> List[Player]:
"""Retrieve roster with player stats of specific team by team_id and by week for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
chosen_week (int): Selected week for which to retrieve data.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_roster_player_stats_by_week(1, 1)
[
Player({
"bye_weeks": {
"week": "10"
},
"display_position": "QB",
"editorial_player_key": "nfl.p.5228",
"editorial_team_abbr": "NE",
"editorial_team_full_name": "New England Patriots",
"editorial_team_key": "nfl.t.17",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/_U9UJlrYMsJ22DpA..S3zg--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt
3PTQ2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08212019/5228.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Tom",
"ascii_last": "Brady",
"first": "Tom",
"full": "Tom Brady",
"last": "Brady"
},
"player_id": "5228",
"player_key": "331.p.5228",
"player_notes_last_timestamp": 1568837880,
"player_points": {
"coverage_type": "week",
"week": "1",
"total": 10.26
},
"player_stats": {
"coverage_type": "week",
"week": "1",
"stats": [
{
"stat": {
"stat_id": "4",
"value": "249"
}
},
...
]
},
"position_type": "O",
"primary_position": "QB",
"selected_position": {
"coverage_type": "week",
"is_flex": 0,
"position": "QB",
"week": "1"
},
"uniform_number": "12"
}),
...,
Player({...})
]
Returns:
list[Player]: List of YFPY Player instances containing attribute "player_stats".
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/roster;week={chosen_week}/players/stats",
["team", "roster", "0", "players"]
)
def get_team_draft_results(self, team_id: Union[str, int]) -> List[DraftResult]:
"""Retrieve draft results of specific team by team_id for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_draft_results(1)
[
DraftResult({
"pick": 4,
"round": 1,
"team_key": "331.l.729259.t.1",
"player_key": "331.p.8256"
}),
...,
DraftResults({...})
]
Returns:
list[DraftResult]: List of YFPY DraftResult instances.
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/draftresults",
["team", "draft_results"]
)
def get_team_matchups(self, team_id: Union[str, int]) -> List[Matchup]:
"""Retrieve matchups of specific team by team_id for chosen league.
Args:
team_id (str | int): Selected team ID for which to retrieva data (can be integers 1 through n where n is the
number of teams in the league).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_team_matchups(1)
[
Matchup({
<matchup data> (see get_league_matchups_by_week docstring for matchup data example)
})
]
Returns:
list[Matchup]: List of YFPY Matchup instances.
"""
team_key = f"{self.get_league_key()}.t.{team_id}"
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/team/{team_key}/matchups",
["team", "matchups"]
)
def get_player_stats_for_season(self, player_key: str, limit_to_league_stats: bool = True) -> Player:
"""Retrieve stats of specific player by player_key for the entire season for chosen league.
Args:
player_key (str): The player key of chosen player (example: 331.p.7200 - <game_id>.p.<player_id>).
limit_to_league_stats (bool): Boolean (default: True) to limit the retrieved player stats to those for the
selected league. When set to False, query retrieves all player stats for the game (NFL, NHL, NBA, MLB).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_player_stats_for_season("331.p.7200")
Player({
"bye_weeks": {
"week": "9"
},
"display_position": "QB",
"editorial_player_key": "nfl.p.7200",
"editorial_team_abbr": "GB",
"editorial_team_full_name": "Green Bay Packers",
"editorial_team_key": "nfl.t.9",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/Xdm96BfVJw4WV_W7GA7xLw--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ
2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08202019/7200.2.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Aaron",
"ascii_last": "Rodgers",
"first": "Aaron",
"full": "Aaron Rodgers",
"last": "Rodgers"
},
"player_id": "7200",
"player_key": "331.p.7200",
"player_notes_last_timestamp": 1568581740,
"player_points": {
"coverage_type": "season",
"total": 359.14
},
"player_stats": {
"coverage_type": "season",
"stats": [
{
"stat": {
"stat_id": "4",
"value": "4381"
}
},
...
]
},
"position_type": "O",
"primary_position": "QB",
"uniform_number": "12"
})
Returns:
Player: YFPY Player instance.
"""
if limit_to_league_stats:
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/players;"
f"player_keys={player_key}/stats",
["league", "players", "0", "player"],
Player
)
else:
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/players;"
f"player_keys={player_key}/stats",
["players", "0", "player"],
Player
)
def get_player_stats_by_week(self, player_key: str, chosen_week: Union[int, str] = "current",
limit_to_league_stats: bool = True) -> Player:
"""Retrieve stats of specific player by player_key and by week for chosen league.
Args:
player_key (str): The player key of chosen player (example: 331.p.7200 - <game_id>.p.<player_id>).
chosen_week (int): Selected week for which to retrieve data.
limit_to_league_stats (bool): Boolean (default: True) to limit the retrieved player stats to those for the
selected league. When set to False, query retrieves all player stats for the game (NFL, NHL, NBA, MLB).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_player_stats_by_week("331.p.7200", 1)
Player({
"bye_weeks": {
"week": "9"
},
"display_position": "QB",
"editorial_player_key": "nfl.p.7200",
"editorial_team_abbr": "GB",
"editorial_team_full_name": "Green Bay Packers",
"editorial_team_key": "nfl.t.9",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/Xdm96BfVJw4WV_W7GA7xLw--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ
2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08202019/7200.2.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Aaron",
"ascii_last": "Rodgers",
"first": "Aaron",
"full": "Aaron Rodgers",
"last": "Rodgers"
},
"player_id": "7200",
"player_key": "331.p.7200",
"player_notes_last_timestamp": 1568581740,
"player_points": {
"coverage_type": "week",
"week": "1",
"total": 10.56
},
"player_stats": {
"coverage_type": "week",
"week": "1",
"stats": [
{
"stat": {
"stat_id": "4",
"value": "189"
}
},
...
]
},
"position_type": "O",
"primary_position": "QB",
"uniform_number": "12"
})
Returns:
Player: YFPY Player instance containing attribute "player_stats".
"""
if limit_to_league_stats:
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/players;"
f"player_keys={player_key}/stats;type=week;week={chosen_week}",
["league", "players", "0", "player"],
Player
)
else:
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/players;"
f"player_keys={player_key}/stats;type=week;week={chosen_week}",
["players", "0", "player"],
Player
)
def get_player_stats_by_date(self, player_key: str, chosen_date: str = None,
limit_to_league_stats: bool = True) -> Player:
"""Retrieve player stats by player_key and by date for chosen league.
Note:
This applies to MLB, NBA, and NHL leagues, but does NOT apply to NFL leagues.
This query will FAIL if you pass it an INVALID date string!
Args:
player_key (str): The player key of chosen player (example: 331.p.7200 - <game_id>.p.<player_id>).
chosen_date (str): Selected date for which to retrieve data. REQUIRED FORMAT: YYYY-MM-DD (Ex. 2011-05-01)
limit_to_league_stats (bool): Boolean (default: True) to limit the retrieved player stats to those for the
selected league. When set to False, query retrieves all player stats for the game (NFL, NHL, NBA, MLB).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nhl")
>>> query.get_player_stats_by_date("nhl.p.4588", "2011-05-01")
Player({
"display_position": "G",
"editorial_player_key": "nhl.p.4588",
"editorial_team_abbr": "Was",
"editorial_team_full_name": "Washington Capitals",
"editorial_team_key": "nhl.t.23",
"eligible_positions": {
"position": "G"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/CzntDh_d59voTqU6fhQy3g--~C/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2
NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/https://s.yimg.com/
xe/i/us/sp/v/nhl_cutout/players_l/10182019/4588.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Braden",
"ascii_last": "Holtby",
"first": "Braden",
"full": "Braden Holtby",
"last": "Holtby"
},
"player_id": "4588",
"player_key": "303.p.4588",
"player_notes_last_timestamp": 1574133600,
"player_stats": {
"coverage_type": "date",
"stats": [
{
"stat": {
"stat_id": "19",
"value": "1"
}
},
{
"stat": {
"stat_id": "22",
"value": "1"
}
},
{
"stat": {
"stat_id": "23",
"value": "1.00"
}
},
{
"stat": {
"stat_id": "25",
"value": "29"
}
},
{
"stat": {
"stat_id": "24",
"value": "30"
}
},
{
"stat": {
"stat_id": "26",
"value": ".967"
}
},
{
"stat": {
"stat_id": "27",
"value": "0"
}
}
]
},
"position_type": "G",
"primary_position": "G",
"uniform_number": "70"
})
Returns:
Player: YFPY Player instnace containing attribute "player_stats".
"""
if limit_to_league_stats:
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/players;"
f"player_keys={player_key}/stats;type=date;date={chosen_date}",
["league", "players", "0", "player"],
Player
)
else:
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/players;"
f"player_keys={player_key}/stats;type=date;date={chosen_date}",
["players", "0", "player"],
Player
)
def get_player_ownership(self, player_key: str) -> Player:
"""Retrieve ownership of specific player by player_key for chosen league.
Args:
player_key (str): The player key of chosen player (example: 331.p.7200 - <game_id>.p.<player_id>).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_player_ownership("331.p.7200")
Player({
"bye_weeks": {
"week": "9"
},
"display_position": "QB",
"editorial_player_key": "nfl.p.7200",
"editorial_team_abbr": "GB",
"editorial_team_full_name": "Green Bay Packers",
"editorial_team_key": "nfl.t.9",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/Xdm96BfVJw4WV_W7GA7xLw--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ
2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08202019/7200.2.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Aaron",
"ascii_last": "Rodgers",
"first": "Aaron",
"full": "Aaron Rodgers",
"last": "Rodgers"
},
"ownership": {
"ownership_type": "team",
"owner_team_key": "331.l.729259.t.4",
"owner_team_name": "hold my D",
"teams": {
"team": {
"clinched_playoffs": 1,
"draft_grade": "B-",
"draft_position": 1,
"draft_recap_url":
"https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/4/draftrecap",
"has_draft_grade": 1,
"league_scoring_type": "head",
"managers": {
"manager": {
"guid": "5KLNXUYW5RP22UMRKUXHBCIITI",
"manager_id": "4",
"nickname": "--hidden--"
}
},
"name": "hold my D",
"number_of_moves": "27",
"number_of_trades": "1",
"roster_adds": {
"coverage_type": "week",
"coverage_value": "17",
"value": "0"
},
"team_id": "4",
"team_key": "331.l.729259.t.4",
"team_logos": {
"team_logo": {
"size": "large",
"url": "https://ct.yimg.com/cy/1589/24677593583_68859308dd_192sq.jpg?ct=fantasy"
}
},
"url": "https://football.fantasysports.yahoo.com/archive/nfl/2014/729259/4",
"waiver_priority": 7
}
}
},
"player_id": "7200",
"player_key": "331.p.7200",
"player_notes_last_timestamp": 1568581740,
"position_type": "O",
"primary_position": "QB",
"uniform_number": "12"
})
Returns:
Player: YFPY Player instance containing attribute "ownership".
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/players;"
f"player_keys={player_key}/ownership",
["league", "players", "0", "player"],
Player
)
def get_player_percent_owned_by_week(self, player_key: str, chosen_week: Union[int, str] = "current") -> Player:
"""Retrieve percent-owned of specific player by player_key and by week for chosen league.
Args:
player_key (str): The player key of chosen player (example: 331.p.7200 - <game_id>.p.<player_id>).
chosen_week (int): Selected week for which to retrieve data.
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_player_percent_owned_by_week("331.p.7200", 1)
Player({
"bye_weeks": {
"week": "9"
},
"display_position": "QB",
"editorial_player_key": "nfl.p.7200",
"editorial_team_abbr": "GB",
"editorial_team_full_name": "Green Bay Packers",
"editorial_team_key": "nfl.t.9",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/Xdm96BfVJw4WV_W7GA7xLw--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ2/
https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08202019/7200.2.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Aaron",
"ascii_last": "Rodgers",
"first": "Aaron",
"full": "Aaron Rodgers",
"last": "Rodgers"
},
"percent_owned": {
"coverage_type": "week",
"week": "1",
"value": 100,
"delta": "0"
},
"player_id": "7200",
"player_key": "331.p.7200",
"player_notes_last_timestamp": 1568581740,
"position_type": "O",
"primary_position": "QB",
"uniform_number": "12"
})
Returns:
Player: YFPY Player instance containing attribute "percent_owned".
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/players;"
f"player_keys={player_key}/percent_owned;type=week;week={chosen_week}",
["league", "players", "0", "player"],
Player
)
def get_player_draft_analysis(self, player_key: str) -> Player:
"""Retrieve draft analysis of specific player by player_key for chosen league.
Args:
player_key (str): The player key of chosen player (example: 331.p.7200 - <game_id>.p.<player_id>).
Examples:
>>> from pathlib import Path
>>> from yfpy.query import YahooFantasySportsQuery
>>> query = YahooFantasySportsQuery(league_id="######", game_code="nfl")
>>> query.get_player_draft_analysis("331.p.7200")
Player({
"bye_weeks": {
"week": "9"
},
"display_position": "QB",
"draft_analysis": {
"average_pick": "19.9",
"average_round": "2.8",
"average_cost": "38.5",
"percent_drafted": "1.00"
},
"editorial_player_key": "nfl.p.7200",
"editorial_team_abbr": "GB",
"editorial_team_full_name": "Green Bay Packers",
"editorial_team_key": "nfl.t.9",
"eligible_positions": {
"position": "QB"
},
"has_player_notes": 1,
"headshot": {
"size": "small",
"url": "https://s.yimg.com/iu/api/res/1.2/Xdm96BfVJw4WV_W7GA7xLw--~C
/YXBwaWQ9eXNwb3J0cztjaD0yMzM2O2NyPTE7Y3c9MTc5MDtkeD04NTc7ZHk9MDtmaT11bGNyb3A7aD02MDtxPTEwMDt3PTQ
2/https://s.yimg.com/xe/i/us/sp/v/nfl_cutout/players_l/08202019/7200.2.png"
},
"is_undroppable": "0",
"name": {
"ascii_first": "Aaron",
"ascii_last": "Rodgers",
"first": "Aaron",
"full": "Aaron Rodgers",
"last": "Rodgers"
},
"player_id": "7200",
"player_key": "331.p.7200",
"player_notes_last_timestamp": 1568581740,
"position_type": "O",
"primary_position": "QB",
"uniform_number": "12"
})
Returns:
Player: YFPY Player instance containing attribute "draft_analysis".
"""
return self.query(
f"https://fantasysports.yahooapis.com/fantasy/v2/league/{self.get_league_key()}/players;"
f"player_keys={player_key}/draft_analysis",
["league", "players", "0", "player"],
Player
)
|