python-stats 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
py_stats/univariate.py ADDED
@@ -0,0 +1,1213 @@
1
+ """
2
+ Univariate statistics functions for py-stats package.
3
+
4
+ This module provides comprehensive univariate statistical analysis functions
5
+ including means, central tendency measures, quantiles, dispersion measures,
6
+ shape measures, and specialized statistical functions.
7
+ """
8
+
9
+ import math
10
+ import statistics
11
+ from typing import List, Union, Tuple, Optional
12
+ import numpy as np
13
+
14
+
15
+ def _validate_data(data: List[Union[int, float]]) -> List[float]:
16
+ """Validate and convert data to list of floats."""
17
+ if not data:
18
+ raise ValueError("Data cannot be empty")
19
+
20
+ try:
21
+ return [float(x) for x in data]
22
+ except (ValueError, TypeError):
23
+ raise ValueError("All data points must be numeric")
24
+
25
+
26
+ def arithmetic_mean(data: List[Union[int, float]]) -> float:
27
+ """
28
+ Calculate the arithmetic mean (average) of a dataset.
29
+
30
+ Args:
31
+ data: List of numeric values
32
+
33
+ Returns:
34
+ Arithmetic mean of the data
35
+
36
+ Example:
37
+ >>> arithmetic_mean([1, 2, 3, 4, 5])
38
+ 3.0
39
+ """
40
+ data = _validate_data(data)
41
+ return sum(data) / len(data)
42
+
43
+
44
+ def harmonic_mean(data: List[Union[int, float]]) -> float:
45
+ """
46
+ Calculate the harmonic mean of a dataset.
47
+
48
+ The harmonic mean is the reciprocal of the arithmetic mean of reciprocals.
49
+ Useful for rates, speeds, and ratios.
50
+
51
+ Args:
52
+ data: List of positive numeric values
53
+
54
+ Returns:
55
+ Harmonic mean of the data
56
+
57
+ Example:
58
+ >>> harmonic_mean([1, 2, 4])
59
+ 1.7142857142857142
60
+ """
61
+ data = _validate_data(data)
62
+ if any(x <= 0 for x in data):
63
+ raise ValueError("All values must be positive for harmonic mean")
64
+
65
+ return len(data) / sum(1/x for x in data)
66
+
67
+
68
+ def geometric_mean(data: List[Union[int, float]]) -> float:
69
+ """
70
+ Calculate the geometric mean of a dataset.
71
+
72
+ The geometric mean is the nth root of the product of n values.
73
+ Useful for growth rates and ratios.
74
+
75
+ Args:
76
+ data: List of positive numeric values
77
+
78
+ Returns:
79
+ Geometric mean of the data
80
+
81
+ Example:
82
+ >>> geometric_mean([1, 2, 4])
83
+ 2.0
84
+ """
85
+ data = _validate_data(data)
86
+ if any(x <= 0 for x in data):
87
+ raise ValueError("All values must be positive for geometric mean")
88
+
89
+ return math.pow(math.prod(data), 1/len(data))
90
+
91
+
92
+ def quadratic_mean(data: List[Union[int, float]]) -> float:
93
+ """
94
+ Calculate the quadratic mean (root mean square) of a dataset.
95
+
96
+ The quadratic mean is the square root of the arithmetic mean of squares.
97
+ Useful for physical quantities like voltage and current.
98
+
99
+ Args:
100
+ data: List of numeric values
101
+
102
+ Returns:
103
+ Quadratic mean of the data
104
+
105
+ Example:
106
+ >>> quadratic_mean([1, 2, 3, 4, 5])
107
+ 3.3166247903554
108
+ """
109
+ data = _validate_data(data)
110
+ return math.sqrt(sum(x**2 for x in data) / len(data))
111
+
112
+
113
+ def median(data: List[Union[int, float]]) -> float:
114
+ """
115
+ Calculate the median of a dataset.
116
+
117
+ The median is the middle value when data is sorted.
118
+ For even-sized datasets, it's the average of the two middle values.
119
+
120
+ Args:
121
+ data: List of numeric values
122
+
123
+ Returns:
124
+ Median of the data
125
+
126
+ Example:
127
+ >>> median([1, 3, 5, 7, 9])
128
+ 5.0
129
+ >>> median([1, 2, 3, 4])
130
+ 2.5
131
+ """
132
+ data = _validate_data(data)
133
+ sorted_data = sorted(data)
134
+ n = len(sorted_data)
135
+
136
+ if n % 2 == 1:
137
+ return sorted_data[n // 2]
138
+ else:
139
+ return (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2
140
+
141
+
142
+ def mode(data: List[Union[int, float]]) -> List[float]:
143
+ """
144
+ Calculate the mode(s) of a dataset.
145
+
146
+ The mode is the most frequently occurring value(s).
147
+ Returns all modes if there are multiple.
148
+
149
+ Args:
150
+ data: List of numeric values
151
+
152
+ Returns:
153
+ List of mode(s)
154
+
155
+ Example:
156
+ >>> mode([1, 2, 2, 3, 4])
157
+ [2.0]
158
+ >>> mode([1, 1, 2, 2, 3])
159
+ [1.0, 2.0]
160
+ """
161
+ data = _validate_data(data)
162
+ frequency = {}
163
+
164
+ for value in data:
165
+ frequency[value] = frequency.get(value, 0) + 1
166
+
167
+ max_freq = max(frequency.values())
168
+ modes = [value for value, freq in frequency.items() if freq == max_freq]
169
+
170
+ return sorted(modes)
171
+
172
+
173
+ def midrange(data: List[Union[int, float]]) -> float:
174
+ """
175
+ Calculate the midrange of a dataset.
176
+
177
+ The midrange is the average of the minimum and maximum values.
178
+
179
+ Args:
180
+ data: List of numeric values
181
+
182
+ Returns:
183
+ Midrange of the data
184
+
185
+ Example:
186
+ >>> midrange([1, 2, 3, 4, 5])
187
+ 3.0
188
+ """
189
+ data = _validate_data(data)
190
+ return (min(data) + max(data)) / 2
191
+
192
+
193
+ def trimean(data: List[Union[int, float]]) -> float:
194
+ """
195
+ Calculate the trimean of a dataset.
196
+
197
+ The trimean is (Q1 + 2*Q2 + Q3) / 4, where Q1, Q2, Q3 are quartiles.
198
+ It's a robust measure of central tendency.
199
+
200
+ Args:
201
+ data: List of numeric values
202
+
203
+ Returns:
204
+ Trimean of the data
205
+
206
+ Example:
207
+ >>> trimean([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
208
+ 5.5
209
+ """
210
+ data = _validate_data(data)
211
+ q1, q2, q3 = quartiles(data)
212
+ return (q1 + 2 * q2 + q3) / 4
213
+
214
+
215
+ def quartiles(data: List[Union[int, float]]) -> Tuple[float, float, float]:
216
+ """
217
+ Calculate the first, second (median), and third quartiles.
218
+
219
+ Args:
220
+ data: List of numeric values
221
+
222
+ Returns:
223
+ Tuple of (Q1, Q2, Q3)
224
+
225
+ Example:
226
+ >>> quartiles([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
227
+ (3.25, 5.5, 7.75)
228
+ """
229
+ data = _validate_data(data)
230
+ sorted_data = sorted(data)
231
+ n = len(sorted_data)
232
+
233
+ q1 = quantile(sorted_data, 0.25)
234
+ q2 = quantile(sorted_data, 0.50)
235
+ q3 = quantile(sorted_data, 0.75)
236
+
237
+ return q1, q2, q3
238
+
239
+
240
+ def hinges(data: List[Union[int, float]]) -> Tuple[float, float]:
241
+ """
242
+ Calculate the lower and upper hinges.
243
+
244
+ Hinges are similar to quartiles but use a different calculation method.
245
+
246
+ Args:
247
+ data: List of numeric values
248
+
249
+ Returns:
250
+ Tuple of (lower_hinge, upper_hinge)
251
+
252
+ Example:
253
+ >>> hinges([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
254
+ (3.5, 7.5)
255
+ """
256
+ data = _validate_data(data)
257
+ sorted_data = sorted(data)
258
+ n = len(sorted_data)
259
+
260
+ if n % 2 == 0:
261
+ lower_half = sorted_data[:n//2]
262
+ upper_half = sorted_data[n//2:]
263
+ else:
264
+ lower_half = sorted_data[:n//2]
265
+ upper_half = sorted_data[n//2 + 1:]
266
+
267
+ lower_hinge = median(lower_half)
268
+ upper_hinge = median(upper_half)
269
+
270
+ return lower_hinge, upper_hinge
271
+
272
+
273
+ def quantile(data: List[Union[int, float]], q: float) -> float:
274
+ """
275
+ Calculate the quantile at probability q.
276
+
277
+ Args:
278
+ data: List of numeric values
279
+ q: Probability (0 <= q <= 1)
280
+
281
+ Returns:
282
+ Quantile value
283
+
284
+ Example:
285
+ >>> quantile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0.25)
286
+ 3.25
287
+ """
288
+ if not 0 <= q <= 1:
289
+ raise ValueError("Quantile probability must be between 0 and 1")
290
+
291
+ data = _validate_data(data)
292
+ sorted_data = sorted(data)
293
+ n = len(sorted_data)
294
+
295
+ if q == 0:
296
+ return sorted_data[0]
297
+ if q == 1:
298
+ return sorted_data[-1]
299
+
300
+ # Linear interpolation method
301
+ index = q * (n - 1)
302
+ lower_index = int(index)
303
+ upper_index = min(lower_index + 1, n - 1)
304
+
305
+ if lower_index == upper_index:
306
+ return sorted_data[lower_index]
307
+
308
+ weight = index - lower_index
309
+ return sorted_data[lower_index] * (1 - weight) + sorted_data[upper_index] * weight
310
+
311
+
312
+ def variance(data: List[Union[int, float]], population: bool = False) -> float:
313
+ """
314
+ Calculate the variance of a dataset.
315
+
316
+ Args:
317
+ data: List of numeric values
318
+ population: If True, calculate population variance (n denominator)
319
+ If False, calculate sample variance (n-1 denominator)
320
+
321
+ Returns:
322
+ Variance of the data
323
+
324
+ Example:
325
+ >>> variance([1, 2, 3, 4, 5])
326
+ 2.5
327
+ >>> variance([1, 2, 3, 4, 5], population=True)
328
+ 2.0
329
+ """
330
+ data = _validate_data(data)
331
+ if len(data) < 2:
332
+ raise ValueError("At least 2 data points required for variance")
333
+
334
+ mean_val = arithmetic_mean(data)
335
+ squared_diff_sum = sum((x - mean_val) ** 2 for x in data)
336
+
337
+ denominator = len(data) if population else len(data) - 1
338
+ return squared_diff_sum / denominator
339
+
340
+
341
+ def standard_deviation(data: List[Union[int, float]], population: bool = False) -> float:
342
+ """
343
+ Calculate the standard deviation of a dataset.
344
+
345
+ Args:
346
+ data: List of numeric values
347
+ population: If True, calculate population standard deviation
348
+ If False, calculate sample standard deviation
349
+
350
+ Returns:
351
+ Standard deviation of the data
352
+
353
+ Example:
354
+ >>> standard_deviation([1, 2, 3, 4, 5])
355
+ 1.5811388300841898
356
+ """
357
+ return math.sqrt(variance(data, population))
358
+
359
+
360
+ def average_deviation(data: List[Union[int, float]]) -> float:
361
+ """
362
+ Calculate the average absolute deviation from the mean.
363
+
364
+ Args:
365
+ data: List of numeric values
366
+
367
+ Returns:
368
+ Average absolute deviation
369
+
370
+ Example:
371
+ >>> average_deviation([1, 2, 3, 4, 5])
372
+ 1.2
373
+ """
374
+ data = _validate_data(data)
375
+ mean_val = arithmetic_mean(data)
376
+ return sum(abs(x - mean_val) for x in data) / len(data)
377
+
378
+
379
+ def median_absolute_deviation(data: List[Union[int, float]]) -> float:
380
+ """
381
+ Calculate the median absolute deviation (MAD).
382
+
383
+ MAD is the median of absolute deviations from the median.
384
+ It's a robust measure of dispersion.
385
+
386
+ Args:
387
+ data: List of numeric values
388
+
389
+ Returns:
390
+ Median absolute deviation
391
+
392
+ Example:
393
+ >>> median_absolute_deviation([1, 2, 3, 4, 5])
394
+ 1.0
395
+ """
396
+ data = _validate_data(data)
397
+ median_val = median(data)
398
+ absolute_deviations = [abs(x - median_val) for x in data]
399
+ return median(absolute_deviations)
400
+
401
+
402
+ def skewness(data: List[Union[int, float]]) -> float:
403
+ """
404
+ Calculate the skewness of a dataset.
405
+
406
+ Skewness measures the asymmetry of the distribution.
407
+ Positive skewness indicates a longer right tail.
408
+
409
+ Args:
410
+ data: List of numeric values
411
+
412
+ Returns:
413
+ Skewness coefficient
414
+
415
+ Example:
416
+ >>> skewness([1, 2, 3, 4, 5])
417
+ 0.0
418
+ """
419
+ data = _validate_data(data)
420
+ if len(data) < 3:
421
+ raise ValueError("At least 3 data points required for skewness")
422
+
423
+ mean_val = arithmetic_mean(data)
424
+ std_val = standard_deviation(data)
425
+
426
+ if std_val == 0:
427
+ return 0.0
428
+
429
+ n = len(data)
430
+ skew_sum = sum(((x - mean_val) / std_val) ** 3 for x in data)
431
+ return (n / ((n - 1) * (n - 2))) * skew_sum
432
+
433
+
434
+ def kurtosis(data: List[Union[int, float]]) -> float:
435
+ """
436
+ Calculate the kurtosis of a dataset.
437
+
438
+ Kurtosis measures the "tailedness" of the distribution.
439
+ Higher kurtosis indicates more extreme deviations.
440
+
441
+ Args:
442
+ data: List of numeric values
443
+
444
+ Returns:
445
+ Kurtosis coefficient
446
+
447
+ Example:
448
+ >>> kurtosis([1, 2, 3, 4, 5])
449
+ -1.2
450
+ """
451
+ data = _validate_data(data)
452
+ if len(data) < 4:
453
+ raise ValueError("At least 4 data points required for kurtosis")
454
+
455
+ mean_val = arithmetic_mean(data)
456
+ std_val = standard_deviation(data)
457
+
458
+ if std_val == 0:
459
+ return 0.0
460
+
461
+ n = len(data)
462
+ kurt_sum = sum(((x - mean_val) / std_val) ** 4 for x in data)
463
+
464
+ # Excess kurtosis (subtract 3 to make normal distribution = 0)
465
+ return (n * (n + 1) / ((n - 1) * (n - 2) * (n - 3))) * kurt_sum - (3 * (n - 1) ** 2 / ((n - 2) * (n - 3)))
466
+
467
+
468
+ def angular_mean(data: List[Union[int, float]], degrees: bool = True) -> float:
469
+ """
470
+ Calculate the mean of angular quantities.
471
+
472
+ Args:
473
+ data: List of angular values
474
+ degrees: If True, input is in degrees; if False, in radians
475
+
476
+ Returns:
477
+ Mean angle in the same units as input
478
+
479
+ Example:
480
+ >>> angular_mean([0, 90, 180, 270])
481
+ 135.0
482
+ """
483
+ data = _validate_data(data)
484
+
485
+ if degrees:
486
+ # Convert to radians
487
+ data_rad = [math.radians(x) for x in data]
488
+ else:
489
+ data_rad = data
490
+
491
+ # Calculate mean of sines and cosines
492
+ mean_sin = sum(math.sin(x) for x in data_rad) / len(data_rad)
493
+ mean_cos = sum(math.cos(x) for x in data_rad) / len(data_rad)
494
+
495
+ # Convert back to angle
496
+ result = math.atan2(mean_sin, mean_cos)
497
+
498
+ if degrees:
499
+ result = math.degrees(result)
500
+
501
+ # Ensure result is in [0, 360) for degrees or [0, 2π) for radians
502
+ if degrees:
503
+ return (result + 360) % 360
504
+ else:
505
+ return (result + 2 * math.pi) % (2 * math.pi)
506
+
507
+
508
+ def running_average(data: List[Union[int, float]], window: int = 3) -> List[float]:
509
+ """
510
+ Calculate running average with specified window size.
511
+
512
+ Args:
513
+ data: List of numeric values
514
+ window: Size of the moving window
515
+
516
+ Returns:
517
+ List of running averages
518
+
519
+ Example:
520
+ >>> running_average([1, 2, 3, 4, 5], window=3)
521
+ [2.0, 3.0, 4.0]
522
+ """
523
+ data = _validate_data(data)
524
+ if window > len(data):
525
+ raise ValueError("Window size cannot be larger than data size")
526
+ if window < 1:
527
+ raise ValueError("Window size must be at least 1")
528
+
529
+ result = []
530
+ for i in range(len(data) - window + 1):
531
+ window_data = data[i:i + window]
532
+ result.append(arithmetic_mean(window_data))
533
+
534
+ return result
535
+
536
+
537
+ def weighted_average(data: List[Union[int, float]], weights: List[Union[int, float]]) -> float:
538
+ """
539
+ Calculate weighted average of a dataset.
540
+
541
+ Args:
542
+ data: List of numeric values
543
+ weights: List of weights (must be same length as data)
544
+
545
+ Returns:
546
+ Weighted average
547
+
548
+ Example:
549
+ >>> weighted_average([1, 2, 3], [0.5, 1.0, 1.5])
550
+ 2.1666666666666665
551
+ """
552
+ data = _validate_data(data)
553
+ weights = _validate_data(weights)
554
+
555
+ if len(data) != len(weights):
556
+ raise ValueError("Data and weights must have the same length")
557
+
558
+ if any(w < 0 for w in weights):
559
+ raise ValueError("Weights must be non-negative")
560
+
561
+ total_weight = sum(weights)
562
+ if total_weight == 0:
563
+ raise ValueError("Sum of weights cannot be zero")
564
+
565
+ return sum(x * w for x, w in zip(data, weights)) / total_weight
566
+
567
+
568
+ def standard_error_mean(data: List[Union[int, float]]) -> float:
569
+ """
570
+ Calculate the standard error of the mean.
571
+
572
+ Args:
573
+ data: List of numeric values
574
+
575
+ Returns:
576
+ Standard error of the mean
577
+
578
+ Example:
579
+ >>> standard_error_mean([1, 2, 3, 4, 5])
580
+ 0.7071067811865476
581
+ """
582
+ data = _validate_data(data)
583
+ if len(data) < 2:
584
+ raise ValueError("At least 2 data points required for standard error")
585
+
586
+ return standard_deviation(data) / math.sqrt(len(data))
587
+
588
+
589
+ # Additional robust statistics functions
590
+
591
+ def winsorized_mean(data: List[Union[int, float]], percent: float = 10.0) -> float:
592
+ """
593
+ Calculate the winsorized mean.
594
+
595
+ Winsorization replaces extreme values with less extreme ones.
596
+
597
+ Args:
598
+ data: List of numeric values
599
+ percent: Percentage of values to winsorize from each end
600
+
601
+ Returns:
602
+ Winsorized mean
603
+
604
+ Example:
605
+ >>> winsorized_mean([1, 2, 3, 4, 100], percent=20)
606
+ 3.0
607
+ """
608
+ data = _validate_data(data)
609
+ if not 0 <= percent <= 50:
610
+ raise ValueError("Percent must be between 0 and 50")
611
+
612
+ sorted_data = sorted(data)
613
+ n = len(sorted_data)
614
+ k = int(round(n * percent / 100))
615
+
616
+ # Replace k smallest values with (k+1)th smallest
617
+ # Replace k largest values with (n-k)th largest
618
+ winsorized_data = sorted_data.copy()
619
+ if k > 0:
620
+ winsorized_data[:k] = [sorted_data[k]] * k
621
+ winsorized_data[-k:] = [sorted_data[n-k-1]] * k
622
+
623
+ return arithmetic_mean(winsorized_data)
624
+
625
+
626
+ def trimmed_mean(data: List[Union[int, float]], percent: float = 10.0) -> float:
627
+ """
628
+ Calculate the trimmed mean.
629
+
630
+ Trimming removes extreme values from both ends.
631
+
632
+ Args:
633
+ data: List of numeric values
634
+ percent: Percentage of values to trim from each end
635
+
636
+ Returns:
637
+ Trimmed mean
638
+
639
+ Example:
640
+ >>> trimmed_mean([1, 2, 3, 4, 100], percent=20)
641
+ 3.0
642
+ """
643
+ data = _validate_data(data)
644
+ if not 0 <= percent <= 50:
645
+ raise ValueError("Percent must be between 0 and 50")
646
+
647
+ sorted_data = sorted(data)
648
+ n = len(sorted_data)
649
+ k = int(round(n * percent / 100))
650
+
651
+ # Remove k values from each end
652
+ trimmed_data = sorted_data[k:n-k]
653
+
654
+ if not trimmed_data:
655
+ raise ValueError("No data remaining after trimming")
656
+
657
+ return arithmetic_mean(trimmed_data)
658
+
659
+
660
+ def interquartile_range(data: List[Union[int, float]]) -> float:
661
+ """
662
+ Calculate the interquartile range (IQR).
663
+
664
+ IQR is the difference between Q3 and Q1.
665
+
666
+ Args:
667
+ data: List of numeric values
668
+
669
+ Returns:
670
+ Interquartile range
671
+
672
+ Example:
673
+ >>> interquartile_range([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
674
+ 4.5
675
+ """
676
+ data = _validate_data(data)
677
+ q1, _, q3 = quartiles(data)
678
+ return q3 - q1
679
+
680
+
681
+ def range_value(data: List[Union[int, float]]) -> float:
682
+ """
683
+ Calculate the range of a dataset.
684
+
685
+ Range is the difference between maximum and minimum values.
686
+
687
+ Args:
688
+ data: List of numeric values
689
+
690
+ Returns:
691
+ Range of the data
692
+
693
+ Example:
694
+ >>> range_value([1, 2, 3, 4, 5])
695
+ 4.0
696
+ """
697
+ data = _validate_data(data)
698
+ return max(data) - min(data)
699
+
700
+
701
+ def coefficient_of_variation(data: List[Union[int, float]]) -> float:
702
+ """
703
+ Calculate the coefficient of variation.
704
+
705
+ CV is the ratio of standard deviation to mean, expressed as a decimal.
706
+
707
+ Args:
708
+ data: List of numeric values
709
+
710
+ Returns:
711
+ Coefficient of variation (as a decimal)
712
+
713
+ Example:
714
+ >>> coefficient_of_variation([1, 2, 3, 4, 5])
715
+ 0.5270462766947299
716
+ """
717
+ data = _validate_data(data)
718
+ mean_val = arithmetic_mean(data)
719
+
720
+ if mean_val == 0:
721
+ raise ValueError("Cannot calculate CV when mean is zero")
722
+
723
+ return standard_deviation(data) / abs(mean_val)
724
+
725
+
726
+ # Order statistics functions
727
+
728
+ def percentile_rank(data: List[Union[int, float]], value: Union[int, float]) -> float:
729
+ """
730
+ Calculate the percentile rank of a value in a dataset.
731
+
732
+ Args:
733
+ data: List of numeric values
734
+ value: Value to find percentile rank for
735
+
736
+ Returns:
737
+ Percentile rank (0-100)
738
+
739
+ Example:
740
+ >>> percentile_rank([1, 2, 3, 4, 5], 3)
741
+ 50.0
742
+ """
743
+ data = _validate_data(data)
744
+ sorted_data = sorted(data)
745
+
746
+ # Count values less than the target value
747
+ count_less = sum(1 for x in sorted_data if x < value)
748
+
749
+ # Count values equal to the target value
750
+ count_equal = sum(1 for x in sorted_data if x == value)
751
+
752
+ # Calculate percentile rank
753
+ rank = (count_less + 0.5 * count_equal) / len(sorted_data) * 100
754
+ return rank
755
+
756
+
757
+ def deciles(data: List[Union[int, float]]) -> List[float]:
758
+ """
759
+ Calculate all deciles (10th, 20th, ..., 90th percentiles).
760
+
761
+ Args:
762
+ data: List of numeric values
763
+
764
+ Returns:
765
+ List of deciles [D1, D2, ..., D9]
766
+
767
+ Example:
768
+ >>> deciles([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
769
+ [1.9, 2.8, 3.7, 4.6, 5.5, 6.4, 7.3, 8.2, 9.1]
770
+ """
771
+ data = _validate_data(data)
772
+ sorted_data = sorted(data)
773
+
774
+ deciles_list = []
775
+ for i in range(1, 10):
776
+ q = i / 10
777
+ deciles_list.append(quantile(sorted_data, q))
778
+
779
+ return deciles_list
780
+
781
+
782
+ def percentile(data: List[Union[int, float]], p: float) -> float:
783
+ """
784
+ Calculate the pth percentile.
785
+
786
+ Args:
787
+ data: List of numeric values
788
+ p: Percentile (0-100)
789
+
790
+ Returns:
791
+ pth percentile value
792
+
793
+ Example:
794
+ >>> percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 75)
795
+ 7.75
796
+ """
797
+ if not 0 <= p <= 100:
798
+ raise ValueError("Percentile must be between 0 and 100")
799
+
800
+ return quantile(data, p / 100)
801
+
802
+
803
+ # Shape and distribution functions
804
+
805
+ def coefficient_of_skewness(data: List[Union[int, float]]) -> float:
806
+ """
807
+ Calculate the coefficient of skewness (standardized skewness).
808
+
809
+ Args:
810
+ data: List of numeric values
811
+
812
+ Returns:
813
+ Coefficient of skewness
814
+
815
+ Example:
816
+ >>> coefficient_of_skewness([1, 2, 3, 4, 5])
817
+ 0.0
818
+ """
819
+ data = _validate_data(data)
820
+ if len(data) < 3:
821
+ raise ValueError("At least 3 data points required")
822
+
823
+ mean_val = arithmetic_mean(data)
824
+ std_val = standard_deviation(data)
825
+
826
+ if std_val == 0:
827
+ return 0.0
828
+
829
+ n = len(data)
830
+ skew_sum = sum(((x - mean_val) / std_val) ** 3 for x in data)
831
+
832
+ # Fisher-Pearson coefficient of skewness
833
+ return (n / ((n - 1) * (n - 2))) * skew_sum
834
+
835
+
836
+ def coefficient_of_kurtosis(data: List[Union[int, float]]) -> float:
837
+ """
838
+ Calculate the coefficient of kurtosis (standardized kurtosis).
839
+
840
+ Args:
841
+ data: List of numeric values
842
+
843
+ Returns:
844
+ Coefficient of kurtosis
845
+
846
+ Example:
847
+ >>> coefficient_of_kurtosis([1, 2, 3, 4, 5])
848
+ -1.2
849
+ """
850
+ data = _validate_data(data)
851
+ if len(data) < 4:
852
+ raise ValueError("At least 4 data points required")
853
+
854
+ mean_val = arithmetic_mean(data)
855
+ std_val = standard_deviation(data)
856
+
857
+ if std_val == 0:
858
+ return 0.0
859
+
860
+ n = len(data)
861
+ kurt_sum = sum(((x - mean_val) / std_val) ** 4 for x in data)
862
+
863
+ # Excess kurtosis
864
+ return (n * (n + 1) / ((n - 1) * (n - 2) * (n - 3))) * kurt_sum - (3 * (n - 1) ** 2 / ((n - 2) * (n - 3)))
865
+
866
+
867
+ def simple_normality_test(data: List[Union[int, float]]) -> bool:
868
+ """
869
+ Simple normality test based on skewness and kurtosis.
870
+
871
+ This is a basic test that checks if skewness and kurtosis are close to normal.
872
+
873
+ Args:
874
+ data: List of numeric values
875
+
876
+ Returns:
877
+ True if data appears approximately normal, False otherwise
878
+
879
+ Example:
880
+ >>> simple_normality_test([1, 2, 3, 4, 5])
881
+ True
882
+ """
883
+ data = _validate_data(data)
884
+ if len(data) < 10:
885
+ return False # Need sufficient data for meaningful test
886
+
887
+ skew = coefficient_of_skewness(data)
888
+ kurt = coefficient_of_kurtosis(data)
889
+
890
+ # Check if skewness and kurtosis are within normal ranges
891
+ # Normal distribution has skewness ≈ 0 and kurtosis ≈ 0
892
+ return abs(skew) < 1.0 and abs(kurt) < 2.0
893
+
894
+
895
+ # Central tendency alternatives
896
+
897
+ def winsorized_median(data: List[Union[int, float]], percent: float = 10.0) -> float:
898
+ """
899
+ Calculate the winsorized median.
900
+
901
+ Args:
902
+ data: List of numeric values
903
+ percent: Percentage of values to winsorize from each end
904
+
905
+ Returns:
906
+ Winsorized median
907
+
908
+ Example:
909
+ >>> winsorized_median([1, 2, 3, 4, 100], percent=20)
910
+ 3.0
911
+ """
912
+ data = _validate_data(data)
913
+ if not 0 <= percent <= 50:
914
+ raise ValueError("Percent must be between 0 and 50")
915
+
916
+ sorted_data = sorted(data)
917
+ n = len(sorted_data)
918
+ k = int(round(n * percent / 100))
919
+
920
+ # Replace k smallest values with (k+1)th smallest
921
+ # Replace k largest values with (n-k)th largest
922
+ winsorized_data = sorted_data.copy()
923
+ if k > 0:
924
+ winsorized_data[:k] = [sorted_data[k]] * k
925
+ winsorized_data[-k:] = [sorted_data[n-k-1]] * k
926
+
927
+ return median(winsorized_data)
928
+
929
+
930
+ def midhinge(data: List[Union[int, float]]) -> float:
931
+ """
932
+ Calculate the midhinge.
933
+
934
+ Midhinge is the average of the lower and upper hinges.
935
+
936
+ Args:
937
+ data: List of numeric values
938
+
939
+ Returns:
940
+ Midhinge value
941
+
942
+ Example:
943
+ >>> midhinge([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
944
+ 5.5
945
+ """
946
+ data = _validate_data(data)
947
+ lower_hinge, upper_hinge = hinges(data)
948
+ return (lower_hinge + upper_hinge) / 2
949
+
950
+
951
+ # Probability and distribution functions
952
+
953
+ def z_score(data: List[Union[int, float]], value: Union[int, float]) -> float:
954
+ """
955
+ Calculate the z-score of a value relative to a dataset.
956
+
957
+ Args:
958
+ data: List of numeric values
959
+ value: Value to calculate z-score for
960
+
961
+ Returns:
962
+ Z-score
963
+
964
+ Example:
965
+ >>> z_score([1, 2, 3, 4, 5], 3)
966
+ 0.0
967
+ """
968
+ data = _validate_data(data)
969
+ mean_val = arithmetic_mean(data)
970
+ std_val = standard_deviation(data)
971
+
972
+ if std_val == 0:
973
+ raise ValueError("Cannot calculate z-score when standard deviation is zero")
974
+
975
+ return (value - mean_val) / std_val
976
+
977
+
978
+ def t_score(data: List[Union[int, float]], value: Union[int, float]) -> float:
979
+ """
980
+ Calculate the t-score of a value relative to a dataset.
981
+
982
+ T-score is similar to z-score but uses sample standard deviation.
983
+
984
+ Args:
985
+ data: List of numeric values
986
+ value: Value to calculate t-score for
987
+
988
+ Returns:
989
+ T-score
990
+
991
+ Example:
992
+ >>> t_score([1, 2, 3, 4, 5], 3)
993
+ 0.0
994
+ """
995
+ data = _validate_data(data)
996
+ mean_val = arithmetic_mean(data)
997
+ std_val = standard_deviation(data) # Sample standard deviation
998
+
999
+ if std_val == 0:
1000
+ raise ValueError("Cannot calculate t-score when standard deviation is zero")
1001
+
1002
+ return (value - mean_val) / std_val
1003
+
1004
+
1005
+ def percentile_from_z_score(z: float) -> float:
1006
+ """
1007
+ Calculate the percentile from a z-score.
1008
+
1009
+ This uses the standard normal distribution.
1010
+
1011
+ Args:
1012
+ z: Z-score
1013
+
1014
+ Returns:
1015
+ Percentile (0-100)
1016
+
1017
+ Example:
1018
+ >>> percentile_from_z_score(0)
1019
+ 50.0
1020
+ >>> percentile_from_z_score(1.96)
1021
+ 97.5
1022
+ """
1023
+ # Use normal distribution approximation
1024
+ # For educational purposes, we'll use a simple approximation
1025
+ # In practice, you'd use scipy.stats.norm.cdf
1026
+
1027
+ # Simple approximation using error function
1028
+ import math
1029
+ percentile = 0.5 * (1 + math.erf(z / math.sqrt(2))) * 100
1030
+ return percentile
1031
+
1032
+
1033
+ def confidence_interval_mean(data: List[Union[int, float]], confidence: float = 0.95) -> Tuple[float, float]:
1034
+ """
1035
+ Calculate confidence interval for the mean.
1036
+
1037
+ Args:
1038
+ data: List of numeric values
1039
+ confidence: Confidence level (0-1)
1040
+
1041
+ Returns:
1042
+ Tuple of (lower_bound, upper_bound)
1043
+
1044
+ Example:
1045
+ >>> confidence_interval_mean([1, 2, 3, 4, 5], 0.95)
1046
+ (1.0367563145369689, 4.963243685463031)
1047
+ """
1048
+ data = _validate_data(data)
1049
+ if not 0 < confidence < 1:
1050
+ raise ValueError("Confidence must be between 0 and 1")
1051
+
1052
+ if len(data) < 2:
1053
+ raise ValueError("At least 2 data points required")
1054
+
1055
+ mean_val = arithmetic_mean(data)
1056
+ std_err = standard_error_mean(data)
1057
+
1058
+ # For educational purposes, using z-distribution approximation
1059
+ # In practice, you'd use t-distribution for small samples
1060
+ if confidence == 0.95:
1061
+ z_critical = 1.96
1062
+ elif confidence == 0.99:
1063
+ z_critical = 2.576
1064
+ elif confidence == 0.90:
1065
+ z_critical = 1.645
1066
+ else:
1067
+ # Simple approximation for other confidence levels
1068
+ z_critical = 2.0 # Conservative estimate
1069
+
1070
+ margin_of_error = z_critical * std_err
1071
+
1072
+ return mean_val - margin_of_error, mean_val + margin_of_error
1073
+
1074
+
1075
+ def confidence_interval_proportion(successes: int, total: int, confidence: float = 0.95) -> Tuple[float, float]:
1076
+ """
1077
+ Calculate confidence interval for a proportion.
1078
+
1079
+ Args:
1080
+ successes: Number of successes
1081
+ total: Total number of trials
1082
+ confidence: Confidence level (0-1)
1083
+
1084
+ Returns:
1085
+ Tuple of (lower_bound, upper_bound)
1086
+
1087
+ Example:
1088
+ >>> confidence_interval_proportion(8, 10, 0.95)
1089
+ (0.4439045090940593, 0.9560954909059407)
1090
+ """
1091
+ if total <= 0:
1092
+ raise ValueError("Total must be positive")
1093
+ if not 0 <= successes <= total:
1094
+ raise ValueError("Successes must be between 0 and total")
1095
+ if not 0 < confidence < 1:
1096
+ raise ValueError("Confidence must be between 0 and 1")
1097
+
1098
+ p_hat = successes / total
1099
+
1100
+ # For educational purposes, using normal approximation
1101
+ # In practice, you'd use Wilson score interval for small samples
1102
+ if confidence == 0.95:
1103
+ z_critical = 1.96
1104
+ elif confidence == 0.99:
1105
+ z_critical = 2.576
1106
+ elif confidence == 0.90:
1107
+ z_critical = 1.645
1108
+ else:
1109
+ z_critical = 2.0 # Conservative estimate
1110
+
1111
+ standard_error = math.sqrt(p_hat * (1 - p_hat) / total)
1112
+ margin_of_error = z_critical * standard_error
1113
+
1114
+ lower_bound = max(0, p_hat - margin_of_error)
1115
+ upper_bound = min(1, p_hat + margin_of_error)
1116
+
1117
+ return lower_bound, upper_bound
1118
+
1119
+
1120
+ # Time series functions
1121
+
1122
+ def moving_average(data: List[Union[int, float]], window: int = 3) -> List[float]:
1123
+ """
1124
+ Calculate simple moving average.
1125
+
1126
+ Args:
1127
+ data: List of numeric values
1128
+ window: Size of the moving window
1129
+
1130
+ Returns:
1131
+ List of moving averages
1132
+
1133
+ Example:
1134
+ >>> moving_average([1, 2, 3, 4, 5], window=3)
1135
+ [2.0, 3.0, 4.0]
1136
+ """
1137
+ return running_average(data, window)
1138
+
1139
+
1140
+ def exponential_smoothing(data: List[Union[int, float]], alpha: float = 0.3) -> List[float]:
1141
+ """
1142
+ Calculate exponential smoothing.
1143
+
1144
+ Args:
1145
+ data: List of numeric values
1146
+ alpha: Smoothing factor (0-1)
1147
+
1148
+ Returns:
1149
+ List of smoothed values
1150
+
1151
+ Example:
1152
+ >>> exponential_smoothing([1, 2, 3, 4, 5], alpha=0.3)
1153
+ [1.0, 1.3, 1.81, 2.467, 3.2269]
1154
+ """
1155
+ data = _validate_data(data)
1156
+ if not 0 <= alpha <= 1:
1157
+ raise ValueError("Alpha must be between 0 and 1")
1158
+
1159
+ if not data:
1160
+ return []
1161
+
1162
+ smoothed = [data[0]] # First value is the same
1163
+
1164
+ for i in range(1, len(data)):
1165
+ next_value = alpha * data[i] + (1 - alpha) * smoothed[i-1]
1166
+ smoothed.append(next_value)
1167
+
1168
+ return smoothed
1169
+
1170
+
1171
+ def seasonal_decomposition_simple(data: List[Union[int, float]], period: int = 4) -> Tuple[List[float], List[float], List[float]]:
1172
+ """
1173
+ Simple seasonal decomposition into trend, seasonal, and residual components.
1174
+
1175
+ This is a basic implementation for educational purposes.
1176
+
1177
+ Args:
1178
+ data: List of numeric values
1179
+ period: Seasonal period length
1180
+
1181
+ Returns:
1182
+ Tuple of (trend, seasonal, residual) components
1183
+
1184
+ Example:
1185
+ >>> trend, seasonal, residual = seasonal_decomposition_simple([1, 2, 3, 4, 5, 6, 7, 8], period=4)
1186
+ """
1187
+ data = _validate_data(data)
1188
+ if period <= 1 or period >= len(data):
1189
+ raise ValueError("Period must be between 2 and data length - 1")
1190
+
1191
+ n = len(data)
1192
+
1193
+ # Simple trend using moving average
1194
+ trend = []
1195
+ for i in range(n):
1196
+ start = max(0, i - period // 2)
1197
+ end = min(n, i + period // 2 + 1)
1198
+ trend.append(arithmetic_mean(data[start:end]))
1199
+
1200
+ # Detrend the data
1201
+ detrended = [data[i] - trend[i] for i in range(n)]
1202
+
1203
+ # Simple seasonal component
1204
+ seasonal = []
1205
+ for i in range(n):
1206
+ season_idx = i % period
1207
+ season_values = [detrended[j] for j in range(season_idx, n, period)]
1208
+ seasonal.append(arithmetic_mean(season_values))
1209
+
1210
+ # Residual component
1211
+ residual = [data[i] - trend[i] - seasonal[i] for i in range(n)]
1212
+
1213
+ return trend, seasonal, residual