-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathtopic9_part1_time_series_python.html
3440 lines (3062 loc) · 290 KB
/
topic9_part1_time_series_python.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
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
<!DOCTYPE html>
<html lang="en" data-content_root="" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.18.1: http://docutils.sourceforge.net/" />
<title>Topic 9. Part 1. Time series analysis in Python — mlcourse.ai</title>
<script data-cfasync="false">
document.documentElement.dataset.mode = localStorage.getItem("mode") || "";
document.documentElement.dataset.theme = localStorage.getItem("theme") || "";
</script>
<!-- Loaded before other Sphinx assets -->
<link href="../../_static/styles/theme.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="../../_static/styles/bootstrap.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="../../_static/styles/pydata-sphinx-theme.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link href="../../_static/vendor/fontawesome/6.5.2/css/all.min.css?digest=dfe6caa3a7d634c4db9b" rel="stylesheet" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="../../_static/vendor/fontawesome/6.5.2/webfonts/fa-solid-900.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="../../_static/vendor/fontawesome/6.5.2/webfonts/fa-brands-400.woff2" />
<link rel="preload" as="font" type="font/woff2" crossorigin href="../../_static/vendor/fontawesome/6.5.2/webfonts/fa-regular-400.woff2" />
<link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
<link rel="stylesheet" href="../../_static/styles/sphinx-book-theme.css?digest=14f4ca6b54d191a8c7657f6c759bf11a5fb86285" type="text/css" />
<link rel="stylesheet" type="text/css" href="../../_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="../../_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="../../_static/mystnb.4510f1fc1dee50b3e5859aac5469c37c29e427902b24a333a5f9fcb2f0b3ac41.css" />
<link rel="stylesheet" type="text/css" href="../../_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="../../_static/design-style.4045f2051d55cab465a707391d5b2007.min.css" />
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="../../_static/scripts/bootstrap.js?digest=dfe6caa3a7d634c4db9b" />
<link rel="preload" as="script" href="../../_static/scripts/pydata-sphinx-theme.js?digest=dfe6caa3a7d634c4db9b" />
<script src="../../_static/vendor/fontawesome/6.5.2/js/all.min.js?digest=dfe6caa3a7d634c4db9b"></script>
<script data-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
<script src="../../_static/jquery.js"></script>
<script src="../../_static/underscore.js"></script>
<script src="../../_static/_sphinx_javascript_frameworks_compat.js"></script>
<script src="../../_static/doctools.js"></script>
<script src="../../_static/clipboard.min.js"></script>
<script src="../../_static/copybutton.js"></script>
<script src="../../_static/scripts/sphinx-book-theme.js?digest=5a5c038af52cf7bc1a1ec88eea08e6366ee68824"></script>
<script>let toggleHintShow = 'Click to show';</script>
<script>let toggleHintHide = 'Click to hide';</script>
<script>let toggleOpenOnPrint = 'true';</script>
<script src="../../_static/togglebutton.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script src="https://c6.patreon.com/becomePatronButton.bundle.js"></script>
<script>var togglebuttonSelector = '.toggle, .admonition.dropdown';</script>
<script src="../../_static/design-tabs.js"></script>
<script async="async" src="https://www.googletagmanager.com/gtag/js?id=G-CN7ZN59CQB"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-CN7ZN59CQB');
</script>
<script>const THEBE_JS_URL = "https://unpkg.com/thebe@0.8.2/lib/index.js"
const thebe_selector = ".thebe,.cell"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output, .cell_output"
</script>
<script async="async" src="../../_static/sphinx-thebe.js"></script>
<script>window.MathJax = {"options": {"processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script>
<script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script type="application/vnd.jupyter.widget-state+json">{"state": {"d248e846783f45419fbef38c5b302bfa": {"model_name": "LayoutModel", "model_module": "@jupyter-widgets/base", "model_module_version": "2.0.0", "state": {"_model_module": "@jupyter-widgets/base", "_model_module_version": "2.0.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border_bottom": null, "border_left": null, "border_right": null, "border_top": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null}}, "cb18c1f247bb42298a5a2abe7910e85a": {"model_name": "ProgressStyleModel", "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "state": {"_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "ProgressStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "StyleView", "bar_color": null, "description_width": ""}}, "25bc623dec6a4e779ee4659759a9531b": {"model_name": "FloatProgressModel", "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "state": {"_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "FloatProgressModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "2.0.0", "_view_name": "ProgressView", "bar_style": "success", "description": "", "description_allow_html": false, "layout": "IPY_MODEL_d248e846783f45419fbef38c5b302bfa", "max": 36.0, "min": 0.0, "orientation": "horizontal", "style": "IPY_MODEL_cb18c1f247bb42298a5a2abe7910e85a", "tabbable": null, "tooltip": null, "value": 36.0}}, "fa13a97473154d97bcae528e4dd9aff3": {"model_name": "LayoutModel", "model_module": "@jupyter-widgets/base", "model_module_version": "2.0.0", "state": {"_model_module": "@jupyter-widgets/base", "_model_module_version": "2.0.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border_bottom": null, "border_left": null, "border_right": null, "border_top": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null}}, "3c343ec4a01f40789c8b4517e804c7ed": {"model_name": "HTMLStyleModel", "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "state": {"_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HTMLStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "StyleView", "background": null, "description_width": "", "font_size": null, "text_color": null}}, "6014cd9014284e5da14d93d8b29296f8": {"model_name": "HTMLModel", "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "state": {"_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "2.0.0", "_view_name": "HTMLView", "description": "", "description_allow_html": false, "layout": "IPY_MODEL_fa13a97473154d97bcae528e4dd9aff3", "placeholder": "\u200b", "style": "IPY_MODEL_3c343ec4a01f40789c8b4517e804c7ed", "tabbable": null, "tooltip": null, "value": "100%"}}, "e7ba76851bc94b3fb58c9081abf74bf3": {"model_name": "LayoutModel", "model_module": "@jupyter-widgets/base", "model_module_version": "2.0.0", "state": {"_model_module": "@jupyter-widgets/base", "_model_module_version": "2.0.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border_bottom": null, "border_left": null, "border_right": null, "border_top": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null}}, "80f12468ade24f97946291e07a621228": {"model_name": "HTMLStyleModel", "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "state": {"_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HTMLStyleModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "StyleView", "background": null, "description_width": "", "font_size": null, "text_color": null}}, "0ad5efc03f4142a7a90d189ad015e356": {"model_name": "HTMLModel", "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "state": {"_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HTMLModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "2.0.0", "_view_name": "HTMLView", "description": "", "description_allow_html": false, "layout": "IPY_MODEL_e7ba76851bc94b3fb58c9081abf74bf3", "placeholder": "\u200b", "style": "IPY_MODEL_80f12468ade24f97946291e07a621228", "tabbable": null, "tooltip": null, "value": "\u200736/36\u2007[00:37<00:00,\u2007\u20072.22s/it]"}}, "7df24838b221472f9b97f52370603b10": {"model_name": "LayoutModel", "model_module": "@jupyter-widgets/base", "model_module_version": "2.0.0", "state": {"_model_module": "@jupyter-widgets/base", "_model_module_version": "2.0.0", "_model_name": "LayoutModel", "_view_count": null, "_view_module": "@jupyter-widgets/base", "_view_module_version": "2.0.0", "_view_name": "LayoutView", "align_content": null, "align_items": null, "align_self": null, "border_bottom": null, "border_left": null, "border_right": null, "border_top": null, "bottom": null, "display": null, "flex": null, "flex_flow": null, "grid_area": null, "grid_auto_columns": null, "grid_auto_flow": null, "grid_auto_rows": null, "grid_column": null, "grid_gap": null, "grid_row": null, "grid_template_areas": null, "grid_template_columns": null, "grid_template_rows": null, "height": null, "justify_content": null, "justify_items": null, "left": null, "margin": null, "max_height": null, "max_width": null, "min_height": null, "min_width": null, "object_fit": null, "object_position": null, "order": null, "overflow": null, "padding": null, "right": null, "top": null, "visibility": null, "width": null}}, "36b08147a6d949bcb67d8924b46fb4ca": {"model_name": "HBoxModel", "model_module": "@jupyter-widgets/controls", "model_module_version": "2.0.0", "state": {"_dom_classes": [], "_model_module": "@jupyter-widgets/controls", "_model_module_version": "2.0.0", "_model_name": "HBoxModel", "_view_count": null, "_view_module": "@jupyter-widgets/controls", "_view_module_version": "2.0.0", "_view_name": "HBoxView", "box_style": "", "children": ["IPY_MODEL_6014cd9014284e5da14d93d8b29296f8", "IPY_MODEL_25bc623dec6a4e779ee4659759a9531b", "IPY_MODEL_0ad5efc03f4142a7a90d189ad015e356"], "layout": "IPY_MODEL_7df24838b221472f9b97f52370603b10", "tabbable": null, "tooltip": null}}}, "version_major": 2, "version_minor": 0}</script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script crossorigin="anonymous" data-jupyter-widgets-cdn="https://cdn.jsdelivr.net/npm/" src="https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@1.0.6/dist/embed-amd.js"></script>
<script>DOCUMENTATION_OPTIONS.pagename = 'book/topic09/topic9_part1_time_series_python';</script>
<link rel="shortcut icon" href="../../_static/favicon.ico"/>
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
<link rel="next" title="Topic 9. Time series analysis in Python. Part 2. Predicting the future with Facebook Prophet" href="topic9_part2_facebook_prophet.html" />
<link rel="prev" title="Topic 9. Time Series Analysis with Python" href="topic09_intro.html" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="docsearch:language" content="en"/>
</head>
<body data-bs-spy="scroll" data-bs-target=".bd-toc-nav" data-offset="180" data-bs-root-margin="0px 0px -60%" data-default-mode="">
<div id="pst-skip-link" class="skip-link d-print-none"><a href="#main-content">Skip to main content</a></div>
<div id="pst-scroll-pixel-helper"></div>
<button type="button" class="btn rounded-pill" id="pst-back-to-top">
<i class="fa-solid fa-arrow-up"></i>Back to top</button>
<input type="checkbox"
class="sidebar-toggle"
id="pst-primary-sidebar-checkbox"/>
<label class="overlay overlay-primary" for="pst-primary-sidebar-checkbox"></label>
<input type="checkbox"
class="sidebar-toggle"
id="pst-secondary-sidebar-checkbox"/>
<label class="overlay overlay-secondary" for="pst-secondary-sidebar-checkbox"></label>
<div class="search-button__wrapper">
<div class="search-button__overlay"></div>
<div class="search-button__search-container">
<form class="bd-search d-flex align-items-center"
action="../../search.html"
method="get">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="search"
class="form-control"
name="q"
id="search-input"
placeholder="Search this book..."
aria-label="Search this book..."
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"/>
<span class="search-button__kbd-shortcut"><kbd class="kbd-shortcut__modifier">Ctrl</kbd>+<kbd>K</kbd></span>
</form></div>
</div>
<div class="pst-async-banner-revealer d-none">
<aside id="bd-header-version-warning" class="d-none d-print-none" aria-label="Version warning"></aside>
</div>
<header class="bd-header navbar navbar-expand-lg bd-navbar d-print-none">
</header>
<div class="bd-container">
<div class="bd-container__inner bd-page-width">
<div class="bd-sidebar-primary bd-sidebar">
<div class="sidebar-header-items sidebar-primary__section">
</div>
<div class="sidebar-primary-items__start sidebar-primary__section">
<div class="sidebar-primary-item">
<a class="navbar-brand logo" href="../index.html">
<img src="../../_static/mlcourse_ai_logo.jpg" class="logo__image only-light" alt="mlcourse.ai - Home"/>
<script>document.write(`<img src="../../_static/mlcourse_ai_logo.jpg" class="logo__image only-dark" alt="mlcourse.ai - Home"/>`);</script>
</a></div>
<div class="sidebar-primary-item"><nav class="bd-links" id="bd-docs-nav" aria-label="Main">
<div class="bd-toc-item navbar-nav active">
<ul class="nav bd-sidenav bd-sidenav__home-link">
<li class="toctree-l1">
<a class="reference internal" href="../index.html">
Intro
</a>
</li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Prerequisites</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../prereqs/python.html">Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="../prereqs/math.html">Math</a></li>
<li class="toctree-l1"><a class="reference internal" href="../prereqs/software_devops.html">Software & DevOps</a></li>
<li class="toctree-l1"><a class="reference internal" href="../prereqs/docker.html">Docker</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 1</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic01/topic01_intro.html">Topic 1 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic01/topic01_pandas_data_analysis.html">Exploratory data analysis with Pandas</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic01/videolecture01.html">Videolecture 1</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic01/assignment01_pandas_uci_adult.html">Demo Assignment 1 Task</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic01/assignment01_pandas_uci_adult_solution.html">Demo Assignment 1 Solution</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic01/bonus_assignment01_pandas_olympics.html">Bonus Assignment 1</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 2</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic02/topic02_intro.html">Topic 2 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic02/topic02_visual_data_analysis.html">Visual Data Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic02/topic02_additional_seaborn_matplotlib_plotly.html">Seaborn, Matplotlib, Plotly</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic02/videolecture02.html">Videolecture 2</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic02/assignment02_analyzing_cardiovascular_desease_data.html">Demo Assignment 2 Task</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic02/assignment02_analyzing_cardiovascular_desease_data_solution.html">Demo Assignment 2 Solution</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic02/bonus_assignment02_visual_analysis.html">Bonus Assignment 2</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 3</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic03/topic03_intro.html">Topic 3 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic03/topic03_decision_trees_kNN.html">Classification, Decision Trees & k Nearest Neighbors</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic03/videolecture03.html">Videolecture 3</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic03/assignment03_decision_trees.html">Demo Assignment 3 Task</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic03/assignment03_decision_trees_solution.html">Demo Assignment 3 Solution</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic03/bonus_assignment03_decision_trees.html">Bonus Assignment 3</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 4</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic04/topic04_intro.html">Topic 4 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/topic4_linear_models_part1_mse_likelihood_bias_variance.html">Ordinary Least Squares</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/topic4_linear_models_part2_logit_likelihood_learning.html">Linear classification</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/topic4_linear_models_part3_regul_example.html">An illustrative example of logistic regression regularization</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/topic4_linear_models_part4_good_bad_logit_movie_reviews_XOR.html">When logistic regression is good and when it is not</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/topic4_linear_models_part5_valid_learning_curves.html">Validation and learning curves</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/videolecture04.html">Videolecture 4</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/assignment04_regression_wine.html">Demo Assignment 4 Task</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/assignment04_regression_wine_solution.html">Demo Assignment 4 Solution</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic04/bonus_assignment04_alice_baselines.html">Bonus Assignment 4</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 5</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic05/topic05_intro.html">Topic 5 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic05/topic5_part1_bagging.html">Bagging</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic05/topic5_part2_random_forest.html">Random Forest</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic05/topic5_part3_feature_importance.html">Feature importance</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic05/videolecture05.html">Videolecture 5</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic05/assignment05_logit_rf_credit_scoring.html">Demo Assignment 5</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic05/assignment05_logit_rf_credit_scoring_solution.html">Demo Assignment 5 Solution</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic05/bonus_assignment05_logreg_rf.html">Bonus Assignment 5</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 6</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic06/topic06_intro.html">Topic 6 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic06/topic6_feature_engineering_feature_selection.html">Feature engineering & feature selection</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic06/demo_assignment06.html">Demo Assignment 6 Task</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic06/bonus_assignment06.html">Bonus Assignment 6</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 7</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic07/topic07_intro.html">Topic 7 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic07/topic7_pca_clustering.html">Unsupervised learning</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic07/videolecture07.html">Videolecture 7</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic07/assignment07_unsupervised_learning.html">Demo Assignment 7</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic07/assignment07_unsupervised_learning_solution.html">Demo Assignment 7 Solution</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic07/bonus_assignment07.html">Bonus Assignment 7</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 8</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic08/topic08_intro.html">Topic 8 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic08/topic08_sgd_hashing_vowpal_wabbit.html">Vowpal Wabbit: Learning with Gigabytes of Data</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic08/videolecture08.html">Videolecture 8</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic08/assignment08_implement_sgd_regressor.html">Demo Assignment 8</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic08/assignment08_implement_sgd_regressor_solution.html">Demo Assignment 8 Solution</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic08/bonus_assignment08.html">Bonus Assignment 8</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 9</span></p>
<ul class="current nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="topic09_intro.html">Topic 9 Intro</a></li>
<li class="toctree-l1 current active"><a class="current reference internal" href="#">Topic 9. Part 1. Time series analysis in Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="topic9_part2_facebook_prophet.html">Predicting the future with Facebook Prophet</a></li>
<li class="toctree-l1"><a class="reference internal" href="videolecture09.html">Videolecture 9</a></li>
<li class="toctree-l1"><a class="reference internal" href="assignment09_time_series.html">Demo Assignment 9</a></li>
<li class="toctree-l1"><a class="reference internal" href="assignment09_time_series_solution.html">Demo Assignment 9 Solution</a></li>
<li class="toctree-l1"><a class="reference internal" href="bonus_assignment09.html">Bonus Assignment 9</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">Topic 10</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../topic10/topic10_intro.html">Topic 10 Intro</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic10/topic10_gradient_boosting.html">Gradient boosting</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic10/videolecture10.html">Videolecture 10</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic10/assignment10_flight_delays_kaggle.html">Demo Assignment 10</a></li>
<li class="toctree-l1"><a class="reference internal" href="../topic10/bonus_assignment10.html">Bonus Assignment 10</a></li>
</ul>
<p aria-level="2" class="caption" role="heading"><span class="caption-text">About the course</span></p>
<ul class="nav bd-sidenav">
<li class="toctree-l1"><a class="reference internal" href="../extra/tutorials.html">Tutorials</a></li>
<li class="toctree-l1"><a class="reference internal" href="../extra/rating.html">Rating</a></li>
<li class="toctree-l1"><a class="reference internal" href="../extra/resources.html">Resources</a></li>
<li class="toctree-l1"><a class="reference internal" href="../extra/contributors.html">Contributors</a></li>
</ul>
</div>
</nav></div>
</div>
<div class="sidebar-primary-items__end sidebar-primary__section">
</div>
<div id="rtd-footer-container"></div>
</div>
<main id="main-content" class="bd-main" role="main">
<div class="sbt-scroll-pixel-helper"></div>
<div class="bd-content">
<div class="bd-article-container">
<div class="bd-header-article d-print-none">
<div class="header-article-items header-article__inner">
<div class="header-article-items__start">
<div class="header-article-item"><label class="sidebar-toggle primary-toggle btn btn-sm" for="__primary" title="Toggle primary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-bars"></span>
</label></div>
</div>
<div class="header-article-items__end">
<div class="header-article-item">
<div class="article-header-buttons">
<div class="dropdown dropdown-source-buttons">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Source repositories">
<i class="fab fa-github"></i>
</button>
<ul class="dropdown-menu">
<li><a href="https://github.com/Yorko/mlcourse.ai" target="_blank"
class="btn btn-sm btn-source-repository-button dropdown-item"
title="Source repository"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fab fa-github"></i>
</span>
<span class="btn__text-container">Repository</span>
</a>
</li>
<li><a href="https://github.com/Yorko/mlcourse.ai/edit/main/mlcourse_ai_jupyter_book/book/topic09/topic9_part1_time_series_python.md" target="_blank"
class="btn btn-sm btn-source-edit-button dropdown-item"
title="Suggest edit"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-pencil-alt"></i>
</span>
<span class="btn__text-container">Suggest edit</span>
</a>
</li>
<li><a href="https://github.com/Yorko/mlcourse.ai/issues/new?title=Issue%20on%20page%20%2Fbook/topic09/topic9_part1_time_series_python.html&body=Your%20issue%20content%20here." target="_blank"
class="btn btn-sm btn-source-issues-button dropdown-item"
title="Open an issue"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-lightbulb"></i>
</span>
<span class="btn__text-container">Open issue</span>
</a>
</li>
</ul>
</div>
<div class="dropdown dropdown-download-buttons">
<button class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Download this page">
<i class="fas fa-download"></i>
</button>
<ul class="dropdown-menu">
<li><a href="../../_sources/book/topic09/topic9_part1_time_series_python.md" target="_blank"
class="btn btn-sm btn-download-source-button dropdown-item"
title="Download source file"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file"></i>
</span>
<span class="btn__text-container">.md</span>
</a>
</li>
<li>
<button onclick="window.print()"
class="btn btn-sm btn-download-pdf-button dropdown-item"
title="Print to PDF"
data-bs-placement="left" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-file-pdf"></i>
</span>
<span class="btn__text-container">.pdf</span>
</button>
</li>
</ul>
</div>
<button onclick="toggleFullScreen()"
class="btn btn-sm btn-fullscreen-button"
title="Fullscreen mode"
data-bs-placement="bottom" data-bs-toggle="tooltip"
>
<span class="btn__icon-container">
<i class="fas fa-expand"></i>
</span>
</button>
<script>
document.write(`
<button class="btn btn-sm nav-link pst-navbar-icon theme-switch-button" title="light/dark" aria-label="light/dark" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="theme-switch fa-solid fa-sun fa-lg" data-mode="light"></i>
<i class="theme-switch fa-solid fa-moon fa-lg" data-mode="dark"></i>
<i class="theme-switch fa-solid fa-circle-half-stroke fa-lg" data-mode="auto"></i>
</button>
`);
</script>
<script>
document.write(`
<button class="btn btn-sm pst-navbar-icon search-button search-button__button" title="Search" aria-label="Search" data-bs-placement="bottom" data-bs-toggle="tooltip">
<i class="fa-solid fa-magnifying-glass fa-lg"></i>
</button>
`);
</script>
<label class="sidebar-toggle secondary-toggle btn btn-sm" for="__secondary"title="Toggle secondary sidebar" data-bs-placement="bottom" data-bs-toggle="tooltip">
<span class="fa-solid fa-list"></span>
</label>
</div></div>
</div>
</div>
</div>
<div id="jb-print-docs-body" class="onlyprint">
<h1>Topic 9. Part 1. Time series analysis in Python</h1>
<!-- Table of contents -->
<div id="print-main-content">
<div id="jb-print-toc">
<div>
<h2> Contents </h2>
</div>
<nav aria-label="Page">
<ul class="visible nav section-nav flex-column">
<li class="toc-h1 nav-item toc-entry"><a class="reference internal nav-link" href="#">Topic 9. Part 1. Time series analysis in Python</a><ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#article-outline">Article outline</a></li>
</ul>
</li>
<li class="toc-h1 nav-item toc-entry"><a class="reference internal nav-link" href="#introduction">Introduction</a><ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#forecast-quality-metrics">Forecast quality metrics</a></li>
</ul>
</li>
<li class="toc-h1 nav-item toc-entry"><a class="reference internal nav-link" href="#move-smoothe-evaluate">Move, smoothe, evaluate</a><ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#exponential-smoothing">Exponential smoothing</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#double-exponential-smoothing">Double exponential smoothing</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#triple-exponential-smoothing-a-k-a-holt-winters">Triple exponential smoothing a.k.a. Holt-Winters</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#time-series-cross-validation">Time series cross validation</a></li>
</ul>
</li>
<li class="toc-h1 nav-item toc-entry"><a class="reference internal nav-link" href="#econometric-approach">Econometric approach</a><ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#stationarity">Stationarity</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#getting-rid-of-non-stationarity-and-building-sarima">Getting rid of non-stationarity and building SARIMA</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#arima-family-crash-course">ARIMA-family Crash-Course</a></li>
</ul>
</li>
<li class="toc-h1 nav-item toc-entry"><a class="reference internal nav-link" href="#linear-and-not-only-models-for-time-series">Linear (and not only) models for time series</a><ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#feature-extraction">Feature extraction</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#time-series-lags">Time series lags</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#target-encoding">Target encoding</a></li>
<li class="toc-h2 nav-item toc-entry"><a class="reference internal nav-link" href="#regularization-and-feature-selection">Regularization and feature selection</a></li>
</ul>
</li>
<li class="toc-h1 nav-item toc-entry"><a class="reference internal nav-link" href="#boosting">Boosting</a></li>
<li class="toc-h1 nav-item toc-entry"><a class="reference internal nav-link" href="#conclusion">Conclusion</a></li>
<li class="toc-h1 nav-item toc-entry"><a class="reference internal nav-link" href="#useful-resources">Useful resources</a></li>
</ul>
</nav>
</div>
</div>
</div>
<div id="searchbox"></div>
<article class="bd-article">
<section class="tex2jax_ignore mathjax_ignore" id="topic-9-part-1-time-series-analysis-in-python">
<span id="topic09-part1"></span><h1><a class="toc-backref" href="#id1" role="doc-backlink">Topic 9. Part 1. Time series analysis in Python</a><a class="headerlink" href="#topic-9-part-1-time-series-analysis-in-python" title="Permalink to this heading">#</a></h1>
<img src="https://habrastorage.org/webt/ia/m9/zk/iam9zkyzqebnf_okxipihkgjwnw.jpeg" />
<p><strong><center><a class="reference external" href="https://mlcourse.ai">mlcourse.ai</a> – Open Machine Learning Course</strong> </center><br></p>
<p>Author: <a class="reference external" href="https://github.com/DmitrySerg">Dmitriy Sergeyev</a>, Data Scientist @ Zeptolab, lecturer in the Center of Mathematical Finance in MSU. Translated by: @borowis. This material is subject to the terms and conditions of the <a class="reference external" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons CC BY-NC-SA 4.0</a> license. Free use is permitted for any non-commercial purpose.</p>
<p>We continue our open machine learning course with a new article on time series.</p>
<p>Let’s take a look at how to work with time series in Python: what methods and models we can use for prediction, what double and triple exponential smoothing is, what to do if stationarity is not your favorite thing, how to build SARIMA and stay alive, how to make predictions using xgboost… In addition, all of this will be applied to (harsh) real world examples.</p>
<section id="article-outline">
<h2><a class="toc-backref" href="#id2" role="doc-backlink">Article outline</a><a class="headerlink" href="#article-outline" title="Permalink to this heading">#</a></h2>
<nav class="contents" id="contents">
<p class="topic-title">Contents</p>
<ul class="simple">
<li><p><a class="reference internal" href="#topic-9-part-1-time-series-analysis-in-python" id="id1">Topic 9. Part 1. Time series analysis in Python</a></p>
<ul>
<li><p><a class="reference internal" href="#article-outline" id="id2">Article outline</a></p></li>
</ul>
</li>
<li><p><a class="reference internal" href="#introduction" id="id3">Introduction</a></p>
<ul>
<li><p><a class="reference internal" href="#forecast-quality-metrics" id="id4">Forecast quality metrics</a></p></li>
</ul>
</li>
<li><p><a class="reference internal" href="#move-smoothe-evaluate" id="id5">Move, smoothe, evaluate</a></p>
<ul>
<li><p><a class="reference internal" href="#exponential-smoothing" id="id6">Exponential smoothing</a></p></li>
<li><p><a class="reference internal" href="#double-exponential-smoothing" id="id7">Double exponential smoothing</a></p></li>
<li><p><a class="reference internal" href="#triple-exponential-smoothing-a-k-a-holt-winters" id="id8">Triple exponential smoothing a.k.a. Holt-Winters</a></p></li>
<li><p><a class="reference internal" href="#time-series-cross-validation" id="id9">Time series cross validation</a></p></li>
</ul>
</li>
<li><p><a class="reference internal" href="#econometric-approach" id="id10">Econometric approach</a></p>
<ul>
<li><p><a class="reference internal" href="#stationarity" id="id11">Stationarity</a></p></li>
<li><p><a class="reference internal" href="#getting-rid-of-non-stationarity-and-building-sarima" id="id12">Getting rid of non-stationarity and building SARIMA</a></p></li>
<li><p><a class="reference internal" href="#arima-family-crash-course" id="id13">ARIMA-family Crash-Course</a></p></li>
</ul>
</li>
<li><p><a class="reference internal" href="#linear-and-not-only-models-for-time-series" id="id14">Linear (and not only) models for time series</a></p>
<ul>
<li><p><a class="reference internal" href="#feature-extraction" id="id15">Feature extraction</a></p></li>
<li><p><a class="reference internal" href="#time-series-lags" id="id16">Time series lags</a></p></li>
<li><p><a class="reference internal" href="#target-encoding" id="id17">Target encoding</a></p></li>
<li><p><a class="reference internal" href="#regularization-and-feature-selection" id="id18">Regularization and feature selection</a></p></li>
</ul>
</li>
<li><p><a class="reference internal" href="#boosting" id="id19">Boosting</a></p></li>
<li><p><a class="reference internal" href="#conclusion" id="id20">Conclusion</a></p></li>
<li><p><a class="reference internal" href="#useful-resources" id="id21">Useful resources</a></p></li>
</ul>
</nav>
<p>In my day-to-day job, I encounter time-series related tasks almost every day. The most frequent questions asked are the following: what will happen with our metrics in the next day/week/month/etc., how many users will install our app, how much time will they spend online, how many actions will users complete, and so on. We can approach these prediction tasks using different methods depending on the required quality of the prediction, length of the forecast period, and, of course, the time within which we have to choose features and tune parameters to achieve desired results.</p>
</section>
</section>
<section class="tex2jax_ignore mathjax_ignore" id="introduction">
<h1><a class="toc-backref" href="#id3" role="doc-backlink">Introduction</a><a class="headerlink" href="#introduction" title="Permalink to this heading">#</a></h1>
<p>We begin with a simple <a class="reference external" href="https://en.wikipedia.org/wiki/Time_series">definition</a> of time series:</p>
<blockquote>
<div><p><em>Time series</em> is a series of data points indexed (or listed or graphed) in time order.</p>
</div></blockquote>
<p>Therefore, the data is organized by relatively deterministic timestamps, and may, compared to random sample data, contain additional information that we can extract.</p>
<p>Let’s import some libraries. First, we will need the <a class="reference external" href="http://statsmodels.sourceforge.net/stable/">statsmodels</a> library, which has many statistical modeling functions, including time series. For R aficionados who had to move to Python, <code class="docutils literal notranslate"><span class="pre">statsmodels</span></code> will definitely look more familiar since it supports model definitions like ‘Wage ~ Age + Education’.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">matplotlib.pyplot</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">plt</span> <span class="c1"># plots</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">numpy</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">np</span> <span class="c1"># vectors and matrices</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">pandas</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">pd</span> <span class="c1"># tables and data manipulations</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">seaborn</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">sns</span> <span class="c1"># more plots</span>
<span class="n">sns</span><span class="o">.</span><span class="n">set</span><span class="p">()</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">warnings</span>
<span class="kn">from</span><span class="w"> </span><span class="nn">itertools</span><span class="w"> </span><span class="kn">import</span> <span class="n">product</span> <span class="c1"># some useful functions</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">scipy.stats</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">scs</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">statsmodels.api</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">sm</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">statsmodels.formula.api</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">smf</span> <span class="c1"># statistics and econometrics</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">statsmodels.tsa.api</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">smt</span>
<span class="kn">from</span><span class="w"> </span><span class="nn">dateutil.relativedelta</span><span class="w"> </span><span class="kn">import</span> \
<span class="n">relativedelta</span> <span class="c1"># working with dates with style</span>
<span class="kn">from</span><span class="w"> </span><span class="nn">scipy.optimize</span><span class="w"> </span><span class="kn">import</span> <span class="n">minimize</span> <span class="c1"># for function minimization</span>
<span class="kn">from</span><span class="w"> </span><span class="nn">tqdm.notebook</span><span class="w"> </span><span class="kn">import</span> <span class="n">tqdm</span>
<span class="n">warnings</span><span class="o">.</span><span class="n">filterwarnings</span><span class="p">(</span><span class="s2">"ignore"</span><span class="p">)</span> <span class="c1"># `do not disturbe` mode</span>
<span class="o">%</span><span class="k">matplotlib</span> inline
<span class="o">%</span><span class="k">config</span> InlineBackend.figure_format = 'retina'
</pre></div>
</div>
</div>
</div>
<p>As an example, let’s look at real mobile game data. Specifically, we will look into ads watched per hour and in-game currency spend per day:</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># for Jupyter-book, we copy data from GitHub, locally, to save Internet traffic,</span>
<span class="c1"># you can specify the data/ folder from the root of your cloned</span>
<span class="c1"># https://github.com/Yorko/mlcourse.ai repo, to save Internet traffic</span>
<span class="n">DATA_PATH</span> <span class="o">=</span> <span class="s2">"https://raw.githubusercontent.com/Yorko/mlcourse.ai/main/data/"</span>
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">ads</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="n">DATA_PATH</span> <span class="o">+</span> <span class="s2">"ads.csv"</span><span class="p">,</span> <span class="n">index_col</span><span class="o">=</span><span class="p">[</span><span class="s2">"Time"</span><span class="p">],</span> <span class="n">parse_dates</span><span class="o">=</span><span class="p">[</span><span class="s2">"Time"</span><span class="p">])</span>
<span class="n">currency</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span>
<span class="n">DATA_PATH</span> <span class="o">+</span> <span class="s2">"currency.csv"</span><span class="p">,</span> <span class="n">index_col</span><span class="o">=</span><span class="p">[</span><span class="s2">"Time"</span><span class="p">],</span> <span class="n">parse_dates</span><span class="o">=</span><span class="p">[</span><span class="s2">"Time"</span><span class="p">]</span>
<span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">8</span><span class="p">))</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">ads</span><span class="o">.</span><span class="n">Ads</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">title</span><span class="p">(</span><span class="s2">"Ads watched (hourly data)"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../_images/5c117620b68fc3ed52a57e0adbc5cee00fbaa84cd4d265a46c16ef7dc849cbdb.png" src="../../_images/5c117620b68fc3ed52a57e0adbc5cee00fbaa84cd4d265a46c16ef7dc849cbdb.png" />
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">15</span><span class="p">,</span> <span class="mi">7</span><span class="p">))</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">currency</span><span class="o">.</span><span class="n">GEMS_GEMS_SPENT</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">title</span><span class="p">(</span><span class="s2">"In-game currency spent (daily data)"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../_images/f9ef4b3bbd3729d337b344d93441e24efe1fe88df8837e48f49df10f5caf2a06.png" src="../../_images/f9ef4b3bbd3729d337b344d93441e24efe1fe88df8837e48f49df10f5caf2a06.png" />
</div>
</div>
<section id="forecast-quality-metrics">
<h2><a class="toc-backref" href="#id4" role="doc-backlink">Forecast quality metrics</a><a class="headerlink" href="#forecast-quality-metrics" title="Permalink to this heading">#</a></h2>
<p>Before we begin forecasting, let’s understand how to measure the quality of our predictions and take a look at the most commonly used metrics.</p>
<ul class="simple">
<li><p><a class="reference external" href="http://scikit-learn.org/stable/modules/model_evaluation.html#r2-score-the-coefficient-of-determination">R squared</a>: coefficient of determination (in econometrics, this can be interpreted as the percentage of variance explained by the model), <span class="math notranslate nohighlight">\((-\infty, 1]\)</span></p></li>
</ul>
<p><span class="math notranslate nohighlight">\(R^2 = 1 - \frac{SS_{res}}{SS_{tot}}\)</span></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">sklearn</span><span class="o">.</span><span class="n">metrics</span><span class="o">.</span><span class="n">r2_score</span>
</pre></div>
</div>
<hr class="docutils" />
<ul class="simple">
<li><p><a class="reference external" href="http://scikit-learn.org/stable/modules/model_evaluation.html#mean-absolute-error">Mean Absolute Error</a>: this is an interpretable metric because it has the same unit of measurement as the initial series, <span class="math notranslate nohighlight">\([0, +\infty)\)</span></p></li>
</ul>
<p><span class="math notranslate nohighlight">\(MAE = \frac{\sum\limits_{i=1}^{n} |y_i - \hat{y}_i|}{n}\)</span></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">sklearn</span><span class="o">.</span><span class="n">metrics</span><span class="o">.</span><span class="n">mean_absolute_error</span>
</pre></div>
</div>
<hr class="docutils" />
<ul class="simple">
<li><p><a class="reference external" href="http://scikit-learn.org/stable/modules/model_evaluation.html#median-absolute-error">Median Absolute Error</a>: again, an interpretable metric that is particularly interesting because it is robust to outliers, <span class="math notranslate nohighlight">\([0, +\infty)\)</span></p></li>
</ul>
<p><span class="math notranslate nohighlight">\(MedAE = median(|y_1 - \hat{y}_1|, ... , |y_n - \hat{y}_n|)\)</span></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">sklearn</span><span class="o">.</span><span class="n">metrics</span><span class="o">.</span><span class="n">median_absolute_error</span>
</pre></div>
</div>
<hr class="docutils" />
<ul class="simple">
<li><p><a class="reference external" href="http://scikit-learn.org/stable/modules/model_evaluation.html#mean-squared-error">Mean Squared Error</a>: the most commonly used metric that gives a higher penalty to large errors and vice versa, <span class="math notranslate nohighlight">\([0, +\infty)\)</span></p></li>
</ul>
<p><span class="math notranslate nohighlight">\(MSE = \frac{1}{n}\sum\limits_{i=1}^{n} (y_i - \hat{y}_i)^2\)</span></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">sklearn</span><span class="o">.</span><span class="n">metrics</span><span class="o">.</span><span class="n">mean_squared_error</span>
</pre></div>
</div>
<hr class="docutils" />
<ul class="simple">
<li><p><a class="reference external" href="http://scikit-learn.org/stable/modules/model_evaluation.html#mean-squared-logarithmic-error">Mean Squared Logarithmic Error</a>: practically, this is the same as MSE, but we take the logarithm of the series. As a result, we give more weight to small mistakes as well. This is usually used when the data has exponential trends, <span class="math notranslate nohighlight">\([0, +\infty)\)</span></p></li>
</ul>
<p><span class="math notranslate nohighlight">\(MSLE = \frac{1}{n}\sum\limits_{i=1}^{n} (log(1+y_i) - log(1+\hat{y}_i))^2\)</span></p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">sklearn</span><span class="o">.</span><span class="n">metrics</span><span class="o">.</span><span class="n">mean_squared_log_error</span>
</pre></div>
</div>
<hr class="docutils" />
<ul class="simple">
<li><p>Mean Absolute Percentage Error: this is the same as MAE but is computed as a percentage, which is very convenient when you want to explain the quality of the model to management, <span class="math notranslate nohighlight">\([0, +\infty)\)</span></p></li>
</ul>
<p><span class="math notranslate nohighlight">\(MAPE = \frac{100}{n}\sum\limits_{i=1}^{n} \frac{|y_i - \hat{y}_i|}{y_i}\)</span></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">mean_absolute_percentage_error</span><span class="p">(</span><span class="n">y_true</span><span class="p">,</span> <span class="n">y_pred</span><span class="p">):</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">((</span><span class="n">y_true</span> <span class="o">-</span> <span class="n">y_pred</span><span class="p">)</span> <span class="o">/</span> <span class="n">y_true</span><span class="p">))</span> <span class="o">*</span> <span class="mi">100</span>
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Importing everything from above</span>
<span class="kn">from</span><span class="w"> </span><span class="nn">sklearn.metrics</span><span class="w"> </span><span class="kn">import</span> <span class="p">(</span><span class="n">mean_absolute_error</span><span class="p">,</span> <span class="n">mean_squared_error</span><span class="p">,</span>
<span class="n">mean_squared_log_error</span><span class="p">,</span> <span class="n">median_absolute_error</span><span class="p">,</span>
<span class="n">r2_score</span><span class="p">)</span>
<span class="k">def</span><span class="w"> </span><span class="nf">mean_absolute_percentage_error</span><span class="p">(</span><span class="n">y_true</span><span class="p">,</span> <span class="n">y_pred</span><span class="p">):</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">abs</span><span class="p">((</span><span class="n">y_true</span> <span class="o">-</span> <span class="n">y_pred</span><span class="p">)</span> <span class="o">/</span> <span class="n">y_true</span><span class="p">))</span> <span class="o">*</span> <span class="mi">100</span>
</pre></div>
</div>
</div>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>You should be very careful with MAPE, MSLE and other metrics that are poorly defined around <span class="math notranslate nohighlight">\(y=0\)</span>. Formally, MAPE is not defined for any <span class="math notranslate nohighlight">\(y_i = 0\)</span>. In practice, these metric can “explode” even for small values of <span class="math notranslate nohighlight">\(y_i\)</span> around 0. The ways to go around this limitation should be clear for the end user. For example, simply ignoring actual values <span class="math notranslate nohighlight">\(y_i = 0\)</span> is indeed a workaround but a bad one: thus, we’d ignore those cases where the prediction is high (<span class="math notranslate nohighlight">\(\hat{y}_i \gg 1\)</span>) and the actual value is 0 (<span class="math notranslate nohighlight">\(y_i = 0\)</span>). More of this is <a class="reference external" href="https://stats.stackexchange.com/questions/299712/what-are-the-shortcomings-of-the-mean-absolute-percentage-error-mape">discussed</a> on CrossValidated.</p>
</div>
<p>Now that we know how to measure the quality of the forecasts, let’s see what metrics we can use and how to translate the results for the boss. After that, one small detail remains - building the model.</p>
</section>
</section>
<section class="tex2jax_ignore mathjax_ignore" id="move-smoothe-evaluate">
<h1><a class="toc-backref" href="#id5" role="doc-backlink">Move, smoothe, evaluate</a><a class="headerlink" href="#move-smoothe-evaluate" title="Permalink to this heading">#</a></h1>
<p>Let’s start with a naive hypothesis: “tomorrow will be the same as today”. However, instead of a model like <span class="math notranslate nohighlight">\(\hat{y}_{t} = y_{t-1}\)</span> (which is actually a great baseline for any time series prediction problems and sometimes is impossible to beat), we will assume that the future value of our variable depends on the average of its <span class="math notranslate nohighlight">\(k\)</span> previous values. Therefore, we will use the <strong>moving average</strong>.</p>
<p><span class="math notranslate nohighlight">\(\hat{y}_{t} = \frac{1}{k} \displaystyle\sum^{k}_{n=1} y_{t-n}\)</span></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">moving_average</span><span class="p">(</span><span class="n">series</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Calculate average of last n observations</span>
<span class="sd"> """</span>
<span class="k">return</span> <span class="n">np</span><span class="o">.</span><span class="n">average</span><span class="p">(</span><span class="n">series</span><span class="p">[</span><span class="o">-</span><span class="n">n</span><span class="p">:])</span>
<span class="n">moving_average</span><span class="p">(</span><span class="n">ads</span><span class="p">,</span> <span class="mi">24</span><span class="p">)</span> <span class="c1"># prediction for the last observed day (past 24 hours)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>np.float64(116805.0)
</pre></div>
</div>
</div>
</div>
<p>Unfortunately, we cannot make predictions far in the future - in order to get the value for the next step, we need the previous values to be actually observed. But moving average has another use case - smoothing the original time series to identify trends. Pandas has an implementation available with <a class="reference external" href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html"><code class="docutils literal notranslate"><span class="pre">DataFrame.rolling(window).mean()</span></code></a>. The wider the window, the smoother the trend. In the case of very noisy data, which is often encountered in finance, this procedure can help detect common patterns.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">plotMovingAverage</span><span class="p">(</span>
<span class="n">series</span><span class="p">,</span> <span class="n">window</span><span class="p">,</span> <span class="n">plot_intervals</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">scale</span><span class="o">=</span><span class="mf">1.96</span><span class="p">,</span> <span class="n">plot_anomalies</span><span class="o">=</span><span class="kc">False</span>
<span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> series - dataframe with timeseries</span>
<span class="sd"> window - rolling window size</span>
<span class="sd"> plot_intervals - show confidence intervals</span>
<span class="sd"> plot_anomalies - show anomalies</span>
<span class="sd"> """</span>
<span class="n">rolling_mean</span> <span class="o">=</span> <span class="n">series</span><span class="o">.</span><span class="n">rolling</span><span class="p">(</span><span class="n">window</span><span class="o">=</span><span class="n">window</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
<span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">15</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
<span class="n">plt</span><span class="o">.</span><span class="n">title</span><span class="p">(</span><span class="s2">"Moving average</span><span class="se">\n</span><span class="s2"> window size = </span><span class="si">{}</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">window</span><span class="p">))</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">rolling_mean</span><span class="p">,</span> <span class="s2">"g"</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s2">"Rolling mean trend"</span><span class="p">)</span>
<span class="c1"># Plot confidence intervals for smoothed values</span>
<span class="k">if</span> <span class="n">plot_intervals</span><span class="p">:</span>
<span class="n">mae</span> <span class="o">=</span> <span class="n">mean_absolute_error</span><span class="p">(</span><span class="n">series</span><span class="p">[</span><span class="n">window</span><span class="p">:],</span> <span class="n">rolling_mean</span><span class="p">[</span><span class="n">window</span><span class="p">:])</span>
<span class="n">deviation</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">std</span><span class="p">(</span><span class="n">series</span><span class="p">[</span><span class="n">window</span><span class="p">:]</span> <span class="o">-</span> <span class="n">rolling_mean</span><span class="p">[</span><span class="n">window</span><span class="p">:])</span>
<span class="n">lower_bond</span> <span class="o">=</span> <span class="n">rolling_mean</span> <span class="o">-</span> <span class="p">(</span><span class="n">mae</span> <span class="o">+</span> <span class="n">scale</span> <span class="o">*</span> <span class="n">deviation</span><span class="p">)</span>
<span class="n">upper_bond</span> <span class="o">=</span> <span class="n">rolling_mean</span> <span class="o">+</span> <span class="p">(</span><span class="n">mae</span> <span class="o">+</span> <span class="n">scale</span> <span class="o">*</span> <span class="n">deviation</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">upper_bond</span><span class="p">,</span> <span class="s2">"r--"</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s2">"Upper Bond / Lower Bond"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">lower_bond</span><span class="p">,</span> <span class="s2">"r--"</span><span class="p">)</span>
<span class="c1"># Having the intervals, find abnormal values</span>
<span class="k">if</span> <span class="n">plot_anomalies</span><span class="p">:</span>
<span class="n">anomalies</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">index</span><span class="o">=</span><span class="n">series</span><span class="o">.</span><span class="n">index</span><span class="p">,</span> <span class="n">columns</span><span class="o">=</span><span class="n">series</span><span class="o">.</span><span class="n">columns</span><span class="p">)</span>
<span class="n">anomalies</span><span class="p">[</span><span class="n">series</span> <span class="o"><</span> <span class="n">lower_bond</span><span class="p">]</span> <span class="o">=</span> <span class="n">series</span><span class="p">[</span><span class="n">series</span> <span class="o"><</span> <span class="n">lower_bond</span><span class="p">]</span>
<span class="n">anomalies</span><span class="p">[</span><span class="n">series</span> <span class="o">></span> <span class="n">upper_bond</span><span class="p">]</span> <span class="o">=</span> <span class="n">series</span><span class="p">[</span><span class="n">series</span> <span class="o">></span> <span class="n">upper_bond</span><span class="p">]</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">anomalies</span><span class="p">,</span> <span class="s2">"ro"</span><span class="p">,</span> <span class="n">markersize</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">series</span><span class="p">[</span><span class="n">window</span><span class="p">:],</span> <span class="n">label</span><span class="o">=</span><span class="s2">"Actual values"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">legend</span><span class="p">(</span><span class="n">loc</span><span class="o">=</span><span class="s2">"upper left"</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">grid</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>Let’s smooth by the previous 4 hours.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">plotMovingAverage</span><span class="p">(</span><span class="n">ads</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../_images/17146e5298ee835ce779745f98e55997931cc8e0842486b67883f70f2a6de0ef.png" src="../../_images/17146e5298ee835ce779745f98e55997931cc8e0842486b67883f70f2a6de0ef.png" />
</div>
</div>
<p>Now let’s try smoothing by the previous 12 hours.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">plotMovingAverage</span><span class="p">(</span><span class="n">ads</span><span class="p">,</span> <span class="mi">12</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../_images/21b984e7b7604e9770fd78637251a0d7528cea76d79f5197fa4f7499af8accdc.png" src="../../_images/21b984e7b7604e9770fd78637251a0d7528cea76d79f5197fa4f7499af8accdc.png" />
</div>
</div>
<p>Now smoothing with the previous 24 hours, we get the daily trend.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">plotMovingAverage</span><span class="p">(</span><span class="n">ads</span><span class="p">,</span> <span class="mi">24</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../_images/dcc5cc4a9e20375cf20c491ceaaadaa1799b1e0fd442b297cfbafa4f3bfd4650.png" src="../../_images/dcc5cc4a9e20375cf20c491ceaaadaa1799b1e0fd442b297cfbafa4f3bfd4650.png" />
</div>
</div>
<p>When we applied daily smoothing on hourly data, we could clearly see the dynamics of ads watched. During the weekends, the values are higher (more time to play on the weekends) while fewer ads are watched on weekdays.</p>
<p>We can also plot confidence intervals for our smoothed values.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">plotMovingAverage</span><span class="p">(</span><span class="n">ads</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="n">plot_intervals</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../_images/d1f2c6fe7fb421cacb46a31a7581db2317e12d268c0d1e7c041356df2d2745dd.png" src="../../_images/d1f2c6fe7fb421cacb46a31a7581db2317e12d268c0d1e7c041356df2d2745dd.png" />
</div>
</div>
<p>Now, let’s create a simple anomaly detection system with the help of moving average. Unfortunately, in this particular dataset, everything is more or less normal, so we will intentionally make one of the values abnormal in our dataframe <code class="docutils literal notranslate"><span class="pre">ads_anomaly</span></code>.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">ads_anomaly</span> <span class="o">=</span> <span class="n">ads</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="n">ads_anomaly</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="o">-</span><span class="mi">20</span><span class="p">]</span> <span class="o">=</span> <span class="n">ads_anomaly</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="o">-</span><span class="mi">20</span><span class="p">]</span> <span class="o">*</span> <span class="mf">0.2</span> <span class="c1"># say we have 80% drop of ads</span>
</pre></div>
</div>
</div>
</div>
<p>Let’s see if this simple method can catch the anomaly.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">plotMovingAverage</span><span class="p">(</span><span class="n">ads_anomaly</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="n">plot_intervals</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">plot_anomalies</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../_images/ac50e311931c8cd88dcd8947bf03db8fac6de3631b18fdaf09406122dfd1b71f.png" src="../../_images/ac50e311931c8cd88dcd8947bf03db8fac6de3631b18fdaf09406122dfd1b71f.png" />
</div>
</div>
<p>Neat! What about the second series?</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">plotMovingAverage</span><span class="p">(</span>
<span class="n">currency</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="n">plot_intervals</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">plot_anomalies</span><span class="o">=</span><span class="kc">True</span>
<span class="p">)</span> <span class="c1"># weekly smoothing</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<img alt="../../_images/d99665edb1b7539375bf6a33c963ead3564eae4e45cdfc9a22687855d2e527b7.png" src="../../_images/d99665edb1b7539375bf6a33c963ead3564eae4e45cdfc9a22687855d2e527b7.png" />
</div>
</div>
<p>Oh no, this was not as great! Here, we can see the downside of our simple approach – it did not capture the monthly seasonality in our data and marked almost all 30-day peaks as anomalies. If you want to avoid false positives, it is best to consider more complex models.</p>
<p><strong>Weighted average</strong> is a simple modification to the moving average. The weights sum up to <code class="docutils literal notranslate"><span class="pre">1</span></code> with larger weights assigned to more recent observations.</p>
<p><span class="math notranslate nohighlight">\(\hat{y}_{t} = \displaystyle\sum^{k}_{n=1} \omega_n y_{t+1-n}\)</span></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">weighted_average</span><span class="p">(</span><span class="n">series</span><span class="p">,</span> <span class="n">weights</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Calculate weighted average on the series.</span>
<span class="sd"> Assuming weights are sorted in descending order</span>
<span class="sd"> (larger weights are assigned to more recent observations).</span>
<span class="sd"> """</span>
<span class="n">result</span> <span class="o">=</span> <span class="mf">0.0</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">weights</span><span class="p">)):</span>
<span class="n">result</span> <span class="o">+=</span> <span class="n">series</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="o">-</span><span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">]</span> <span class="o">*</span> <span class="n">weights</span><span class="p">[</span><span class="n">n</span><span class="p">]</span>
<span class="k">return</span> <span class="nb">float</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">weighted_average</span><span class="p">(</span><span class="n">ads</span><span class="p">,</span> <span class="p">[</span><span class="mf">0.6</span><span class="p">,</span> <span class="mf">0.3</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">])</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>87025.5
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># just checking</span>
<span class="mf">0.6</span> <span class="o">*</span> <span class="n">ads</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="mf">0.3</span> <span class="o">*</span> <span class="n">ads</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">*</span> <span class="n">ads</span><span class="o">.</span><span class="n">iloc</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output text_plain highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>Ads 87025.5
dtype: float64
</pre></div>
</div>
</div>
</div>
<section id="exponential-smoothing">
<h2><a class="toc-backref" href="#id6" role="doc-backlink">Exponential smoothing</a><a class="headerlink" href="#exponential-smoothing" title="Permalink to this heading">#</a></h2>
<p>Now, let’s see what happens if, instead of weighting the last <span class="math notranslate nohighlight">\(k\)</span> values of the time series, we start weighting all available observations while exponentially decreasing the weights as we move further back in time. There exists a formula for <strong><a class="reference external" href="https://en.wikipedia.org/wiki/Exponential_smoothing">exponential smoothing</a></strong> that will help us with this:</p>
<div class="math notranslate nohighlight">
\[\hat{y}_{t} = \alpha \cdot y_t + (1-\alpha) \cdot \hat y_{t-1} \]</div>
<p>Here the model value is a weighted average between the current true value and the previous model values. The <span class="math notranslate nohighlight">\(\alpha\)</span> weight is called a smoothing factor. It defines how quickly we will “forget” the last available true observation. The smaller <span class="math notranslate nohighlight">\(\alpha\)</span> is, the more influence the previous observations have and the smoother the series is.</p>
<p>Exponentiality is hidden in the recursiveness of the function – we multiply by <span class="math notranslate nohighlight">\((1-\alpha)\)</span> each time, which already contains a multiplication by <span class="math notranslate nohighlight">\((1-\alpha)\)</span> of previous model values.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">exponential_smoothing</span><span class="p">(</span><span class="n">series</span><span class="p">,</span> <span class="n">alpha</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> series - dataset with timestamps</span>
<span class="sd"> alpha - float [0.0, 1.0], smoothing parameter</span>
<span class="sd"> """</span>
<span class="n">result</span> <span class="o">=</span> <span class="p">[</span><span class="n">series</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span> <span class="c1"># first value is same as series</span>
<span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">series</span><span class="p">)):</span>
<span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">alpha</span> <span class="o">*</span> <span class="n">series</span><span class="p">[</span><span class="n">n</span><span class="p">]</span> <span class="o">+</span> <span class="p">(</span><span class="mi">1</span> <span class="o">-</span> <span class="n">alpha</span><span class="p">)</span> <span class="o">*</span> <span class="n">result</span><span class="p">[</span><span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">])</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
</div>
</div>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">plotExponentialSmoothing</span><span class="p">(</span><span class="n">series</span><span class="p">,</span> <span class="n">alphas</span><span class="p">):</span>
<span class="w"> </span><span class="sd">"""</span>
<span class="sd"> Plots exponential smoothing with different alphas</span>
<span class="sd"> series - dataset with timestamps</span>
<span class="sd"> alphas - list of floats, smoothing parameters</span>
<span class="sd"> """</span>
<span class="k">with</span> <span class="n">plt</span><span class="o">.</span><span class="n">style</span><span class="o">.</span><span class="n">context</span><span class="p">(</span><span class="s2">"bmh"</span><span class="p">):</span>
<span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">15</span><span class="p">,</span> <span class="mi">7</span><span class="p">))</span>
<span class="k">for</span> <span class="n">alpha</span> <span class="ow">in</span> <span class="n">alphas</span><span class="p">:</span>