├── .gitignore ├── LICENSE.md ├── README.md ├── datasets_required.txt ├── environment.yml ├── notebooks ├── Module 1.1.1 - Overview.ipynb ├── Module 1.1.2 - Distributions.ipynb ├── Module 1.1.3 - Moments and Z-Scores.ipynb ├── Module 1.1.4 - Normality Tests.ipynb ├── Module 1.2.1 - Covariance.ipynb ├── Module 1.2.2 - Correlation.ipynb ├── Module 1.2.3 - Cross Correlation.ipynb ├── Module 1.3.1 - Ordinary Least Squares.ipynb ├── Module 1.3.2 - Multivariate OLS.ipynb ├── Module 1.3.3 - Regression Tests.ipynb ├── Module 1.3.4 - Multicolinearity.ipynb ├── Module 1.4.1 - PCA Introduction.ipynb ├── Module 1.4.2 - PCA Interpretation.ipynb ├── Module 1.5.1 - Bayesian Statistics Introduction.ipynb ├── Module 1.5.2 - Bayesian Inference Basics.ipynb ├── Module 1.5.3 - Representing Prior information.ipynb ├── Module 1.6.1 - Time Series moving average.ipynb ├── Module 1.6.2 - Stationarity.ipynb ├── Module 1.6.3 - White Noise.ipynb ├── Module 1.6.4 - ARMA.ipynb ├── Module 1.7.1 - Kalman Filter Introduction.ipynb ├── Module 2.1.1 - Hypothesis Testing.ipynb ├── Module 2.2.1 - Linear regression models.ipynb ├── Module 2.2.2 - ARIMA.ipynb ├── Module 2.2.3 - GARCH.ipynb ├── Module 2.3.1 - Statistical Significance.ipynb ├── Module 2.3.2 - Confidence Intervals.ipynb ├── Module 2.4.1 - Residual Analysis.ipynb ├── Module 2.5.1 - Model and Estimate Instability.ipynb ├── Module 2.6.1 - Overfitting.ipynb ├── Module Unknown - Moving averages in time series (not moving average processes).ipynb ├── bayesian_updating_plot.py ├── custom │ ├── __init__.py │ ├── css │ │ └── custom.css │ └── figures.py ├── data │ ├── AAPL.h5 │ ├── AAPL.pkl │ ├── HousePricesVsInterestRates.hdf │ ├── aus_state_populations.h5 │ └── sp500.csv ├── img │ ├── Wong_Baker_Scale.sr (1).JPG │ ├── Wong_Baker_Scale.sr.JPG │ ├── confidence_interval_highlight.png │ ├── facial_recognition.png │ ├── lagged_correlation_plot.png │ ├── python_charmers_logo.png │ ├── snapshot.png │ ├── spurious.png │ └── tibra_logo.png ├── my_secrets_template.py ├── plot_priors.ipy ├── python2_test.sh ├── setup.ipy ├── show_posteriors_coins.ipy ├── solutions │ ├── PCA Application Example Solution.ipynb │ ├── adfuller.py │ ├── adjusted_increases.py │ ├── an_array.py │ ├── arch_models.py │ ├── arima_cryptocurrrency.py │ ├── arima_seasonal.py │ ├── arima_sse.py │ ├── arima_types.py │ ├── arma_cryptocurrency.py │ ├── bayesian_updating_2.py │ ├── best_coin.py │ ├── bic_results.py │ ├── capm.py │ ├── cdf_relationships.py │ ├── confidence_intervals.py │ ├── control_charts.py │ ├── correlations.py │ ├── credible_interval.py │ ├── cross_validation_one.py │ ├── detrending.py │ ├── dot.py │ ├── error_term_u.py │ ├── exponential_smoothing.py │ ├── false_postives.py │ ├── fit_linear_plot_residuals.py │ ├── generate_significance_data.py │ ├── histograms.py │ ├── hypothesis_one.py │ ├── hypothesis_two.py │ ├── increasing_variability.py │ ├── inferring_statistics.py │ ├── jarque_bera.py │ ├── kalman_basics.py │ ├── lagged_correlations.py │ ├── linear_regression_intro.py │ ├── ljungbox.py │ ├── ma_model.py │ ├── make_stationary.py │ ├── many_normal_tests.py │ ├── matrix_products.py │ ├── matrix_terminology.py │ ├── moments.py │ ├── multiple_comparisons.py │ ├── normal_distributions.py │ ├── ols_basic_ensemble.py │ ├── ols_train_test.py │ ├── ordinal_encoding.py │ ├── ordinal_nominal.py │ ├── overfitting_arma.py │ ├── overfitting_one.py │ ├── overfitting_three.py │ ├── pca_different_kinds.py │ ├── pca_explained_variance.py │ ├── pca_numpy.py │ ├── pca_statsmodels.py │ ├── plotting_distributions.py │ ├── polyfit.py │ ├── prior_postcode_given_state.py │ ├── public_medical.py │ ├── ratio_interval.py │ ├── representing_prior_information.py │ ├── residual_analysis_one.py │ ├── residual_analysis_two.py │ ├── residual_plotting.py │ ├── rolling_forecast.py │ ├── scipy_normal_tests.py │ ├── simulation_ttest.py │ ├── stationarity.py │ ├── statsmodels_formula_ols.py │ ├── uniform.py │ ├── white_noise_break.py │ └── why_not_normal.py └── tools │ └── check_headings.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # In general, ignore all non markdown files unless otherwise stated 2 | 3 | # * 4 | 5 | # Force git to pick up the folders for unignore 6 | !*/ 7 | 8 | # Then unignore specific files 9 | !*.md 10 | !*.Rmd 11 | !*.py 12 | !*.ipynb 13 | !.gitignore 14 | !notedown_all.py 15 | !Common/preamble.tex 16 | 17 | # Don't ignore extras or solutions 18 | !/**/images/* 19 | !/**/img/* 20 | !/**/extra/* 21 | !/**/extras/* 22 | !/**/solutions/* 23 | 24 | # Finally, specifically ignore temp files generated by the system 25 | .DS_Store 26 | *~ 27 | **/.ipynb_checkpoints/ 28 | **/__pycache__/ 29 | **/*.egg-info/ 30 | altair*.json 31 | */altair-temp-data/ 32 | 33 | my_secrets.py 34 | 35 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # Creative Commons Attribution-NonCommercial 4.0 International Public License 2 | 3 | URL of license text: https://creativecommons.org/licenses/by-nc/4.0/legalcode 4 | 5 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 6 | 7 | ## Section 1 – Definitions. 8 | 9 | Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 10 | Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 11 | Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 12 | Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 13 | Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 14 | Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 15 | Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 16 | Licensor means the individual(s) or entity(ies) granting rights under this Public License. 17 | NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 18 | Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 19 | Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 20 | You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 21 | 22 | ## Section 2 – Scope. 23 | 24 | License grant. 25 | Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 26 | reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 27 | produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 28 | Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 29 | Term. The term of this Public License is specified in Section 6(a). 30 | Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 31 | Downstream recipients. 32 | Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 33 | No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 34 | No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 35 | Other rights. 36 | 37 | Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 38 | Patent and trademark rights are not licensed under this Public License. 39 | To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 40 | 41 | ## Section 3 – License Conditions. 42 | 43 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 44 | 45 | Attribution. 46 | 47 | If You Share the Licensed Material (including in modified form), You must: 48 | 49 | retain the following if it is supplied by the Licensor with the Licensed Material: 50 | identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 51 | a copyright notice; 52 | a notice that refers to this Public License; 53 | a notice that refers to the disclaimer of warranties; 54 | a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 55 | indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 56 | indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 57 | You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 58 | If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 59 | If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 60 | 61 | ## Section 4 – Sui Generis Database Rights. 62 | 63 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 64 | 65 | for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 66 | if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 67 | You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 68 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 69 | 70 | ## Section 5 – Disclaimer of Warranties and Limitation of Liability. 71 | 72 | Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. 73 | To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. 74 | The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 75 | 76 | ## Section 6 – Term and Termination. 77 | 78 | This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 79 | Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 80 | 81 | automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 82 | upon express reinstatement by the Licensor. 83 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 84 | For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 85 | Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 86 | 87 | ## Section 7 – Other Terms and Conditions. 88 | 89 | The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 90 | Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 91 | 92 | ## Section 8 – Interpretation. 93 | 94 | For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 95 | To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 96 | No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 97 | Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 98 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 99 | 100 | Creative Commons may be contacted at creativecommons.org. 101 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Self-taught training materials in quantitative finance 2 | 3 | ## Copyright 4 | 5 | Copyright (c) 2020 Python Charmers Pty Ltd, Australia, . All rights reserved. 6 | 7 | Python Charmers Logo 8 | 9 | ## License 10 | 11 | Published under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) license. See `LICENSE.md` for details. 12 | 13 | ## Sponsor 14 | 15 | Sponsored by Tibra Global Services, 16 | 17 | Tibra Logo 18 | -------------------------------------------------------------------------------- /datasets_required.txt: -------------------------------------------------------------------------------- 1 | These datasets need to be distributed with the course materials: 2 | 3 | Available from here: https://github.com/PythonCharmers/PythonCharmersData 4 | 5 | --- 6 | 7 | * AAPL.h5 8 | 9 | -------------------------------------------------------------------------------- /environment.yml: -------------------------------------------------------------------------------- 1 | name: quant_finance 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - jupyter 7 | - pytest 8 | - numpy 9 | - scipy 10 | - statsmodels 11 | - altair-all 12 | - vega_datasets 13 | - scikit-learn 14 | - tensorflow 15 | - matplotlib 16 | - tables 17 | - quandl 18 | - arch-py 19 | -------------------------------------------------------------------------------- /notebooks/Module 1.1.1 - Overview.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Introduction to Quantitative Finance\n", 8 | "\n", 9 | "Copyright (c) 2019 Python Charmers Pty Ltd, Australia, . All rights reserved.\n", 10 | "\n", 11 | "\"Python\n", 12 | "\n", 13 | "Published under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) license. See `LICENSE.md` for details.\n", 14 | "\n", 15 | "Sponsored by Tibra Global Services, \n", 16 | "\n", 17 | "\"Tibra\n", 18 | "\n", 19 | "## Module 1.1: Distributions and Random Processes\n", 20 | "\n", 21 | "### 1.1.1: Overview\n", 22 | "\n", 23 | "In this section we will review random distributions and processes, identifying their use cases and how to build them with the Python programming language.\n", 24 | "\n", 25 | "This module will also cover some background material on getting installed on your system, and some other notes on how to use these notebooks.\n", 26 | "\n", 27 | "In this first set of modules we will cover the following topics:\n", 28 | "\n", 29 | "1. How to use Jupyter Notebooks, including Markdown cells and exporting to PDF\n", 30 | "2. How to complete exercises and check your solutions work with *pytest*\n", 31 | "3. Python versions, and writing compatible code in both Python 2 and Python 3\n", 32 | "4. The Altair library for visualisations (we will use this extensively throughout the course)\n", 33 | "5. Different types of data (discrete and continuous) and how to generate random variables from them.\n", 34 | "6. Normal distributions, their properties and testing for normality\n", 35 | "7. Z-scores and moments" 36 | ] 37 | }, 38 | { 39 | "cell_type": "markdown", 40 | "metadata": {}, 41 | "source": [ 42 | "Before we get started, let's check your setup to make sure it has the necessary software installed to run the notebooks. Click the next cell, and press: CTRL + Enter to run the code in it." 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 1, 48 | "metadata": {}, 49 | "outputs": [ 50 | { 51 | "name": "stdout", 52 | "output_type": "stream", 53 | "text": [ 54 | "3.11.8 | packaged by Anaconda, Inc. | (main, Feb 26 2024, 21:34:05) [MSC v.1916 64 bit (AMD64)]\n" 55 | ] 56 | } 57 | ], 58 | "source": [ 59 | "import sys\n", 60 | "print(sys.version)" 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "metadata": {}, 66 | "source": [ 67 | "This course is designed to work with both Python 2 and Python 3. There are some differences, but these will be pointed out as we go.\n", 68 | "\n", 69 | "In the output above, you should see the version of Python you are using. These notebooks have been tested with versions:\n", 70 | "\n", 71 | "* 2.7 and above for Python 2\n", 72 | "* 3.6 and above for Python 3\n", 73 | "\n", 74 | "If your versions are lower than those, please consider upgrading - your Python system may not be receiving all updates it can, and many libraries will slowly stop adding features for your version. This is true of Python 2.7 too." 75 | ] 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "metadata": { 80 | "collapsed": false, 81 | "jupyter": { 82 | "outputs_hidden": false 83 | }, 84 | "pycharm": { 85 | "name": "#%% md\n" 86 | } 87 | }, 88 | "source": [ 89 | "Additionally, it is recommended that Anaconda Distribution or Miniconda is used in order to make use of the conda package and environment manager. The Anaconda Distribution link can be found [here](https://docs.anaconda.com/free/anaconda/install/), whilst minconda can be found [here](https://docs.anaconda.com/free/miniconda/miniconda-install/). The full Anaconda Distribution is recommended as it comes with many useful packages preinstalled." 90 | ] 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "metadata": {}, 95 | "source": [ 96 | "Throughout this course, you'll be able to run the code directly in the notebook itself. I also recommend completing the exercises within the notebook as you go. That way, you can reuse some of the code in the notebook itself for your exercises. To do that, you will need to add cells. " 97 | ] 98 | }, 99 | { 100 | "cell_type": "markdown", 101 | "metadata": {}, 102 | "source": [ 103 | "Try adding a cell now. Click this cell, so that it has an outline around this paragraph. Then click ESC, and then b. This should create a new cell below this one." 104 | ] 105 | }, 106 | { 107 | "cell_type": "raw", 108 | "metadata": {}, 109 | "source": [ 110 | "For more keyboard shortcuts, click ESC, and then h. The command mode is activated by clicking ESC, and then the command itself is selected using the letter h (or whatever for the other commands).\n", 111 | "\n", 112 | "If you want to write notes, like these ones, click ESC, and then m. This changes the cell type to \"markdown\", letting you add notes to the notebook as we are going." 113 | ] 114 | }, 115 | { 116 | "cell_type": "raw", 117 | "metadata": {}, 118 | "source": [ 119 | "Next, let us test your python setup. Let's check you have all the libraries installed on your computer." 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": 2, 125 | "metadata": {}, 126 | "outputs": [ 127 | { 128 | "name": "stdout", 129 | "output_type": "stream", 130 | "text": [ 131 | "Everything is installed!\n" 132 | ] 133 | } 134 | ], 135 | "source": [ 136 | "import pytest\n", 137 | "import numpy\n", 138 | "import scipy\n", 139 | "import statsmodels\n", 140 | "import altair\n", 141 | "import vega_datasets\n", 142 | "import sklearn\n", 143 | "import tensorflow\n", 144 | "import matplotlib\n", 145 | "import quandl\n", 146 | "print(\"Everything is installed!\")" 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "metadata": {}, 152 | "source": [ 153 | "If one of those failed, you'll get an error that looks like this:\n", 154 | "\n", 155 | "
---------------------------------------------------------------------------\n",
156 |     "ModuleNotFoundError                       Traceback (most recent call last)\n",
157 |     "<ipython-input-2-302beb3fe330> in <module>\n",
158 |     "      2 import scipy\n",
159 |     "      3 import statsmodels\n",
160 |     "----> 4 import altair\n",
161 |     "      6 import vega_datasets\n",
162 |     "\n",
163 |     "ModuleNotFoundError: No module named 'altair'\n",
164 |     "\n",
165 |     "
\n", 166 | "\n", 167 | "#### Managing packages using Conda\n", 168 | "##### Using prepackaged environment\n", 169 | "To use a prepackaged environment with the necessary packages installed, run\n", 170 | "\n", 171 | " conda env create -f environment.yml\n", 172 | "\n", 173 | "which creates a `quant_finance` environment. You can activate this environment using:\n", 174 | "\n", 175 | " conda activate quant_finance\n", 176 | "\n", 177 | "and then re-run the Jupyter notebook/lab in this environment to use all the required packages.\n", 178 | "\n", 179 | "**Note:** this method does not install the `maxentropy` package, refer to the last part of the pip instructions below for this package.\n", 180 | "\n", 181 | "##### Installing standalone packages\n", 182 | "To install a standalone package, use the following command:\n", 183 | "\n", 184 | " conda install -y LIBRARY_NAME\n", 185 | " \n", 186 | "For instance, to get tensorflow, run:\n", 187 | "\n", 188 | " conda install -y tensorflow\n", 189 | " \n", 190 | "You can run this command from Jupyter Notebooks too, and if you run many versions of Python on your computer, this helps ensure you have the right environment. Just prepend a `!` and run in a cell:\n", 191 | "\n", 192 | " !conda install -y tensorflow\n", 193 | " \n", 194 | "For `sklearn`, the name of the library is `scikit-learn`. Therefore you would run:\n", 195 | "\n", 196 | " !conda install -y scikit-learn\n", 197 | " \n", 198 | " \n", 199 | "For `altair`, `vega` and `vega_datasets`, you'll need to use the `conda-forge`, which is simply a different repository of libraries than normal. Instead, use:\n", 200 | " \n", 201 | " !conda install -c conda-forge -y vega vega_datasets altair\n", 202 | "\n", 203 | "If the cell run, completed, and gave you an execution number, you'll see the message \"Everything is installed!\" printed after the cell. If that's the case, you are free to move onto the next Notebook!\n", 204 | "\n", 205 | "#### Managing packages using pip\n", 206 | "If you've installed Python yourself, you probably know how to install modules for your system. If you are unsure, try: `pip install my_module`\n", 207 | "\n", 208 | "You may also find the command `pip install -r requirements.txt` useful. \n", 209 | "\n", 210 | "The `maxentropy` package in `requirements.txt` requires deprecated `sklearn` (updated to `scikit-learn`), so first run `set SKLEARN_ALLOW_DEPRECATED_SKLEARN_PACKAGE_INSTALL=True` before `pip install -r requirements.txt`. Deprecated `sklearn` can then be uninstalled with `pip uninstall sklearn`." 211 | ] 212 | } 213 | ], 214 | "metadata": { 215 | "kernelspec": { 216 | "display_name": "Python 3 (ipykernel)", 217 | "language": "python", 218 | "name": "python3" 219 | }, 220 | "language_info": { 221 | "codemirror_mode": { 222 | "name": "ipython", 223 | "version": 3 224 | }, 225 | "file_extension": ".py", 226 | "mimetype": "text/x-python", 227 | "name": "python", 228 | "nbconvert_exporter": "python", 229 | "pygments_lexer": "ipython3", 230 | "version": "3.12.3" 231 | } 232 | }, 233 | "nbformat": 4, 234 | "nbformat_minor": 4 235 | } 236 | -------------------------------------------------------------------------------- /notebooks/Module 1.1.4 - Normality Tests.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Introduction to Quantitative Finance\n", 8 | "\n", 9 | "Copyright (c) 2019 Python Charmers Pty Ltd, Australia, . All rights reserved.\n", 10 | "\n", 11 | "\"Python\n", 12 | "\n", 13 | "Published under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) license. See `LICENSE.md` for details.\n", 14 | "\n", 15 | "Sponsored by Tibra Global Services, \n", 16 | "\n", 17 | "\"Tibra\n", 18 | "\n", 19 | "\n", 20 | "## Module 1.1: Distributions and Random Processes\n", 21 | "\n", 22 | "### 1.1.4: Normality Tests\n", 23 | "\n", 24 | "If you are analysing data on the assumption it is normally distributed, you should test that assumption first. Properties of normal distributions do not necessarily apply to data that has a different underlying distribution. As an example, an ANOVA test assumes normality in your data, and the results of an ANOVA are not valid if the data comes from some other source.\n", 25 | "\n", 26 | "There are a number of normality tests that provide a way for us to determine if it is likely that the data comes from a normal distribution.\n", 27 | "\n", 28 | "One method of testing for normality is to compute the skew and kurtosis of the data. A standard normal distribution has a skew of 0 and a kurtosis of 3." 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 1, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "%run setup.ipy" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 3, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "aapl = pd.read_pickle(\"data/AAPL.pkl\")" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 4, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "aapl['Gain'] = aapl['Adj Close'].diff()\n", 56 | "aapl.dropna(inplace=True)" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 5, 62 | "metadata": {}, 63 | "outputs": [ 64 | { 65 | "data": { 66 | "text/plain": [ 67 | "0.49966243998511045" 68 | ] 69 | }, 70 | "execution_count": 5, 71 | "metadata": {}, 72 | "output_type": "execute_result" 73 | } 74 | ], 75 | "source": [ 76 | "stats.skew(aapl['Gain'])" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 6, 82 | "metadata": {}, 83 | "outputs": [ 84 | { 85 | "data": { 86 | "text/plain": [ 87 | "20.448973653158085" 88 | ] 89 | }, 90 | "execution_count": 6, 91 | "metadata": {}, 92 | "output_type": "execute_result" 93 | } 94 | ], 95 | "source": [ 96 | "stats.kurtosis(aapl['Gain'])" 97 | ] 98 | }, 99 | { 100 | "cell_type": "markdown", 101 | "metadata": {}, 102 | "source": [ 103 | "The AAPL stock price increases do not appear to have a normal distribution based on this data. Let's have a look at the histogram again:" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": 7, 109 | "metadata": {}, 110 | "outputs": [ 111 | { 112 | "data": { 113 | "text/html": [ 114 | "\n", 115 | "\n", 126 | "
\n", 127 | "" 180 | ], 181 | "text/plain": [ 182 | "alt.Chart(...)" 183 | ] 184 | }, 185 | "execution_count": 7, 186 | "metadata": {}, 187 | "output_type": "execute_result" 188 | } 189 | ], 190 | "source": [ 191 | "alt.Chart(aapl).mark_bar().encode(\n", 192 | " alt.X(\"Gain\", bin=alt.Bin(maxbins=100)),\n", 193 | " y='count()',\n", 194 | " )" 195 | ] 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "metadata": {}, 200 | "source": [ 201 | "A high Kurtosis is obtained from very \"sharp\" peaks such as this one. The skew is not that high, but is positive, indicating a right-leaning distribution.\n", 202 | "\n", 203 | "More objective tests are available in the `scipy.stats` package. For instance, the Shapiro-Wilk test is commonly used and is a good test for small to medium datasets, with up to a few thousand data points." 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": 8, 209 | "metadata": {}, 210 | "outputs": [], 211 | "source": [ 212 | "statistic, p = stats.shapiro(aapl['Gain'])" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": 9, 218 | "metadata": {}, 219 | "outputs": [ 220 | { 221 | "data": { 222 | "text/plain": [ 223 | "0.0" 224 | ] 225 | }, 226 | "execution_count": 9, 227 | "metadata": {}, 228 | "output_type": "execute_result" 229 | } 230 | ], 231 | "source": [ 232 | "p # Compare the p value to your acceptable alpha value to determine if the null hypothesis can be rejected." 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": 10, 238 | "metadata": {}, 239 | "outputs": [ 240 | { 241 | "name": "stdout", 242 | "output_type": "stream", 243 | "text": [ 244 | "The data does not look like it was drawn from a normal distribution\n" 245 | ] 246 | } 247 | ], 248 | "source": [ 249 | "if p > 0.05:\n", 250 | " print(\"The data looks like it was drawn from a normal distribution\")\n", 251 | "else:\n", 252 | " print(\"The data does not look like it was drawn from a normal distribution\")" 253 | ] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "metadata": {}, 258 | "source": [ 259 | "### What is a p-value?\n", 260 | "\n", 261 | "The p-value above is a commonly used term to describe the probability of your test being true.\n", 262 | "\n", 263 | "As it is a probability, it has a value between 0 and 1. Values near 0 indicate that your test is \"not likely to be true\" and values near 1 indicate that your test is likely to be true. Often, we apply a threshold, and if our p value is greater than that threshold, we accept the outcome as \"likely enough, and we continue as if it were true\", that is, we accept the outcome of the test as a \"positive\".\n", 264 | "\n", 265 | "It is very common to use a threshold of 0.05 when performing a test. That is, if our test has a greater than 95% chance of being true, we accept it as such. While this is an adequate rule of thumb, it is not a one-size-fits-all solution to the problem of choosing a p value threshold.\n", 266 | "\n", 267 | "Where this is normally seen in classical statistics is with a Null, and Alternative hypothesis. We will delve into these deeper later, but as this is used above, the null hypothesis is our \"nothing is surprising\" hypothesis, and the alternative is \"there is something interesting here\". For the Shapiro-Wilk used above, the hypothesis are:\n", 268 | "\n", 269 | "* $H_0$ (the Null hypothesis): The data is drawn from a normal distribution\n", 270 | "* $H_A$ (the Alternative hypothesis): The data was not drawn from a normal distribution\n", 271 | "\n", 272 | "Here we have mutually exclusive tests. If we get a value of $a$ for our Null hypothesis, then the probability of our Alternative being true is $1-a$. Statisticians are a pessimistic bunch, so require a very high threshold before we reject the Null hypothesis. This is akin to requiring a very high amount of evidence to reject it. Therefore, to reject the Null hypothesis, to indicate something else is going on here, we require the p value to be less than 0.05, i.e. for there to be a greater than 95% chance the Alternative hypothesis is true.\n", 273 | "\n", 274 | "This might seem like a high standard to meet, but humans often see patterns in data that are not there. We use statistics to test these patterns and ensure we don't fall afoul of this over confident pattern matching.\n", 275 | "\n", 276 | "Before you decide to run a new statistical test, you should see first what the p value would tell you. Often the language is \"accept the null hypothesis\" or \"fail to accept the null hypothesis\". This will tell you how to use the test." 277 | ] 278 | }, 279 | { 280 | "cell_type": "markdown", 281 | "metadata": {}, 282 | "source": [ 283 | "We could see from the Kurtosis that this dataset above wasn't normal. Let's look at a different set of data." 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": 11, 289 | "metadata": {}, 290 | "outputs": [], 291 | "source": [ 292 | "heights = np.array([\n", 293 | " 205.61624376, 155.80577135, 202.09636984, 159.19312848,\n", 294 | " 160.0263383 , 147.44200373, 160.96891569, 160.76304892,\n", 295 | " 167.59165377, 164.31571823, 151.11269914, 176.43856129,\n", 296 | " 176.88435091, 138.04177187, 183.87507305, 162.81488426,\n", 297 | " 167.96767641, 144.68437342, 180.88771461, 179.18997091,\n", 298 | " 189.81672505, 163.68662119, 175.70135072, 167.32793289,\n", 299 | " 163.72509862, 207.93257342, 177.41722601, 167.28154916,\n", 300 | " 170.26294662, 187.01142671, 178.3108478 , 168.8711774 ,\n", 301 | " 202.77222671, 138.55043572, 187.10284379, 155.13494037,\n", 302 | " 175.24219374, 188.54739561, 191.42024196, 174.34537673,\n", 303 | " 158.36285104, 183.17014557, 166.36310929, 185.3415384 ,\n", 304 | " 163.87673308, 173.70401469, 168.78499868, 167.39762991,\n", 305 | " 166.89193943, 191.04035344, 148.02108024, 140.82772936,\n", 306 | " 168.85378921, 142.13536543, 189.77084606, 173.7849811 ,\n", 307 | " 157.61303804, 171.62493617, 173.30529631, 162.92083214,\n", 308 | " 169.52974326, 142.01039665, 176.01691215, 170.32439763,\n", 309 | " 172.64616031, 158.35076247, 185.96332979, 176.6176222 ,\n", 310 | " 204.68516079, 161.43591954, 172.42384543, 179.36900257,\n", 311 | " 170.01353653, 194.40269002, 139.96802012, 156.47281846,\n", 312 | " 210.21895193, 153.30508193, 157.10282665, 200.07040619,\n", 313 | " 174.69616438, 168.97403285, 188.9396949 , 156.19358617,\n", 314 | " 179.56494356, 175.04014032, 164.1384659 , 167.90219562,\n", 315 | " 184.80752625, 143.56580744, 169.80537836, 186.5894398 ,\n", 316 | " 166.39251657, 165.65510886, 195.49137372, 152.21650272,\n", 317 | " 163.14001055, 170.27382512, 147.63901378, 190.32910286])" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": 12, 323 | "metadata": {}, 324 | "outputs": [], 325 | "source": [ 326 | "statistic, p = stats.shapiro(heights)" 327 | ] 328 | }, 329 | { 330 | "cell_type": "code", 331 | "execution_count": 13, 332 | "metadata": {}, 333 | "outputs": [ 334 | { 335 | "name": "stdout", 336 | "output_type": "stream", 337 | "text": [ 338 | "The data looks like it was drawn from a normal distribution\n", 339 | "p=0.278\n" 340 | ] 341 | } 342 | ], 343 | "source": [ 344 | "if p > 0.05:\n", 345 | " print(\"The data looks like it was drawn from a normal distribution\")\n", 346 | " print(\"p={:.3f}\".format(p))\n", 347 | "else:\n", 348 | " print(\"The data does not look like it was drawn from a normal distribution\")" 349 | ] 350 | }, 351 | { 352 | "cell_type": "markdown", 353 | "metadata": {}, 354 | "source": [ 355 | "#### Exercise\n", 356 | "\n", 357 | "Two other commonly used tests for normality are available in `scipy.stats`. They are `stats.normaltest` and `stats.kstest`. Review the help and references for these functions, and run them on the `heights` data. What are the strengths and weaknesses of each test?" 358 | ] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": 14, 363 | "metadata": {}, 364 | "outputs": [ 365 | { 366 | "name": "stdout", 367 | "output_type": "stream", 368 | "text": [ 369 | "0.6994130645220737 0.0\n", 370 | "From Stack overflow, the Kolmogorov-Smirnov is for a completely specified distribution, while the Shapiro-Wilk is for normality, with unspecified mean and variance.\n" 371 | ] 372 | } 373 | ], 374 | "source": [ 375 | "statistic_chi, p_c = stats.normaltest(heights) #chi squared test statistic\n", 376 | "statistic_k, p_k = stats.kstest(heights,cdf = 'norm') #another one?\n", 377 | "print(str(p_c), str(p_k))\n", 378 | "\n", 379 | "print(\"From Stack overflow, the Kolmogorov-Smirnov is for a completely specified distribution, while the Shapiro-Wilk is for normality, with unspecified mean and variance.\")" 380 | ] 381 | }, 382 | { 383 | "cell_type": "markdown", 384 | "metadata": {}, 385 | "source": [ 386 | "*For solutions, see `solutions/scipy_normal_tests.py`*" 387 | ] 388 | }, 389 | { 390 | "cell_type": "markdown", 391 | "metadata": {}, 392 | "source": [ 393 | "### Statsmodels\n", 394 | "\n", 395 | "We will now perform a normality test using the `statsmodels` package. This package allows for higher level statistics than the `scipy` module we have been using. We will be using `statsmodels` for much of the ordinary least squares computation in future modules." 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": 15, 401 | "metadata": {}, 402 | "outputs": [], 403 | "source": [ 404 | "import statsmodels.api as sm" 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": 16, 410 | "metadata": {}, 411 | "outputs": [], 412 | "source": [ 413 | "statistic, p_value = sm.stats.diagnostic.kstest_normal(heights)" 414 | ] 415 | }, 416 | { 417 | "cell_type": "code", 418 | "execution_count": 17, 419 | "metadata": {}, 420 | "outputs": [ 421 | { 422 | "name": "stdout", 423 | "output_type": "stream", 424 | "text": [ 425 | "The data looks like it was drawn from a normal distribution\n", 426 | "p=0.395\n" 427 | ] 428 | } 429 | ], 430 | "source": [ 431 | "if p_value > 0.05:\n", 432 | " print(\"The data looks like it was drawn from a normal distribution\")\n", 433 | " print(\"p={:.3f}\".format(p_value))\n", 434 | "else:\n", 435 | " print(\"The data does not look like it was drawn from a normal distribution\")" 436 | ] 437 | }, 438 | { 439 | "cell_type": "markdown", 440 | "metadata": {}, 441 | "source": [ 442 | "#### Exercise\n", 443 | "\n", 444 | "Review the documentation for `statsmodels` at https://www.statsmodels.org and run the Jarque-Bera test for normality on this data." 445 | ] 446 | }, 447 | { 448 | "cell_type": "code", 449 | "execution_count": 18, 450 | "metadata": {}, 451 | "outputs": [ 452 | { 453 | "name": "stdout", 454 | "output_type": "stream", 455 | "text": [ 456 | "0.6714923453511482\n" 457 | ] 458 | } 459 | ], 460 | "source": [ 461 | "from statsmodels.stats import stattools\n", 462 | "\n", 463 | "jbstat, pvalue, skew, kurtosis = stattools.jarque_bera(heights)\n", 464 | "print(pvalue)" 465 | ] 466 | }, 467 | { 468 | "cell_type": "markdown", 469 | "metadata": {}, 470 | "source": [ 471 | "*For solutions, see `solutions/jarque_bera.py`*" 472 | ] 473 | }, 474 | { 475 | "cell_type": "markdown", 476 | "metadata": {}, 477 | "source": [ 478 | "### Handling conflicts\n", 479 | "\n", 480 | "There are many different normality tests. If you get the same result for all the tests (i.e. multiple tests suggest normal data), then you can be reasonably sure the data does come from a normal distribution.\n", 481 | "\n", 482 | "If you get conflicting result, the results are not quite so clear. In a conflicting case, it would be unlikely that the results will be wildly different. Instead, you are likely to get a few slightly \"above the line\" and a few slightly \"below the line\". Depending on the use case, you can interpret a single \"is normal\" result as being good enough. Much of the later analysis you can do will be fine for \"normal-like\" data, rather than strictly normal data.\n", 483 | "\n", 484 | "If you do have a very sensitive application that requires a great degree in confidence in your normality test, research further the assumptions behind different normality tests and see which are most applicable to your application. The SciPy and Statsmodels documentation contain references for each of the normality tests.\n", 485 | "\n", 486 | "A major property is the number of samples in your dataset. Some tests work better with more samples, and some work better with fewer. We will investigate this in the last exercise for this module." 487 | ] 488 | }, 489 | { 490 | "cell_type": "markdown", 491 | "metadata": {}, 492 | "source": [ 493 | "#### Exercise\n", 494 | "\n", 495 | "We are going to investigate the relationship that sample size has with the results of a normality test. We want to test the likelihood a normality test will reject the normality hypothesis for a dataset that *actually is generated from a normal distribution*, as the sample size increases.\n", 496 | "\n", 497 | "Write a script that:\n", 498 | "\n", 499 | "1. Creates a normal distribution\n", 500 | "2. Randomly samples N data points from that distribution\n", 501 | "3. Checks for normality against four different normality tests\n", 502 | "4. Repeats steps 1-3 a large number of times, and with varying N\n", 503 | "5. Plot the likelihood each test fails for a given sample size.\n", 504 | "\n", 505 | "Below is a snippet of code that runs 20 tests against one sample of data, and determines if the test determines it is normal or not. For an alpha value of 0.05, you would expect about 1 of the tests to fail on average.\n" 506 | ] 507 | }, 508 | { 509 | "cell_type": "code", 510 | "execution_count": 1, 511 | "metadata": {}, 512 | "outputs": [], 513 | "source": [ 514 | "def normality_script(sample_size, test_type, repetitions = 100):\n", 515 | " distribution = stats.norm()\n", 516 | " data = distribution.rvs(sample_size)\n", 517 | " \n", 518 | " passed = 0\n", 519 | " failed = 0\n", 520 | " for i in range(repetitions):\n", 521 | " distribution = stats.norm()\n", 522 | " data = distribution.rvs(sample_size)\n", 523 | " \n", 524 | " if test_type == \"sw\":\n", 525 | " statistic, p = stats.shapiro(data)\n", 526 | " elif test_type == \"cs\":\n", 527 | " statistic, p = stats.normaltest(data)\n", 528 | " elif test_type == \"ks\":\n", 529 | " statistic, p = stats.kstest(data, cdf = 'norm')\n", 530 | " elif test_type == \"jb\":\n", 531 | " statistic, p, skew, kurtosis = stattools.jarque_bera(data)\n", 532 | " \n", 533 | " if p > 0.05:\n", 534 | " passed += 1\n", 535 | " else:\n", 536 | " failed += 1\n", 537 | " \n", 538 | " return failed/(passed+failed)" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": 2, 544 | "metadata": {}, 545 | "outputs": [ 546 | { 547 | "name": "stderr", 548 | "output_type": "stream", 549 | "text": [ 550 | "c:\\Python311\\Lib\\site-packages\\scipy\\stats\\_stats_py.py:1736: UserWarning: kurtosistest only valid for n>=20 ... continuing anyway, n=10\n", 551 | " warnings.warn(\"kurtosistest only valid for n>=20 ... continuing \"\n" 552 | ] 553 | }, 554 | { 555 | "data": { 556 | "text/html": [ 557 | "\n", 558 | "\n", 569 | "
\n", 570 | "" 623 | ], 624 | "text/plain": [ 625 | "alt.Chart(...)" 626 | ] 627 | }, 628 | "execution_count": 2, 629 | "metadata": {}, 630 | "output_type": "execute_result" 631 | } 632 | ], 633 | "source": [ 634 | "import pandas as pd\n", 635 | "from statsmodels.stats import stattools\n", 636 | "from scipy import stats\n", 637 | "import altair as alt\n", 638 | "import numpy as np\n", 639 | "\n", 640 | "sample_sizes = [10, 30, 50, 100, 1000, 5000]\n", 641 | "#sample_sizes = np.linspace(10, max_sample_size, 20, dtype=np.int)\n", 642 | "\n", 643 | "test_types = [\"sw\", \"cs\", \"ks\", \"jb\"]\n", 644 | "data = []\n", 645 | "\n", 646 | "for size in sample_sizes:\n", 647 | " for test in test_types:\n", 648 | " p_fail = normality_script(size, test)\n", 649 | " row = [test,size,p_fail]\n", 650 | " data.append(row)\n", 651 | " \n", 652 | "\n", 653 | "df = pd.DataFrame(data, columns=['Test', 'Sample', 'Failed'])\n", 654 | "\n", 655 | "\n", 656 | "\n", 657 | "alt.Chart(df).mark_line().encode(\n", 658 | " x='Sample',\n", 659 | " y='Failed',\n", 660 | " color = 'Test'\n", 661 | ")" 662 | ] 663 | }, 664 | { 665 | "cell_type": "code", 666 | "execution_count": 3, 667 | "metadata": {}, 668 | "outputs": [ 669 | { 670 | "name": "stdout", 671 | "output_type": "stream", 672 | "text": [ 673 | "20 passed and 0 failed\n" 674 | ] 675 | } 676 | ], 677 | "source": [ 678 | "sample_size = 30\n", 679 | "passed = 0\n", 680 | "failed = 0\n", 681 | "for i in range(20):\n", 682 | " distribution = stats.norm()\n", 683 | " data = distribution.rvs(sample_size)\n", 684 | " stat, p = stats.normaltest(data)\n", 685 | " if p > 0.05:\n", 686 | " passed += 1\n", 687 | " else:\n", 688 | " failed += 1\n", 689 | "print(\"{} passed and {} failed\".format(passed, failed))" 690 | ] 691 | }, 692 | { 693 | "cell_type": "markdown", 694 | "metadata": {}, 695 | "source": [ 696 | "*For solutions see `solutions/many_normal_tests.py`*" 697 | ] 698 | } 699 | ], 700 | "metadata": { 701 | "kernelspec": { 702 | "display_name": "Python 3", 703 | "language": "python", 704 | "name": "python3" 705 | }, 706 | "language_info": { 707 | "codemirror_mode": { 708 | "name": "ipython", 709 | "version": 3 710 | }, 711 | "file_extension": ".py", 712 | "mimetype": "text/x-python", 713 | "name": "python", 714 | "nbconvert_exporter": "python", 715 | "pygments_lexer": "ipython3", 716 | "version": "3.11.0" 717 | } 718 | }, 719 | "nbformat": 4, 720 | "nbformat_minor": 2 721 | } 722 | -------------------------------------------------------------------------------- /notebooks/Module 1.5.1 - Bayesian Statistics Introduction.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Introduction to Quantitative Finance\n", 8 | "\n", 9 | "Copyright (c) 2019 Python Charmers Pty Ltd, Australia, . All rights reserved.\n", 10 | "\n", 11 | "\"Python\n", 12 | "\n", 13 | "Published under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) license. See `LICENSE.md` for details.\n", 14 | "\n", 15 | "Sponsored by Tibra Global Services, \n", 16 | "\n", 17 | "\"Tibra\n", 18 | "\n", 19 | "\n", 20 | "## Module 1.5: Bayesian inference\n", 21 | "\n", 22 | "# 1.5.1 Bayesian Statistics Introduction\n", 23 | "\n", 24 | "Classical / frequentist statistics interprets a probability as a limit of many identical trials. In the strict frequentist viewpoint, a statement such as \"The probability that party X will win the election\" is meaningless; the election will only take place once, under one set of circumstances, and will not be repeated -- so the outcome cannot be observed repeatedly and the probability of this cannot be computed. Likewise, the strict frequentist perspective is that it is meaningless to discuss probabilities associated with model parameters and other fixed but unknown quantities, such as whether it is raining right now (if you are holed up in a building). It is either raining or it is not.\n", 25 | "\n", 26 | "In practice, it is useful to be able to reason quantitatively about events that cannot and will not be repeated, or about model parameters that are fixed but unobserved, or about quantities that are fixed (deterministic) but unknown. This requires either a frequentist methodology combined with inaccurate statistical reasoning (which is rife) or a Bayesian interpretation of probability.\n", 27 | "\n", 28 | "In the Bayesian perspective, a probability encodes a degree of certainty about a proposition. It is \"subjective\": you and I may have different beliefs about a proposition. With the proposition \"it is raining\", if you heard yesterday's weather forecast, and I didn't, we may assign different probabilities the same proposition that it is raining right now.\n", 29 | "\n", 30 | "\n", 31 | "# Introduction: We all think \"Bayesian\"\n", 32 | "\n", 33 | "The Bayesian method requires that we be explicit about our uncertainty up-front and update our beliefs in the light of new evidence or data.\n", 34 | "\n", 35 | "Features of Bayesian inference:\n", 36 | "- Probability encodes our degree of certainty or uncertainty.\n", 37 | "- Unknown parameters are modelled as probability distributions.\n", 38 | "\n", 39 | "\n", 40 | "### Why use Bayesian inference?\n", 41 | "\n", 42 | "1. Because it is correct. Bayes' theorem is a theorem. If you accept the axioms of probability theory, it is true. You can ignore it, but it won't go away.\n", 43 | "\n", 44 | "2. Because it is useful for applications.\n", 45 | "3. You can incorporate your existing knowledge into the model, known as a prior.\n", 46 | "\n", 47 | "This last point is interesting. If you have some *a priori* knowledge of the event (either intuition or something more formal), you can set this as a prior in your model. This leads to faster training of your model (assuming your prior is somewhat accurate) and can lead to the discover of better models.\n", 48 | " \n", 49 | "\n", 50 | "Applications of Bayesian inference include:\n", 51 | "\n", 52 | "- prediction (e.g. outcome of an election, behaviour of asset prices, ...)\n", 53 | "- classification (does a person with these symptoms have this disease?; OCR; speech recognition)\n", 54 | "- scientific inference\n", 55 | "- hypothesis testing (single and multiple)\n", 56 | "- modelling\n", 57 | "- uncertainty analysis\n", 58 | "- physics: thermodynamics, crystallography, astronomy, ...\n", 59 | "- biology and medicine: bioinformatics (sequencing), predicting drug targets\n", 60 | "- ranking for information retrieval, spam detection, ... and other computer science applications\n", 61 | "\n", 62 | "\n", 63 | "### How to do Bayesian inference?\n", 64 | "\n", 65 | "1. Method 1: **mathematical analysis**. This is exact but requires heroic integration skills, which makes it hard to begin in the field. A more important drawback is that it tends to be intractable for complex models.\n", 66 | "\n", 67 | "2. Method 2: **probabilistic programming**. Computing power is cheap! Using simulation allows models to be more complex." 68 | ] 69 | }, 70 | { 71 | "cell_type": "markdown", 72 | "metadata": {}, 73 | "source": [ 74 | "### Probability as logic\n", 75 | "\n", 76 | "Bayesian statistics was previously called the \"method of inverse probability\" -- reasoning backwards from what we observe about the world to make quantitative inferences. Here is how [Jaynes 2003] introduces its relationship to other forms of inference.\n", 77 | "\n", 78 | "### Deductive reasoning\n", 79 | "\n", 80 | "Deductive reason can be analyzed into repeated application of two syllogisms:\n", 81 | "\n", 82 | "
\n", 83 | "\n", 84 | "
\n", 85 | "If A is true, then B is true.\n", 86 | "\n", 87 | "A is true.\n", 88 | "\n", 89 | "Therefore, B is true.\n", 90 | "
\n", 91 | "\n", 92 | "and its inverse:\n", 93 | "\n", 94 | "
\n", 95 | "If B is false, then A is false.\n", 96 | "\n", 97 | "B is false.\n", 98 | "\n", 99 | "Therefore, A is false.\n", 100 | "
\n", 101 | "\n", 102 | "
\n", 103 | "\n", 104 | "Note that these are only valid for the true/false values above. For instance, this reasoning in **invalid**: \"If A is true, then B is true -> A is false, therefore B is false\".\n", 105 | "\n", 106 | "\n", 107 | "### Intuitive reasoning\n", 108 | "\n", 109 | "As [Jaynes 2003] notes, we would like to use this kind of reasoning all the time, but most of the time **we do not have the right kind of information**. We fall back on weaker syllogisms like:\n", 110 | "\n", 111 | "
\n", 112 | "\n", 113 | "If A is true, then B is true.\n", 114 | "\n", 115 | "B is true.\n", 116 | "\n", 117 | "Therefore, A becomes more plausible.\n", 118 | "\n", 119 | "
\n", 120 | "\n", 121 | "\n", 122 | "\n", 123 | "**Example: probability of rain**\n", 124 | "\n", 125 | "A $\\equiv$ it will start to rain by 10am at the latest.\n", 126 | "\n", 127 | "B $\\equiv$ the sky will become cloudy before 10am.\n", 128 | "\n", 129 | "If you notice clouds at 9:45am, your common sense obeys the weak syllogism above. You are more likely to take an umbrella.\n", 130 | "\n", 131 | "What is the logical connection?\n", 132 | "\n", 133 | "rain $\\implies$ clouds\n", 134 | "\n", 135 | "Notice that the physical cause is in the opposite direction:\n", 136 | "\n", 137 | "clouds $\\implies$ rain\n", 138 | "\n", 139 | "Important: the **logical connection** is what is most relevant to our inference.\n", 140 | "\n", 141 | "### Weak syllogism 2\n", 142 | "\n", 143 | "There are other weaker syllogisms that we use every day in our reasoning, such as:\n", 144 | "\n", 145 | "
\n", 146 | "\n", 147 | "If A is true, then B becomes more plausible.\n", 148 | "\n", 149 | "A is false.\n", 150 | "\n", 151 | "Therefore, B becomes less plausible.\n", 152 | "\n", 153 | "
\n", 154 | "\n", 155 | "**Example: disease symptoms**\n", 156 | "\n", 157 | "Symptoms of the Zika virus include conjunctivitis (red eyes) and skin rash.\n", 158 | "\n", 159 | "This traveller doesn't have conjunctivitis or skin rash. Therefore, it is less likely that he/she has the Zika virus.\n", 160 | "\n", 161 | "### Weak syllogism 3\n", 162 | "\n", 163 | "
\n", 164 | "\n", 165 | "If A is true, then B becomes more plausible.\n", 166 | "\n", 167 | "B is true.\n", 168 | "\n", 169 | "Therefore, A becomes more plausible.\n", 170 | "\n", 171 | "
\n", 172 | "\n", 173 | "**Example:**\n", 174 | "\n", 175 | "Aston-Martin owners are usually rich.\n", 176 | "\n", 177 | "Bill Gates is rich.\n", 178 | "\n", 179 | "Therefore, it is more likely that Bill Gates owns an Aston-Martin.\n", 180 | "\n", 181 | "### Aside\n", 182 | "\n", 183 | "There are many more complex weak syllogisms that we use easily and intuitively in everyday reasoning. Polya [1945, 1954] wrote three books about plausible reasoning, pointing out many interesting examples and showing that we do plausible reasoning by applying definite rules.\n", 184 | "\n", 185 | "### Meaning for probability theory\n", 186 | "\n", 187 | "These principles may be made **quantitative**, with useful applications.\n", 188 | "\n", 189 | "How? With the Cox-Jaynes interpretation of probability theory and **Bayes theorem**.\n", 190 | "\n", 191 | "[See Terenin and Draper, \"Cox's Theorem and the Jaynesian Interpretation of Probability\"]" 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "### Bayes' theorem\n", 199 | "\n", 200 | "- $X$ = prior information\n", 201 | "- $H$ = hypothesis or model parameters\n", 202 | "- $D$ = data\n", 203 | "\n", 204 | "$$P(H | DX) = P(H | X) \\frac{P(D | HX)}{P(D | X)}$$\n", 205 | "\n", 206 | "The vertical bar means \"conditional upon\". Bayes' theorem follows simply from the definition of conditional probability: $P ( A | B ) = \\frac{P (A \\cap B)}{P(B)}$.\n", 207 | "\n", 208 | "We call these things:\n", 209 | "\n", 210 | "$$ \\textrm{posterior} = \\textrm{prior} \\times \\frac{\\textrm{likelihood}}{\\textrm{evidence}}$$\n", 211 | "\n", 212 | "### Prior information\n", 213 | "\n", 214 | "It is important to specify the **prior information** carefully before we have a well-posed problem. Then this equation tells us what probabilities we need to find in order to see what conclusions are justified by our evidence.\n", 215 | "\n", 216 | "Often this is regarded as a nuisance. It is, however, an **opportunity** to improve models, especially when data is sparse.\n", 217 | "\n", 218 | "### Data sparsity\n", 219 | "\n", 220 | "Often, in the real world, data is small / sparse / noisy / expensive to collect.\n", 221 | "\n", 222 | "See \"N is never large\", Andrew Gelman: http://andrewgelman.com/2005/07/31/n_is_never_larg/\n", 223 | "\n", 224 | "As you have more data, the posterior drifts away from the prior, **provided the prior is uninformed / flat enough**." 225 | ] 226 | }, 227 | { 228 | "cell_type": "code", 229 | "execution_count": 7, 230 | "metadata": { 231 | "attributes": { 232 | "classes": [], 233 | "id": "", 234 | "n": "1" 235 | } 236 | }, 237 | "outputs": [], 238 | "source": [ 239 | "%matplotlib inline\n", 240 | "from IPython.core.pylabtools import figsize\n", 241 | "import numpy as np\n", 242 | "from matplotlib import pyplot as plt\n", 243 | "figsize(11, 9)" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "metadata": {}, 249 | "source": [ 250 | "### Bayesian updating\n" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": 8, 256 | "metadata": { 257 | "attributes": { 258 | "classes": [], 259 | "id": "", 260 | "n": "3" 261 | } 262 | }, 263 | "outputs": [], 264 | "source": [ 265 | "%run -i bayesian_updating_plot.py" 266 | ] 267 | }, 268 | { 269 | "cell_type": "markdown", 270 | "metadata": {}, 271 | "source": [ 272 | "#### Exercises\n", 273 | "\n", 274 | "Review the code for `bayesian_updating_plot.py` and make the following changes:\n", 275 | "\n", 276 | "1. Run the analysis for 5000 trails for the last plot\n", 277 | "2. Rerun the analysis with a biased coin (i.e. one with an 80% chance of heads). Observe how the Bayesian analysis probabilities change in the new plots." 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "metadata": {}, 283 | "source": [ 284 | "*For solutions, see `solutions/bayesian_updating_2.py`*" 285 | ] 286 | }, 287 | { 288 | "cell_type": "markdown", 289 | "metadata": {}, 290 | "source": [ 291 | "### Outline of solving problems with Bayesian reasoning\n", 292 | "\n", 293 | "Tim Salimans, the winner of the Kaggle contest \"Observing Dark Words\", used Bayesian inference to find the best locations for halos. His solution is presented well in \"Bayesian Methods for Hackers\", chapter 5.\n", 294 | "\n", 295 | "Summary:\n", 296 | "\n", 297 | "### Steps to doing Bayesian inference\n", 298 | "\n", 299 | "1. Construct a prior distribution $p(H|X)$ for what you are predicting ($H$) -- i.e. formulate our expectations about the thing before looking at the data.\n", 300 | "\n", 301 | "2. Construct a probabilistic model for the data given your hypothesis / parameters and prior information: $p(D | HX)$.\n", 302 | "\n", 303 | "3. Use Bayes’ rule to calculate the posterior distribution $P(H|DX)$ of the hypothesis. In other words, use the data to determine a **probability distribution** over the unknowns.\n", 304 | "\n", 305 | "4. Minimize the expected loss with respect to the posterior distribution over the predictions for\n", 306 | "$h$: \n", 307 | "\n", 308 | "$$\n", 309 | "\\hat{h} = \\mathrm{argmin}_\\mathrm{prediction} \\mathbb{E} [L(\\mathrm{prediction}, h)]\n", 310 | "$$\n", 311 | "\n", 312 | "i.e. tune our predictions to be as good as possible for the given error metric.\n", 313 | "\n", 314 | "This may be the maximum a-posteriori (\"MAP\") estimate or something else.\n", 315 | "\n", 316 | "### Applications which benefit from strong prior information\n", 317 | "\n", 318 | "- Learning when a self-driving car should brake from LIDAR data\n", 319 | "- Learning the effectiveness of a medicine from clinical data\n", 320 | "- Learning the elasticity of demand from economic data\n", 321 | "- Learning the structure of a distant galaxy from telescopic data\n", 322 | "- Learning whether to accept or reject a box of widgets from industrial QC control data" 323 | ] 324 | }, 325 | { 326 | "cell_type": "markdown", 327 | "metadata": {}, 328 | "source": [ 329 | "### Resources\n", 330 | "\n", 331 | "### Books\n", 332 | "\n", 333 | "- Edwin T. Jaynes: \"Probability Theory: The Logic of Science\". (Cambridge University Press). A masterpiece. Deep and very interesting. \n", 334 | "\n", 335 | "- Michael I Jordan's lecture notes (UC Berkeley): https://people.eecs.berkeley.edu/~jordan/courses.html\n", 336 | "\n", 337 | "- Bayesian modeling and inference, Spring 2010\n", 338 | "- Practical machine learning, Fall 2009\n", 339 | "\n", 340 | "- D. S. Sivia with J Skilling: \"Data analysis: A Bayesian tutorial\"\n", 341 | "\n", 342 | "- MacKay: Information Theory, Inference, and Learning Algorithms\n", 343 | "\n", 344 | "- John Kruschke: Doing Bayesian Data Analysis. 2nd edition switches to JAGS and Stan (from BUGS). \"The dog book\" for the illustration of dogs on the cover.\n", 345 | "\n", 346 | "- Andrew Gelman et al. Bayesian Data Analysis. CRC Press (3rd edition). The most influential and widely used Bayesian text by statisticians.\n", 347 | "\n", 348 | "- \"Probabilistic Programming and Bayesian Methods for Hackers\": Pearson CMG. Useful because it serves as more accessible documentation to PyMC. (The official PyMC docs assume prior knowledge of Bayesian inference.)\n", 349 | "\n", 350 | "PyMC3 examples for PPBMH are available on GitHub: https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers\n", 351 | "\n", 352 | "### Software for Bayesian modelling\n", 353 | "\n", 354 | "- Stan: http://mc-stan.org. Upcoming successor to BUGS / JAGS. Compiles models to C++. Uses Hamiltonian Monte Carlo for posterior sampling.\n", 355 | "\n", 356 | "- PyMC3: http://pymc-devs.github.io/pymc3/\n", 357 | "\n", 358 | "- Edward: http://edwardlib.org. Variational inference package for Python built on TensorFlow." 359 | ] 360 | } 361 | ], 362 | "metadata": { 363 | "kernelspec": { 364 | "display_name": "Python 3", 365 | "language": "python", 366 | "name": "python3" 367 | }, 368 | "language_info": { 369 | "codemirror_mode": { 370 | "name": "ipython", 371 | "version": 3 372 | }, 373 | "file_extension": ".py", 374 | "mimetype": "text/x-python", 375 | "name": "python", 376 | "nbconvert_exporter": "python", 377 | "pygments_lexer": "ipython3", 378 | "version": "3.11.0" 379 | } 380 | }, 381 | "nbformat": 4, 382 | "nbformat_minor": 2 383 | } 384 | -------------------------------------------------------------------------------- /notebooks/Module 2.2.1 - Linear regression models.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Introduction to Quantitative Finance\n", 8 | "\n", 9 | "Copyright (c) 2019 Python Charmers Pty Ltd, Australia, . All rights reserved.\n", 10 | "\n", 11 | "\"Python\n", 12 | "\n", 13 | "Published under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) license. See `LICENSE.md` for details.\n", 14 | "\n", 15 | "Sponsored by Tibra Global Services, \n", 16 | "\n", 17 | "\"Tibra\n", 18 | "\n", 19 | "\n", 20 | "## Module 2.2: Modelling Techniques\n", 21 | "\n", 22 | "### 2.2.1 Data for Linear Regression Models\n", 23 | "\n", 24 | "In this module we will go through the Linear Regression models again in more detail, before reviewing ARMA and then enhancing it with ARIMA and GARCH. We will revisit the previous considered concepts from a more theoretical view over these two modules, and afterwards we will go back to the normal mixture of code and theory when we investigate ARIMA.\n", 25 | "\n", 26 | "\n", 27 | "### Representing Data\n", 28 | "\n", 29 | "There are four major types of data and measurements, which can become a variable in a model. However, some need to be handled differently than simply used as-is. The four major types are:\n", 30 | "\n", 31 | "* Ratio, which allows us to multiply values in the range\n", 32 | "* Interval, which doesn't allow multiplying, but allows averaging\n", 33 | "* Ordinal, which doesn't allow averaging but allows order\n", 34 | "* Nominal, also called Categorical, which do not have order\n", 35 | "\n", 36 | "Note that some authors use different names, conventions or types, but the general pattern is very consistent across multiple sources." 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "### Ratio Data\n", 44 | "\n", 45 | "The first type we will look at is **Ratio** data, which are standard numbers. They are measurements with a range, and those measurements have a clear distance between them.\n", 46 | "\n", 47 | "An example of an interval is a stock's price. It can be measured, and the differences between prices can be computed. For instance:\n", 48 | "\n", 49 | "* Company A's stock is valued at \\$100\n", 50 | "* Company B's stock is valued at \\$105\n", 51 | "\n", 52 | "We can therefore say it costs $5 more to buy a stock in Company B than it does in Company A. Further, we can say that Company B's stock is 5\\% more than Company A's stock. (If this is all seeming a bit obvious, counter examples of data that you can't do this with are coming up).\n", 53 | "\n", 54 | "A Ratio doesn't need to encapsulate all information about the samples. For instance, in the above, we don't take into consideration things such as the number of stocks in a company, the ownership proportion, or the movement in the stock price. That's fine - we are just talking about a variable, and not a full model.\n", 55 | "\n", 56 | "The next important aspect a Ratio variable has is a \"clear zero\", which makes comparisons possible of the form \"X is twice Y\". For instance, if Company C's stock was valued at $200, we can say it costs \"twice as much\" as Company A to buy. Note that ratios can be negative in some cases (not in stock prices though, although stock valuations could be negative)." 57 | ] 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "metadata": {}, 62 | "source": [ 63 | "### Interval Data\n", 64 | "\n", 65 | "**Interval** data works a lot like Ratio data. You can compute the mean and median of both, the data is obviously ordered, and you can say \"X is more than Y\".\n", 66 | "\n", 67 | "However, Interval data doesn't have a clear zero reference, known as a true zero, which makes comparisons like \"X is twice Y\" meaningless. For instance, Temperature is interval data.\n", 68 | "\n", 69 | "If Melbourne has a temperature of 15°C, and Sydney has a temperature of 30°C, we can say that Sydney has a greater temperature than Melbourne. We **cannot** say that Sydney is twice as hot at Melbourne. \n", 70 | "\n", 71 | "While this would make intuitive sense in lay speak, it actually doesn't mean anything. The reason? The units matter. If we measure in Fahrenheit, we get Melbourne's temperature as 59°F and Sydney's as 86°F, which is no longer twice, despite the underlying facts not changing.\n", 72 | "\n", 73 | "Interval data is still very useful, and you can normally just deal with it as a ratio value. This is especially true with practical data where the data sits in a normal range.\n" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "metadata": {}, 79 | "source": [ 80 | "#### Exercise\n", 81 | "\n", 82 | "Answer the following questions intuitively first, and then either research or compute the actual answers to confirm.\n", 83 | "\n", 84 | "1. Does the ratio of price of two stocks (X is 105% of Y) change if you convert the prices from USD to AUD before doing the comparison?\n", 85 | "2. Is temperature in Kelvin a Ratio or an Interval?" 86 | ] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "metadata": {}, 91 | "source": [ 92 | "1. The ratio should not change because they are both being multiple by a constant ratio\n", 93 | "2. Kelvin would be interval data. Nevermind, I was wrong, Kelvin has a clear 0." 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "metadata": {}, 99 | "source": [ 100 | "*For solutions, see `solutions/ratio_interval.py`*" 101 | ] 102 | }, 103 | { 104 | "cell_type": "markdown", 105 | "metadata": {}, 106 | "source": [ 107 | "### Ordinal Data\n", 108 | "\n", 109 | "As Interval data is like Ratio data with restrictions, **Ordinal** data is a \"restricted\" Interval. The data is ordered, but not really numerical in nature. \n", 110 | "\n", 111 | "An example is the Wong-Baker FACES Pain Rating Scale, used for helping children describe how much pain they are in to a doctor or nurse.\n", 112 | "\n", 113 | "\n", 114 | "Source: https://en.wikipedia.org/wiki/File:Wong_Baker_Scale.sr.JPG\n", 115 | "\n", 116 | "Note that even though you may not be able to read the text, you could still describe the level of pain you are in.\n", 117 | "\n", 118 | "The data is clearly ordered - a person is in more pain on level 6 of the scale than level 2. However, you wouldn't say they are in \"three times more pain\". Further, you could compute the average pain someone is in, but that value is ultimately meaningless - the different between a 4 and a 6 is not really the same as the difference between a 6 and an 8. Instead, it would make more sense to compute the median or mode, and say \"the patient normally answers around 6\", rather than say \"the average pain rating is 6.3\".\n", 119 | "\n", 120 | "Another example is the standard feedback \"How satisfied are you with our service?\", with values ranging from \"Very Unsatisfied\" to \"Very Satisfied\". There is a clear order - one would rather customers be Satisfied than Unsatisfied, and \"Very Satisfied\" is even better! However, there are not really numerical values you can assign clearly to this data. \n", 121 | "\n", 122 | "Note that some people *do* assign numerical numbers, and *do* compute the mean value - this does have some use, but is ultimately meaningless, for instance, in comparing two survey results." 123 | ] 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "metadata": {}, 128 | "source": [ 129 | "### Nominal data (Categorical)\n", 130 | "\n", 131 | "**Nominal** data, also called Categorical or Labels, are unordered categories of data. For instance, if I asked if your pet was a Dog or a Cat, there isn't a \"greater\" of these values (one could argue with this point, but not mathematically).\n", 132 | "\n", 133 | "A common type of data here is Gender. Options could include \"Female\", \"Male\" and \"Other\". They could be presented in an order, and could even get numbered labels for storing, but you can't compute the average. You *can* compute the ratio of the total (e.g. 53% Female, 46% Male, 1% Other), but it would make no sense to say the average customer is 53% Female. If anything, that sends a very different message!\n", 134 | "\n", 135 | "A two-option nominal value is also called a dichotomous variable. This could be True/False, Correct/Incorrect, Married/Not Married, and other data of the form X / not X." 136 | ] 137 | }, 138 | { 139 | "cell_type": "markdown", 140 | "metadata": {}, 141 | "source": [ 142 | "#### Questions\n", 143 | "\n", 144 | "What type of variable is the following?\n", 145 | "\n", 146 | "1. the age of a person\n", 147 | "2. the time taken for a program to run\n", 148 | "3. Level of education obtained, out of \"University degree\", \"No Education\", \"High school completed\", \"Some schooling\".\n", 149 | "4. A variable noting which doctor performed the surgery.\n" 150 | ] 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "metadata": {}, 155 | "source": [ 156 | "1. Ratio\n", 157 | "2. Ratio\n", 158 | "3. Ordinal\n", 159 | "4. Nominal" 160 | ] 161 | }, 162 | { 163 | "cell_type": "markdown", 164 | "metadata": {}, 165 | "source": [ 166 | "*For solutions, see `solutions/ordinal_nominal.py`*" 167 | ] 168 | }, 169 | { 170 | "cell_type": "markdown", 171 | "metadata": {}, 172 | "source": [ 173 | "### Dealing with nominal and ordinal data types\n", 174 | "\n", 175 | "In statistics and programming, the programs we write often assume data is at least Interval, and perhaps Ratio. We freely compute the mean of data (even if that doesn't make sense) and report the result. One of the key problems here is that we often use numbers to encode variables. For instance, in our gender question, we might assign the following numbers:\n", 176 | "\n", 177 | "* Male: 0\n", 178 | "* Female: 1\n", 179 | "* Other: 2\n", 180 | "\n", 181 | "Therefore, our data looks like this: `gender = [0, 0, 1, 1, 1, 0, 2]`, indicating Male, Male, Female, Female, and so on. This means that technically we can compute `np.mean(gender)`, and that operation will work. Further, we could fit a OLS model on this data, and that will probably also show something.\n", 182 | "\n", 183 | "To better encode the gender variable, a one-hot encoding is normally recommended. This expands the data into multiple variables of the form \"Is Male?\", \"Is Female?\" and \"Is Other?\". Only, and exactly, one of these three will be 1, and the others will be always 0. This turns this into a dichotomous nominal variable, which can actually be used as a ratio!\n", 184 | "\n", 185 | "\n", 186 | "
\n", 187 | " Gender is nearly dichotomous for the general population - most people identify as either male or female. You can do things with dichotomous variables like compute the ratio from the mean, but if you do, you will run the risk of your results being meaningless in some samples.\n", 188 | "
\n", 189 | "\n", 190 | "\n", 191 | "You can encode ordinal data the same way. You do lose some data doing this though, as it turns your ordinal data into nominal data." 192 | ] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "metadata": {}, 197 | "source": [ 198 | "#### Exercise\n", 199 | "\n", 200 | "1. Review the documentation for Scikit-learn's OrdinalEncoder and OneHotEncoder transformers. What do they do?\n", 201 | "\n", 202 | "\n", 203 | "#### Extended Exercise\n", 204 | "\n", 205 | "1. What is the problem with the name of Scikit-Learn's Ordinal Encoder?\n", 206 | "1. Load some data that contains ordinal and nominal variables (e.g. Boston house prices). Convert the ordinal and nominal variables to encoded forms using the above scikit-learn classes." 207 | ] 208 | }, 209 | { 210 | "cell_type": "markdown", 211 | "metadata": {}, 212 | "source": [ 213 | "*For solutions see `solutions/ordinal_encoding.py`*" 214 | ] 215 | }, 216 | { 217 | "cell_type": "markdown", 218 | "metadata": {}, 219 | "source": [ 220 | "### Formats for data\n", 221 | "\n", 222 | "Our data is usually called $X$, specifically a 2 dimensional matrix, where the rows correspond to each sample in our dataset (like a stock data for a day, a company, or a person), and columns correspond to features, or variables (such as the closing price, the number of employees or the person's height).\n", 223 | "\n", 224 | "Therefore, value $X_{i, j}$ is the value of the $j$th variable for the $i$th sample.\n", 225 | "\n", 226 | "Normally, we use the term $n$ to describe how many samples we have, and $k$ to describe how many variables. If no other information is given, assume these values. That said, lots of other terms are used as well (for instance, $m$ is usually used if a second set of data is included for the number of samples in that second set).\n", 227 | "\n", 228 | "Therefore, our matrix $X$ has shape $n \\times k$.\n", 229 | "\n", 230 | "Next, we have our coefficients, which are $\\beta$, and this is a value for each variable, so it has shape $k$. Often, it is much more useful for this to be a 2D array of size $k \\times 1$. This allows us to compute the values $X\\beta$, which gives a $n \\times 1$ value, which is $Y$.\n", 231 | "\n", 232 | "\n", 233 | "#### Question\n", 234 | "\n", 235 | "If $u$ is the error term associated with each sample, what would its shape be?" 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "metadata": {}, 241 | "source": [ 242 | "nx1" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "*For solutions, see `solutions/error_term_u.py`*" 250 | ] 251 | }, 252 | { 253 | "cell_type": "markdown", 254 | "metadata": {}, 255 | "source": [ 256 | "### Samples versus Population, and Notation\n", 257 | "\n", 258 | "To date, these modules have been a little slack with terminology relating to samples versus populations. We will address that here before we continue further.\n", 259 | "\n", 260 | "If we remember our equation for our Linear Regression model, it has been presented so far like this:\n", 261 | "\n", 262 | "$Y = X \\beta + u$\n", 263 | "\n", 264 | "In this case, we have $X$ as our independent variables in the format above. $\\beta$ is the set of *actual parameters for mapping the linear relationship*. In other words, if there was a perfect computer simulation of the world, the relationship between $X$ and $y$ would be perfectly modelled by this equation. Note that we may not know these true values - we may never know these actual values. (They may not actually exist either, but the assumptions behind a linear model assume they do.)\n", 265 | "\n", 266 | "Finally, $u$ is the error of the model, which really is just what is left over from taking the values of $\\beta$, and then computing $u = Y - \\beta X$. These are the errors, but they are the *actual population errors*, again that are quite theoretical and you may never know what these are. Further, the values of $u$ are not learned, they are the remaining error. It may seem odd that we need $u$ if $\\beta$ is perfectly defined, but note that sometimes the same values for $x$ may result in a different $y$ value. If the $\\beta$ values are fixed, then the only way we can distinguish is through $u$.\n", 267 | "\n", 268 | "The above equations deal with ground truth population data, however almost always you are working with sample data. This means that we don't have all $X$ values. This means that, at best, we can estimate the true values for $\\beta$, so we use the notation $\\hat{\\beta}$ to denote we have an estimation of $\\beta$, not the true values.\n", 269 | "\n", 270 | "As we do not know the true values for $\\beta$, the errors we get in the model are just estimated too, so we use the notation $\\hat{u}$. Then, finally, we come to our $Y$ values being estimated, so we use the notation $\\hat{Y}$ to describe them, or $\\hat{y}$ to describe the predicted value for a given $y$ value.\n", 271 | "\n", 272 | "So while OLS is aiming to get as close to the true values as possible, what we are really learning is:\n", 273 | "\n", 274 | "$\\hat{Y} = X \\hat{\\beta} + \\hat{u}$\n", 275 | "\n", 276 | "Other notation may use $\\textbf{b}$ as the learned and estimated values for the true values of $\\beta$.\n", 277 | "\n", 278 | "This confuses the notation to keep doing this, and have separate symbols for effectively the same thing. For these notebooks, we won't be too particular about the specific symbols and \"hats\" for them. Know however, that if you ever publish a journal paper in an academic journal, you'll need to ensure you have all the symbols correctly identified.\n", 279 | "\n", 280 | "At the end of the day, notation is just notation - simply describe what your variables are upfront if you do not know the normal terminology to use.\n", 281 | "\n", 282 | "#### Question\n", 283 | "\n", 284 | "Why is $\\beta$ presented after $X$ in the previous equations, and not on the left? Hint: they are matrices" 285 | ] 286 | }, 287 | { 288 | "cell_type": "markdown", 289 | "metadata": {}, 290 | "source": [ 291 | "X dimensions is n x k, B dimensions is k x 1, hence needs to be that way." 292 | ] 293 | }, 294 | { 295 | "cell_type": "markdown", 296 | "metadata": {}, 297 | "source": [ 298 | "*For solutions, see `solutions/dot.py`*" 299 | ] 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "metadata": {}, 304 | "source": [ 305 | "### Basics of Prediction\n", 306 | "\n", 307 | "We will finish this module with a mid-point revision of some of the basics covered so far, but specifically with a view to prediction in the Linear Regression space.\n", 308 | "\n", 309 | "The most basic, reasonable, prediction algorithm is simply to predict the mean of your sample of data. This is the best estimator if you have just one variable. i.e. if we have *just* the heights for lots of dogs, and want to do the best guess of the next dog's height, we just use the mean. This is mathematically proven as the best estimate you can get - known as the *expected value*.\n", 310 | "\n", 311 | "Our model is therefore of the form:\n", 312 | "\n", 313 | "$\\hat{y} = \\bar{x} + u$\n", 314 | "\n", 315 | "Where $\\bar{x}$ is the mean of $X$ and $u$ is the errors, the residuals. These residuals are the difference between the prediction and the actual value. You'll often hear this referred to as a measure of the \"Goodness of fit\".\n", 316 | "\n", 317 | "The sum of squared error (SSE) is a commonly used metric in comparing two models to determine which is better. It is the sum of the squared of these residuals, therefore:\n", 318 | "\n", 319 | "$SSE = \\sum{u^2}$\n", 320 | "\n", 321 | "For a single set of values, the mean is the value that minimises the SSE in a single row of data. This is why, according to this model, the mean is the best predictor if we have no other data.\n", 322 | "\n", 323 | "The goal of linear regression is to minimise the SSE when we use multiple independent variables to predict a dependent variable. This is only one evaluation metric - there are dozens of commonly used ones, and for financial data we might be more concerned with \"absolute profit\" or some other metric more closely tied to business outcomes. Use the evaluation metric that works for your application. SSE has some nice algorithmic properties, for instance, you can compute the gradient at all points, allowing for solving the OLS algorithm quickly to minimise SSE. Not all metrics are as nice.\n", 324 | "\n", 325 | "When you fit any model to data, and want to evaluate how well it does in practice, you must fit your model on one set of data, and evaluate it on another set of data. This is known as a train/test split. You fit your data on the training data, and evaluate on the testing data. A common split is simply to split randomly 1/3 of the data for testing, and the remaining 2/3 for training. The exact numbers usually don't matter too much. If you are using a time series dataset, you'll need to split by time rather than randomly. Think always about how your model will be used in practice - for price prediction, you want to be predicting tomorrow's price, not some random day in the past. Therefore, your model needs to be evaluated when it's trying to predict data in the future.\n", 326 | "\n", 327 | "\n", 328 | "#### Exercise\n", 329 | "\n", 330 | "An issue with train/test splits, is that you must, by definition, lose the learning power of 1/3 of your dataset (or whatever you put into the test split). To address this, use cross-validation.\n", 331 | "\n", 332 | "Review the documentation for scikit-learn's cross-validation functions at https://scikit-learn.org/stable/modules/cross_validation.html\n", 333 | "\n", 334 | "What does cross-validation do, and why is it better than a simple train/test split?\n", 335 | "\n", 336 | "Why is there an *additional* test split in the diagram?\n" 337 | ] 338 | }, 339 | { 340 | "cell_type": "markdown", 341 | "metadata": {}, 342 | "source": [ 343 | "Multiple train test splits, can use smaller test sets depending on sample size, and average the results." 344 | ] 345 | }, 346 | { 347 | "cell_type": "markdown", 348 | "metadata": {}, 349 | "source": [ 350 | "*For solutions, see `solutions/cross_validation_one.py`*" 351 | ] 352 | } 353 | ], 354 | "metadata": { 355 | "kernelspec": { 356 | "display_name": "Python 3", 357 | "language": "python", 358 | "name": "python3" 359 | }, 360 | "language_info": { 361 | "codemirror_mode": { 362 | "name": "ipython", 363 | "version": 3 364 | }, 365 | "file_extension": ".py", 366 | "mimetype": "text/x-python", 367 | "name": "python", 368 | "nbconvert_exporter": "python", 369 | "pygments_lexer": "ipython3", 370 | "version": "3.7.4" 371 | } 372 | }, 373 | "nbformat": 4, 374 | "nbformat_minor": 4 375 | } 376 | -------------------------------------------------------------------------------- /notebooks/Module 2.3.2 - Confidence Intervals.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Introduction to Quantitative Finance\n", 8 | "\n", 9 | "Copyright (c) 2019 Python Charmers Pty Ltd, Australia, . All rights reserved.\n", 10 | "\n", 11 | "\"Python\n", 12 | "\n", 13 | "Published under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) license. See `LICENSE.md` for details.\n", 14 | "\n", 15 | "Sponsored by Tibra Global Services, \n", 16 | "\n", 17 | "\"Tibra\n", 18 | "\n", 19 | "\n", 20 | "## Module 2.3: Testing and Benchmarking\n", 21 | "\n", 22 | "### 2.3.2 Confidence Intervals\n", 23 | "\n", 24 | "A statistical analysis without discussion of confidence or range is not complete.\n", 25 | "\n", 26 | "Statistics is about dealing with uncertainty, and when a statistical analysis gives a confident \"the mean is 3.2\" result, there is information missing here, specifically around how confident we are in that result and where we can reasonably expect the *actual* value to end up. This is also why political polls jump around so much in the news - they don't really, just that newspapers rarely report confidence intervals, so when sample mean naturally jumps around, this is the only value that is reported.\n", 27 | "\n", 28 | "Confidence intervals are a key measure to use here, and one of the easiest to explain, especially to non-statistical stakeholders. A confidence interval for a given estimate, at a given threshold X% is an interval for where X% of the expected values sit in that interval. Let's look at an example:" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 1, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "%run setup.ipy" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 2, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "# Module from 1.3.2 - Multivariate OLS" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 2, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "import quandl\n", 56 | "\n", 57 | "interest_rates = quandl.get(\"RBA/F13_FOOIRATCR\")\n", 58 | "interest_rates = interest_rates[interest_rates.columns[0]] # Extract the first column, whatever it is called\n", 59 | "interest_rates.name = \"InterestRate\" # Rename, as the original had a long name. Hint: don't use spaces or special chars" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 3, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "inflation = quandl.get(\"RBA/G01_GCPIAGSAQP\")\n", 69 | "inflation.columns = ['Inflation']" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 4, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "au_dollar = quandl.get(\"BUNDESBANK/BBEX3_M_AUD_USD_CM_AC_A01\")['Value']\n", 79 | "au_dollar.name = \"AUDUSD\"" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": 5, 85 | "metadata": {}, 86 | "outputs": [], 87 | "source": [ 88 | "data = pd.concat([interest_rates, inflation, au_dollar], axis=1) # Combines multiple series into a DataFrame" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": 6, 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "\n", 98 | "import statsmodels.formula.api as smf\n", 99 | "est = smf.ols(formula='Inflation ~ InterestRate + AUDUSD', data=data).fit() # Does the constant for us" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 7, 105 | "metadata": {}, 106 | "outputs": [ 107 | { 108 | "data": { 109 | "text/html": [ 110 | "\n", 111 | "\n", 112 | "\n", 113 | " \n", 114 | "\n", 115 | "\n", 116 | " \n", 117 | "\n", 118 | "\n", 119 | " \n", 120 | "\n", 121 | "\n", 122 | " \n", 123 | "\n", 124 | "\n", 125 | " \n", 126 | "\n", 127 | "\n", 128 | " \n", 129 | "\n", 130 | "\n", 131 | " \n", 132 | "\n", 133 | "\n", 134 | " \n", 135 | "\n", 136 | "\n", 137 | " \n", 138 | "\n", 139 | "
OLS Regression Results
Dep. Variable: Inflation R-squared: 0.102
Model: OLS Adj. R-squared: 0.087
Method: Least Squares F-statistic: 6.929
Date: Fri, 09 Feb 2024 Prob (F-statistic): 0.00141
Time: 01:28:37 Log-Likelihood: -100.11
No. Observations: 125 AIC: 206.2
Df Residuals: 122 BIC: 214.7
Df Model: 2
Covariance Type: nonrobust
\n", 140 | "\n", 141 | "\n", 142 | " \n", 143 | "\n", 144 | "\n", 145 | " \n", 146 | "\n", 147 | "\n", 148 | " \n", 149 | "\n", 150 | "\n", 151 | " \n", 152 | "\n", 153 | "
coef std err t P>|t| [0.025 0.975]
Intercept 0.2446 0.308 0.794 0.429 -0.365 0.855
InterestRate 0.0646 0.017 3.720 0.000 0.030 0.099
AUDUSD 0.0730 0.385 0.190 0.850 -0.688 0.834
\n", 154 | "\n", 155 | "\n", 156 | " \n", 157 | "\n", 158 | "\n", 159 | " \n", 160 | "\n", 161 | "\n", 162 | " \n", 163 | "\n", 164 | "\n", 165 | " \n", 166 | "\n", 167 | "
Omnibus: 49.562 Durbin-Watson: 1.909
Prob(Omnibus): 0.000 Jarque-Bera (JB): 455.460
Skew: 0.997 Prob(JB): 1.25e-99
Kurtosis: 12.136 Cond. No. 56.6


Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified." 168 | ], 169 | "text/plain": [ 170 | "\n", 171 | "\"\"\"\n", 172 | " OLS Regression Results \n", 173 | "==============================================================================\n", 174 | "Dep. Variable: Inflation R-squared: 0.102\n", 175 | "Model: OLS Adj. R-squared: 0.087\n", 176 | "Method: Least Squares F-statistic: 6.929\n", 177 | "Date: Fri, 09 Feb 2024 Prob (F-statistic): 0.00141\n", 178 | "Time: 01:28:37 Log-Likelihood: -100.11\n", 179 | "No. Observations: 125 AIC: 206.2\n", 180 | "Df Residuals: 122 BIC: 214.7\n", 181 | "Df Model: 2 \n", 182 | "Covariance Type: nonrobust \n", 183 | "================================================================================\n", 184 | " coef std err t P>|t| [0.025 0.975]\n", 185 | "--------------------------------------------------------------------------------\n", 186 | "Intercept 0.2446 0.308 0.794 0.429 -0.365 0.855\n", 187 | "InterestRate 0.0646 0.017 3.720 0.000 0.030 0.099\n", 188 | "AUDUSD 0.0730 0.385 0.190 0.850 -0.688 0.834\n", 189 | "==============================================================================\n", 190 | "Omnibus: 49.562 Durbin-Watson: 1.909\n", 191 | "Prob(Omnibus): 0.000 Jarque-Bera (JB): 455.460\n", 192 | "Skew: 0.997 Prob(JB): 1.25e-99\n", 193 | "Kurtosis: 12.136 Cond. No. 56.6\n", 194 | "==============================================================================\n", 195 | "\n", 196 | "Notes:\n", 197 | "[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.\n", 198 | "\"\"\"" 199 | ] 200 | }, 201 | "execution_count": 7, 202 | "metadata": {}, 203 | "output_type": "execute_result" 204 | } 205 | ], 206 | "source": [ 207 | "est.summary()" 208 | ] 209 | }, 210 | { 211 | "cell_type": "markdown", 212 | "metadata": {}, 213 | "source": [ 214 | "If we let our `InterestRate` variable be $X_1$, then we can see that our model gives a 95% confidence interval between a low of 0.030 and a high of 0.102 (your results may change, see this line):\n", 215 | "\n", 216 | "" 217 | ] 218 | }, 219 | { 220 | "cell_type": "markdown", 221 | "metadata": {}, 222 | "source": [ 223 | "A key part of the need for a confidence interval is that we almost always have error in our estimate, at the very least due to the sample we take. This is true even for things that seem ground truth. For instance, if we are predicting stock prices based on the close price, we have a sampling error - if the market closed a second earlier, we may get a different close price.\n", 224 | "\n", 225 | "Confidence intervals can be calculated lots of different ways, and the general process is the same whether your process is a classical statistical one, a Bayesian or a Simulation methodology.\n", 226 | "\n", 227 | "* For classical statistics, many distribution types have a method to compute the confidence interval, based on manipulation of the equations of those distributions. See `scipy.stats.norm.interval` for information on how to do this for a normal distribution. One example that most have heard about is \"for a normal distribution, 95% of values fit within two standard errors\".\n", 228 | "* For Bayesian statistics and simulations, the formulas and simulations create confidence intervals through their varied predictions. Create many bootstrap samples (same size as the original sample, however sampled with replacement) and compute the statistic for each bootstrap sample. After sorting, take the value 2.5% of the way through the data, and 97.5% of the way through. This range is the 95% confidence interval. This process is generally known as the bootstrap method.\n", 229 | "\n", 230 | "As noted in the previous notebook, the value of 95 in \"95% confidence interval\" has literally no special meaning - it is just a value many people choose. Don't use this value without some thought about it, especially if you are making decisions related to this value." 231 | ] 232 | }, 233 | { 234 | "cell_type": "markdown", 235 | "metadata": {}, 236 | "source": [ 237 | "A common usage of confidence intervals is to see if a given value sits within it, provide a pseudo-likelihood that value is \"possible\". For instance, if the 95% confidence interval for the slope of a line contains 0, some would say there is a possibility of \"no correlation\" between the two. As noted in the last notebook, this confuses the term and is not a reliable methodology to use.\n", 238 | "\n", 239 | "Like p-values, confidence intervals are often misinterpreted. If you get a confidence interval of $a$ and $b$, this does **not** mean that 95% of individual measurements will fit between $a$ and $b$. It means that when we take samples (of the same size we used to compute the confidence interval), 95% of the values for the calculated statistic (such as the mean), will fit inside those bounds.\n", 240 | "\n", 241 | "As a note on reporting, you generally shouldn't give confidence intervals to too many decimal places. Saying \"the confidence interval for average height is between 162 and 182cm\" is better than saying \"the confidence interval is between 162.243cm and 182.976cm\", because the latter makes it seem like the process is much more formal than it really is. Remember you likely just used a 95% confidence interval because that's what most people use.\n", 242 | "\n", 243 | "Using the bootstrap method, we are not limited to computing the confidence interval on the mean, as we are with more classical statistics (well, not limited, but it is very hard to do much else). The resampling method used in bootstrap statistics allows for us to calculate arbitrary statistics from the dataset.\n", 244 | "\n", 245 | "Confidence intervals are affected by two main factors:\n", 246 | "\n", 247 | "* Sample size. Larger sample sizes lead to lower confidence intervals, due to the fact that the sample is \"more like\" the population, by virtue of having more of the population in it. Therefore, all samples are \"more like\" each other, and our interval will be smaller.\n", 248 | "* Variation within the population. Confidence intervals are wider when the variation in the population itself is wider. This makes samples \"less like\" each other, leading to greater different values in different samples." 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": {}, 254 | "source": [ 255 | "#### Exercise\n", 256 | "\n", 257 | "1. Plot the interest rates data above using `altair`, as a line plot.\n", 258 | "2. Add error bars to your plot. See the Altair gallery for examples on how to do this.\n", 259 | "3. Fit a normal distribution to the means-of-samples of the interest rate data (i.e. sample the data, compute the mean, repeat many times). Compute the confidence interval using the `scipy.stats.norm.interval` method.\n", 260 | "4. Use a bootstrap method, where you sort all the sample means and take the 95% confidence interval as the \"middle 95%\" noted above.\n", 261 | "5. Compare the results from (3) and (4)" 262 | ] 263 | }, 264 | { 265 | "cell_type": "markdown", 266 | "metadata": {}, 267 | "source": [ 268 | "From the solutions" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": 8, 274 | "metadata": {}, 275 | "outputs": [ 276 | { 277 | "data": { 278 | "text/html": [ 279 | "\n", 280 | "\n", 291 | "
\n", 292 | "" 345 | ], 346 | "text/plain": [ 347 | "alt.LayerChart(...)" 348 | ] 349 | }, 350 | "execution_count": 8, 351 | "metadata": {}, 352 | "output_type": "execute_result" 353 | } 354 | ], 355 | "source": [ 356 | "# 1 & 2\n", 357 | "d = data.reset_index().dropna()\n", 358 | "d[\"std\"] = np.std(d[\"InterestRate\"]) # Add a column for std\n", 359 | "\n", 360 | "import altair as alt\n", 361 | "\n", 362 | "# the base chart\n", 363 | "base = alt.Chart(d).transform_calculate(\n", 364 | " ymin=\"datum.InterestRate-datum.std\",\n", 365 | " ymax=\"datum.InterestRate+datum.std\"\n", 366 | ")\n", 367 | "# Data Line\n", 368 | "line = base.mark_line().encode(x=\"Date\", y=\"InterestRate\")\n", 369 | "# Error Bars\n", 370 | "bar = base.mark_errorbar().encode(x=\"Date\", y=\"ymin:Q\", y2=\"ymax:Q\")\n", 371 | "line + bar" 372 | ] 373 | }, 374 | { 375 | "cell_type": "code", 376 | "execution_count": 10, 377 | "metadata": {}, 378 | "outputs": [ 379 | { 380 | "data": { 381 | "text/plain": [ 382 | "(4.127339872446008, 5.456089460887325)" 383 | ] 384 | }, 385 | "execution_count": 10, 386 | "metadata": {}, 387 | "output_type": "execute_result" 388 | } 389 | ], 390 | "source": [ 391 | "# 3\n", 392 | "from math import sqrt\n", 393 | "pool = data[\"InterestRate\"].dropna()\n", 394 | "\n", 395 | "sample_size = int(len(pool)/5)\n", 396 | "iters = range(1000)\n", 397 | "means = []\n", 398 | "\n", 399 | "for i in iters:\n", 400 | " sample = np.random.choice(pool, sample_size)\n", 401 | " means.append(np.mean(sample))\n", 402 | "\n", 403 | "mu = np.mean(means)\n", 404 | "std = np.std(means)\n", 405 | "stats.norm.interval(0.95, loc=mu, scale=std)" 406 | ] 407 | }, 408 | { 409 | "cell_type": "code", 410 | "execution_count": 12, 411 | "metadata": {}, 412 | "outputs": [ 413 | { 414 | "data": { 415 | "text/plain": [ 416 | "(4.153999999999999, 5.554666666666667)" 417 | ] 418 | }, 419 | "execution_count": 12, 420 | "metadata": {}, 421 | "output_type": "execute_result" 422 | } 423 | ], 424 | "source": [ 425 | "# 4 \n", 426 | "pool = data[\"InterestRate\"].dropna()\n", 427 | "\n", 428 | "sample_size = int(len(pool)/5)\n", 429 | "iters = range(1000)\n", 430 | "means = []\n", 431 | "\n", 432 | "for i in iters:\n", 433 | " sample = np.random.choice(pool, sample_size)\n", 434 | " means.append(np.mean(sample))\n", 435 | "\n", 436 | "idx_lower = int(len(means)*.025)\n", 437 | "idx_upper = int(len(means)*.975)\n", 438 | "sorted_means = np.sort(means)\n", 439 | "lower = sorted_means[idx_lower]\n", 440 | "upper = sorted_means[idx_upper]\n", 441 | "lower, upper" 442 | ] 443 | }, 444 | { 445 | "cell_type": "markdown", 446 | "metadata": {}, 447 | "source": [ 448 | "Very similar results, as expected from 1000 samples." 449 | ] 450 | }, 451 | { 452 | "cell_type": "markdown", 453 | "metadata": {}, 454 | "source": [ 455 | "*For solutions, see `solutions/confidence_intervals.py`*" 456 | ] 457 | }, 458 | { 459 | "cell_type": "markdown", 460 | "metadata": {}, 461 | "source": [ 462 | "### Worked Example\n", 463 | "\n", 464 | "In this worked example, we will compute the 90% confidence interval for the proportion of times the following is true:\n", 465 | "\n", 466 | " If the price of IBM increases on a given day, Microsoft will increase the following day.\n", 467 | "\n", 468 | "To do this, we first get our data, and then take a sample. We'll use daily closing prices to determine \"increase\". \n", 469 | "\n", 470 | "Note also we aren't testing a correlation. We don't care so much about \"if IBM drops, will Microsoft drop?\", just that if IBM increases, Microsoft will)." 471 | ] 472 | }, 473 | { 474 | "cell_type": "code", 475 | "execution_count": 13, 476 | "metadata": {}, 477 | "outputs": [], 478 | "source": [ 479 | "ibm = quandl.get(\"WIKI/IBM\")['Close']" 480 | ] 481 | }, 482 | { 483 | "cell_type": "code", 484 | "execution_count": 14, 485 | "metadata": {}, 486 | "outputs": [], 487 | "source": [ 488 | "msft = quandl.get(\"WIKI/MSFT\")['Close']" 489 | ] 490 | }, 491 | { 492 | "cell_type": "code", 493 | "execution_count": 15, 494 | "metadata": {}, 495 | "outputs": [ 496 | { 497 | "data": { 498 | "text/plain": [ 499 | "Date\n", 500 | "1986-03-13 28.00\n", 501 | "1986-03-14 29.00\n", 502 | "1986-03-17 29.50\n", 503 | "1986-03-18 28.75\n", 504 | "1986-03-19 28.25\n", 505 | "Name: Close, dtype: float64" 506 | ] 507 | }, 508 | "execution_count": 15, 509 | "metadata": {}, 510 | "output_type": "execute_result" 511 | } 512 | ], 513 | "source": [ 514 | "msft.head()" 515 | ] 516 | }, 517 | { 518 | "cell_type": "code", 519 | "execution_count": 16, 520 | "metadata": {}, 521 | "outputs": [], 522 | "source": [ 523 | "# Combine to make analysis easier\n", 524 | "stocks = pd.DataFrame({\"ibm\": ibm, \"msft\": msft})" 525 | ] 526 | }, 527 | { 528 | "cell_type": "markdown", 529 | "metadata": {}, 530 | "source": [ 531 | "Next, we compute the two intermediate pieces of information:\n", 532 | "\n", 533 | "1. Did IBM increase on the day?\n", 534 | "2. Did MSFT increase on the day?\n", 535 | "\n", 536 | "We can then offset (2) to be \"Did MSFT increase the day after?\":" 537 | ] 538 | }, 539 | { 540 | "cell_type": "code", 541 | "execution_count": 17, 542 | "metadata": {}, 543 | "outputs": [], 544 | "source": [ 545 | "stocks['ibm_up'] = stocks['ibm'].diff() > 0\n", 546 | "stocks['msft_up'] = stocks['msft'].diff() > 0" 547 | ] 548 | }, 549 | { 550 | "cell_type": "code", 551 | "execution_count": 18, 552 | "metadata": {}, 553 | "outputs": [], 554 | "source": [ 555 | "stocks.dropna(inplace=True, how='any') # Removes rows missing some data. Effectively starts from MSFT IPO" 556 | ] 557 | }, 558 | { 559 | "cell_type": "code", 560 | "execution_count": 19, 561 | "metadata": {}, 562 | "outputs": [ 563 | { 564 | "data": { 565 | "text/html": [ 566 | "
\n", 567 | "\n", 580 | "\n", 581 | " \n", 582 | " \n", 583 | " \n", 584 | " \n", 585 | " \n", 586 | " \n", 587 | " \n", 588 | " \n", 589 | " \n", 590 | " \n", 591 | " \n", 592 | " \n", 593 | " \n", 594 | " \n", 595 | " \n", 596 | " \n", 597 | " \n", 598 | " \n", 599 | " \n", 600 | " \n", 601 | " \n", 602 | " \n", 603 | " \n", 604 | " \n", 605 | " \n", 606 | " \n", 607 | " \n", 608 | " \n", 609 | " \n", 610 | " \n", 611 | " \n", 612 | " \n", 613 | " \n", 614 | " \n", 615 | " \n", 616 | " \n", 617 | " \n", 618 | " \n", 619 | " \n", 620 | " \n", 621 | " \n", 622 | " \n", 623 | " \n", 624 | " \n", 625 | " \n", 626 | " \n", 627 | " \n", 628 | " \n", 629 | " \n", 630 | " \n", 631 | " \n", 632 | " \n", 633 | " \n", 634 | "
ibmmsftibm_upmsft_up
Date
1986-03-13150.5028.00TrueFalse
1986-03-14150.3829.00FalseTrue
1986-03-17150.8829.50TrueTrue
1986-03-18152.3828.75TrueFalse
1986-03-19151.6328.25FalseFalse
\n", 635 | "
" 636 | ], 637 | "text/plain": [ 638 | " ibm msft ibm_up msft_up\n", 639 | "Date \n", 640 | "1986-03-13 150.50 28.00 True False\n", 641 | "1986-03-14 150.38 29.00 False True\n", 642 | "1986-03-17 150.88 29.50 True True\n", 643 | "1986-03-18 152.38 28.75 True False\n", 644 | "1986-03-19 151.63 28.25 False False" 645 | ] 646 | }, 647 | "execution_count": 19, 648 | "metadata": {}, 649 | "output_type": "execute_result" 650 | } 651 | ], 652 | "source": [ 653 | "stocks.head()" 654 | ] 655 | }, 656 | { 657 | "cell_type": "code", 658 | "execution_count": 20, 659 | "metadata": {}, 660 | "outputs": [], 661 | "source": [ 662 | "# Offset msft_up to be \"will it increase tomorrow?\"\n", 663 | "stocks['msft_up_tomorrow'] = stocks['msft_up'].shift(-1) # -1 \"shifts upwards\"" 664 | ] 665 | }, 666 | { 667 | "cell_type": "code", 668 | "execution_count": 21, 669 | "metadata": {}, 670 | "outputs": [ 671 | { 672 | "data": { 673 | "text/html": [ 674 | "
\n", 675 | "\n", 688 | "\n", 689 | " \n", 690 | " \n", 691 | " \n", 692 | " \n", 693 | " \n", 694 | " \n", 695 | " \n", 696 | " \n", 697 | " \n", 698 | " \n", 699 | " \n", 700 | " \n", 701 | " \n", 702 | " \n", 703 | " \n", 704 | " \n", 705 | " \n", 706 | " \n", 707 | " \n", 708 | " \n", 709 | " \n", 710 | " \n", 711 | " \n", 712 | " \n", 713 | " \n", 714 | " \n", 715 | " \n", 716 | " \n", 717 | " \n", 718 | " \n", 719 | " \n", 720 | " \n", 721 | " \n", 722 | " \n", 723 | " \n", 724 | " \n", 725 | " \n", 726 | " \n", 727 | " \n", 728 | " \n", 729 | " \n", 730 | " \n", 731 | " \n", 732 | " \n", 733 | " \n", 734 | " \n", 735 | " \n", 736 | " \n", 737 | " \n", 738 | " \n", 739 | " \n", 740 | " \n", 741 | " \n", 742 | " \n", 743 | " \n", 744 | " \n", 745 | " \n", 746 | " \n", 747 | " \n", 748 | " \n", 749 | "
ibmmsftibm_upmsft_upmsft_up_tomorrow
Date
1986-03-13150.5028.00TrueFalseTrue
1986-03-14150.3829.00FalseTrueTrue
1986-03-17150.8829.50TrueTrueFalse
1986-03-18152.3828.75TrueFalseFalse
1986-03-19151.6328.25FalseFalseFalse
\n", 750 | "
" 751 | ], 752 | "text/plain": [ 753 | " ibm msft ibm_up msft_up msft_up_tomorrow\n", 754 | "Date \n", 755 | "1986-03-13 150.50 28.00 True False True\n", 756 | "1986-03-14 150.38 29.00 False True True\n", 757 | "1986-03-17 150.88 29.50 True True False\n", 758 | "1986-03-18 152.38 28.75 True False False\n", 759 | "1986-03-19 151.63 28.25 False False False" 760 | ] 761 | }, 762 | "execution_count": 21, 763 | "metadata": {}, 764 | "output_type": "execute_result" 765 | } 766 | ], 767 | "source": [ 768 | "stocks.head()" 769 | ] 770 | }, 771 | { 772 | "cell_type": "code", 773 | "execution_count": 22, 774 | "metadata": {}, 775 | "outputs": [], 776 | "source": [ 777 | "# Extract just the values for which our premise is true:\n", 778 | "premise_true = stocks[stocks['ibm_up']]" 779 | ] 780 | }, 781 | { 782 | "cell_type": "code", 783 | "execution_count": 23, 784 | "metadata": {}, 785 | "outputs": [ 786 | { 787 | "data": { 788 | "text/plain": [ 789 | "0.49712858926342074" 790 | ] 791 | }, 792 | "execution_count": 23, 793 | "metadata": {}, 794 | "output_type": "execute_result" 795 | } 796 | ], 797 | "source": [ 798 | "# Get an overall estimate for our conclusion being true as well:\n", 799 | "premise_true['msft_up_tomorrow'].mean()" 800 | ] 801 | }, 802 | { 803 | "cell_type": "markdown", 804 | "metadata": {}, 805 | "source": [ 806 | "Here, our estimate is 49% that if IBM increased today, MSFT will increase tomorrow. Effectively random.\n", 807 | "\n", 808 | "Let's compute the confidence interval for this using the bootstrap method:" 809 | ] 810 | }, 811 | { 812 | "cell_type": "code", 813 | "execution_count": 24, 814 | "metadata": {}, 815 | "outputs": [], 816 | "source": [ 817 | "def compute_msft_follows_ibm_statistic(original_data):\n", 818 | " # Encapsulates code above for \"MSFT increase follows an IBM increase\"\n", 819 | " sample = original_data.sample(replace=True, n=len(original_data))\n", 820 | " return sample['msft_up_tomorrow'].mean()\n" 821 | ] 822 | }, 823 | { 824 | "cell_type": "code", 825 | "execution_count": 25, 826 | "metadata": {}, 827 | "outputs": [ 828 | { 829 | "data": { 830 | "text/plain": [ 831 | "0.4968789013732834" 832 | ] 833 | }, 834 | "execution_count": 25, 835 | "metadata": {}, 836 | "output_type": "execute_result" 837 | } 838 | ], 839 | "source": [ 840 | "compute_msft_follows_ibm_statistic(premise_true)" 841 | ] 842 | }, 843 | { 844 | "cell_type": "code", 845 | "execution_count": 26, 846 | "metadata": {}, 847 | "outputs": [], 848 | "source": [ 849 | "number_experiments = 10000\n", 850 | "\n", 851 | "values = np.array([compute_msft_follows_ibm_statistic(premise_true) for i in range(number_experiments)])\n" 852 | ] 853 | }, 854 | { 855 | "cell_type": "code", 856 | "execution_count": 27, 857 | "metadata": {}, 858 | "outputs": [], 859 | "source": [ 860 | "def compute_confidence_interval(values, ci=0.95):\n", 861 | " \"\"\"Computer confidence interval for the given values\"\"\"\n", 862 | " assert 0 < ci <= 1\n", 863 | " n = len(values)\n", 864 | " lower = int(n * (1-ci)/2)\n", 865 | " upper = int(n * ci / 2)\n", 866 | " assert upper > lower # Can be lower == upper if not enough samples\n", 867 | " sorted_values = np.sort(values)\n", 868 | " return sorted_values[lower], sorted_values[upper]\n" 869 | ] 870 | }, 871 | { 872 | "cell_type": "code", 873 | "execution_count": 29, 874 | "metadata": {}, 875 | "outputs": [ 876 | { 877 | "data": { 878 | "text/plain": [ 879 | "(0.48414481897627965, 0.49637952559300874)" 880 | ] 881 | }, 882 | "execution_count": 29, 883 | "metadata": {}, 884 | "output_type": "execute_result" 885 | } 886 | ], 887 | "source": [ 888 | "compute_confidence_interval(values, ci=0.9)" 889 | ] 890 | }, 891 | { 892 | "cell_type": "markdown", 893 | "metadata": {}, 894 | "source": [ 895 | "While the value is *near* 0.50, which would indicate that there is no value to our assumption, we can see that the confidence bound is actually less than 0.50 at the 0.9 confidence level. \n", 896 | "\n", 897 | "We could misinterpret this and suddenly start trading on the pattern \"if IBM increases, short MSFT\". Our evidence does support this idea, but proper backtesting would be needed. Note though, the importance of the confidence interval in this decision. By the mean alone, the value was so close to 0.50 that most would just write it off as \"roughly a coin flip, so no further research to be done\". A small amount of coding gets us confidence intervals and \"there may be a slight edge here that is exploitable\".\n", 898 | "\n", 899 | "That said, always check the confidence intervals. Remember that a confidence interval of 0.90 roughly equates to \"if we do 10 experiments at a CI of 0.9, one in ten will be wrong\". Here is the same analysis for different ci levels:" 900 | ] 901 | }, 902 | { 903 | "cell_type": "code", 904 | "execution_count": 29, 905 | "metadata": {}, 906 | "outputs": [ 907 | { 908 | "name": "stdout", 909 | "output_type": "stream", 910 | "text": [ 911 | "CI\tFalse positives in...\n", 912 | "0.50000\t1 in 2\n", 913 | "0.75000\t1 in 4\n", 914 | "0.80000\t1 in 5\n", 915 | "0.85000\t1 in 6\n", 916 | "0.90000\t1 in 10\n", 917 | "0.95000\t1 in 19\n", 918 | "0.97500\t1 in 39\n", 919 | "0.99000\t1 in 99\n", 920 | "0.99900\t1 in 999\n", 921 | "0.99990\t1 in 10000\n", 922 | "0.99999\t1 in 100000\n" 923 | ] 924 | } 925 | ], 926 | "source": [ 927 | "print(\"CI\\tFalse positives in...\")\n", 928 | "for ci in [0.5, 0.75, 0.8, 0.85, 0.9, 0.95, 0.975, 0.99, 0.999, 0.9999, 0.99999]:\n", 929 | " number_wrong = int(1/(1-ci))\n", 930 | " print(\"{ci:.5f}\\t1 in {number_wrong}\".format(**locals()))" 931 | ] 932 | }, 933 | { 934 | "cell_type": "markdown", 935 | "metadata": {}, 936 | "source": [ 937 | "Those last few values are colloquially referred to as \"three 9s\", \"four 9s\" and \"five 9s\" and so on, especially in studies of reliability." 938 | ] 939 | }, 940 | { 941 | "cell_type": "markdown", 942 | "metadata": {}, 943 | "source": [ 944 | "#### Exercise\n", 945 | "\n", 946 | "Modify the worked example to test this hypothesis:\n", 947 | "\n", 948 | " If IBM drops by more than 5% on a given day, MSFT will increase the following day.\n", 949 | " \n", 950 | "Provide a single estimate for the probability of this happening, as well as a confidence interval.\n", 951 | " \n", 952 | "#### Extended Exercise\n", 953 | "\n", 954 | "Modify further to test this hypothesis:\n", 955 | "\n", 956 | " If IBM drops by more than 5% over a given week, MSFT will increase the following week." 957 | ] 958 | } 959 | ], 960 | "metadata": { 961 | "kernelspec": { 962 | "display_name": "Python 3", 963 | "language": "python", 964 | "name": "python3" 965 | }, 966 | "language_info": { 967 | "codemirror_mode": { 968 | "name": "ipython", 969 | "version": 3 970 | }, 971 | "file_extension": ".py", 972 | "mimetype": "text/x-python", 973 | "name": "python", 974 | "nbconvert_exporter": "python", 975 | "pygments_lexer": "ipython3", 976 | "version": "3.11.0" 977 | } 978 | }, 979 | "nbformat": 4, 980 | "nbformat_minor": 2 981 | } 982 | -------------------------------------------------------------------------------- /notebooks/bayesian_updating_plot.py: -------------------------------------------------------------------------------- 1 | import scipy.stats as stats 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | 5 | dist = stats.beta 6 | n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 5000] 7 | data = stats.bernoulli.rvs(0.5, size=n_trials[-1]) 8 | x = np.linspace(0, 1, 100) 9 | 10 | # For the already prepared, I'm using Binomial's conj. prior. 11 | for k, N in enumerate(n_trials): 12 | sx = plt.subplot(int(len(n_trials) / 2), 2, k + 1) 13 | plt.xlabel("$p$, probability of heads") if k in [0, len(n_trials) - 1] else None 14 | plt.setp(sx.get_yticklabels(), visible=False) 15 | heads = data[:N].sum() 16 | y = dist.pdf(x, 1 + heads, 1 + N - heads) 17 | plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads)) 18 | plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4) 19 | plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1) 20 | 21 | leg = plt.legend() 22 | leg.get_frame().set_alpha(0.4) 23 | plt.autoscale(tight=True) 24 | 25 | 26 | plt.suptitle("Bayesian updating of posterior probabilities", y=1.02, fontsize=14) 27 | 28 | plt.tight_layout() 29 | -------------------------------------------------------------------------------- /notebooks/custom/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/custom/__init__.py -------------------------------------------------------------------------------- /notebooks/custom/css/custom.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | 3 | color: green; 4 | 5 | } 6 | -------------------------------------------------------------------------------- /notebooks/custom/figures.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import warnings 4 | 5 | 6 | def plot_venn_diagram(): 7 | fig, ax = plt.subplots(subplot_kw=dict(frameon=False, xticks=[], yticks=[])) 8 | ax.add_patch(plt.Circle((0.3, 0.3), 0.3, fc="red", alpha=0.5)) 9 | ax.add_patch(plt.Circle((0.6, 0.3), 0.3, fc="blue", alpha=0.5)) 10 | ax.add_patch(plt.Rectangle((-0.1, -0.1), 1.1, 0.8, fc="none", ec="black")) 11 | ax.text(0.2, 0.3, "$x$", size=30, ha="center", va="center") 12 | ax.text(0.7, 0.3, "$y$", size=30, ha="center", va="center") 13 | ax.text(0.0, 0.6, "$I$", size=30) 14 | ax.axis("equal") 15 | 16 | 17 | def plot_example_decision_tree(): 18 | fig = plt.figure(figsize=(10, 4)) 19 | ax = fig.add_axes([0, 0, 0.8, 1], frameon=False, xticks=[], yticks=[]) 20 | ax.set_title("Example Decision Tree: Animal Classification", size=24) 21 | 22 | def text(ax, x, y, t, size=20, **kwargs): 23 | ax.text( 24 | x, 25 | y, 26 | t, 27 | ha="center", 28 | va="center", 29 | size=size, 30 | bbox=dict(boxstyle="round", ec="k", fc="w"), 31 | **kwargs 32 | ) 33 | 34 | text(ax, 0.5, 0.9, "How big is\nthe animal?", 20) 35 | text(ax, 0.3, 0.6, "Does the animal\nhave horns?", 18) 36 | text(ax, 0.7, 0.6, "Does the animal\nhave two legs?", 18) 37 | text(ax, 0.12, 0.3, "Are the horns\nlonger than 10cm?", 14) 38 | text(ax, 0.38, 0.3, "Is the animal\nwearing a collar?", 14) 39 | text(ax, 0.62, 0.3, "Does the animal\nhave wings?", 14) 40 | text(ax, 0.88, 0.3, "Does the animal\nhave a tail?", 14) 41 | 42 | text(ax, 0.4, 0.75, "> 1m", 12, alpha=0.4) 43 | text(ax, 0.6, 0.75, "< 1m", 12, alpha=0.4) 44 | 45 | text(ax, 0.21, 0.45, "yes", 12, alpha=0.4) 46 | text(ax, 0.34, 0.45, "no", 12, alpha=0.4) 47 | 48 | text(ax, 0.66, 0.45, "yes", 12, alpha=0.4) 49 | text(ax, 0.79, 0.45, "no", 12, alpha=0.4) 50 | 51 | ax.plot([0.3, 0.5, 0.7], [0.6, 0.9, 0.6], "-k") 52 | ax.plot([0.12, 0.3, 0.38], [0.3, 0.6, 0.3], "-k") 53 | ax.plot([0.62, 0.7, 0.88], [0.3, 0.6, 0.3], "-k") 54 | ax.plot([0.0, 0.12, 0.20], [0.0, 0.3, 0.0], "--k") 55 | ax.plot([0.28, 0.38, 0.48], [0.0, 0.3, 0.0], "--k") 56 | ax.plot([0.52, 0.62, 0.72], [0.0, 0.3, 0.0], "--k") 57 | ax.plot([0.8, 0.88, 1.0], [0.0, 0.3, 0.0], "--k") 58 | ax.axis([0, 1, 0, 1]) 59 | 60 | 61 | def visualize_tree(estimator, X, y, boundaries=True, xlim=None, ylim=None): 62 | estimator.fit(X, y) 63 | 64 | if xlim is None: 65 | xlim = (X[:, 0].min() - 0.1, X[:, 0].max() + 0.1) 66 | if ylim is None: 67 | ylim = (X[:, 1].min() - 0.1, X[:, 1].max() + 0.1) 68 | 69 | x_min, x_max = xlim 70 | y_min, y_max = ylim 71 | xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100), np.linspace(y_min, y_max, 100)) 72 | Z = estimator.predict(np.c_[xx.ravel(), yy.ravel()]) 73 | 74 | # Put the result into a color plot 75 | Z = Z.reshape(xx.shape) 76 | plt.figure() 77 | plt.pcolormesh(xx, yy, Z, alpha=0.2, cmap="rainbow") 78 | plt.clim(y.min(), y.max()) 79 | 80 | # Plot also the training points 81 | plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap="rainbow") 82 | plt.axis("off") 83 | 84 | plt.xlim(x_min, x_max) 85 | plt.ylim(y_min, y_max) 86 | plt.clim(y.min(), y.max()) 87 | 88 | # Plot the decision boundaries 89 | def plot_boundaries(i, xlim, ylim): 90 | if i < 0: 91 | return 92 | 93 | tree = estimator.tree_ 94 | 95 | if tree.feature[i] == 0: 96 | plt.plot([tree.threshold[i], tree.threshold[i]], ylim, "-k") 97 | plot_boundaries(tree.children_left[i], [xlim[0], tree.threshold[i]], ylim) 98 | plot_boundaries(tree.children_right[i], [tree.threshold[i], xlim[1]], ylim) 99 | 100 | elif tree.feature[i] == 1: 101 | plt.plot(xlim, [tree.threshold[i], tree.threshold[i]], "-k") 102 | plot_boundaries(tree.children_left[i], xlim, [ylim[0], tree.threshold[i]]) 103 | plot_boundaries(tree.children_right[i], xlim, [tree.threshold[i], ylim[1]]) 104 | 105 | if boundaries: 106 | plot_boundaries(0, plt.xlim(), plt.ylim()) 107 | 108 | 109 | def plot_tree_interactive(X, y): 110 | from sklearn.tree import DecisionTreeClassifier 111 | 112 | def interactive_tree(depth=1): 113 | clf = DecisionTreeClassifier(max_depth=depth, random_state=0) 114 | visualize_tree(clf, X, y) 115 | 116 | from IPython.html.widgets import interact 117 | 118 | return interact(interactive_tree, depth=[1, 5]) 119 | 120 | 121 | def plot_kmeans_interactive(min_clusters=1, max_clusters=6): 122 | from ipywidgets import interact 123 | from sklearn.metrics.pairwise import euclidean_distances 124 | from sklearn.datasets.samples_generator import make_blobs 125 | 126 | with warnings.catch_warnings(): 127 | warnings.filterwarnings("ignore") 128 | 129 | X, y = make_blobs(n_samples=300, centers=4, random_state=0, cluster_std=0.60) 130 | 131 | def _kmeans_step(frame=0, n_clusters=4): 132 | rng = np.random.RandomState(2) 133 | labels = np.zeros(X.shape[0]) 134 | centers = rng.randn(n_clusters, 2) 135 | 136 | nsteps = frame // 3 137 | 138 | for i in range(nsteps + 1): 139 | old_centers = centers 140 | if i < nsteps or frame % 3 > 0: 141 | dist = euclidean_distances(X, centers) 142 | labels = dist.argmin(1) 143 | 144 | if i < nsteps or frame % 3 > 1: 145 | centers = np.array( 146 | [X[labels == j].mean(0) for j in range(n_clusters)] 147 | ) 148 | nans = np.isnan(centers) 149 | centers[nans] = old_centers[nans] 150 | 151 | # plot the data and cluster centers 152 | plt.scatter( 153 | X[:, 0], 154 | X[:, 1], 155 | c=labels, 156 | s=50, 157 | cmap="rainbow", 158 | vmin=0, 159 | vmax=n_clusters - 1, 160 | ) 161 | plt.scatter( 162 | old_centers[:, 0], 163 | old_centers[:, 1], 164 | marker="o", 165 | c=np.arange(n_clusters), 166 | s=200, 167 | cmap="rainbow", 168 | ) 169 | plt.scatter( 170 | old_centers[:, 0], old_centers[:, 1], marker="o", c="black", s=50 171 | ) 172 | 173 | # plot new centers if third frame 174 | if frame % 3 == 2: 175 | for i in range(n_clusters): 176 | plt.annotate( 177 | "", 178 | centers[i], 179 | old_centers[i], 180 | arrowprops=dict(arrowstyle="->", linewidth=1), 181 | ) 182 | plt.scatter( 183 | centers[:, 0], 184 | centers[:, 1], 185 | marker="o", 186 | c=np.arange(n_clusters), 187 | s=200, 188 | cmap="rainbow", 189 | ) 190 | plt.scatter(centers[:, 0], centers[:, 1], marker="o", c="black", s=50) 191 | 192 | plt.xlim(-4, 4) 193 | plt.ylim(-2, 10) 194 | 195 | if frame % 3 == 1: 196 | plt.text( 197 | 3.8, 198 | 9.5, 199 | "1. Reassign points to nearest centroid", 200 | ha="right", 201 | va="top", 202 | size=14, 203 | ) 204 | elif frame % 3 == 2: 205 | plt.text( 206 | 3.8, 207 | 9.5, 208 | "2. Update centroids to cluster means", 209 | ha="right", 210 | va="top", 211 | size=14, 212 | ) 213 | 214 | return interact( 215 | _kmeans_step, frame=[0, 50], n_clusters=[min_clusters, max_clusters] 216 | ) 217 | 218 | 219 | def plot_image_components( 220 | x, 221 | coefficients=None, 222 | mean=0, 223 | components=None, 224 | imshape=(8, 8), 225 | n_components=6, 226 | fontsize=12, 227 | cmap="Greys", 228 | ): 229 | if coefficients is None: 230 | coefficients = x 231 | 232 | if components is None: 233 | components = np.eye(len(coefficients), len(x)) 234 | 235 | mean = np.zeros_like(x) + mean 236 | 237 | fig = plt.figure(figsize=(1.2 * (5 + n_components), 1.2 * 2)) 238 | g = plt.GridSpec(2, 5 + n_components, hspace=0.3) 239 | 240 | def show(i, j, x, title=None): 241 | ax = fig.add_subplot(g[i, j], xticks=[], yticks=[]) 242 | ax.imshow(x.reshape(imshape), interpolation="nearest", cmap=cmap) 243 | if title: 244 | ax.set_title(title, fontsize=fontsize) 245 | 246 | show(slice(2), slice(2), x, "True") 247 | 248 | approx = mean.copy() 249 | show(0, 2, np.zeros_like(x) + mean, r"$\mu$") 250 | show(1, 2, approx, r"$1 \cdot \mu$") 251 | 252 | for i in range(0, n_components): 253 | approx = approx + coefficients[i] * components[i] 254 | show(0, i + 3, components[i], r"$c_{0}$".format(i + 1)) 255 | show(1, i + 3, approx, r"${0:.2f} \cdot c_{1}$".format(coefficients[i], i + 1)) 256 | plt.gca().text( 257 | 0, 258 | 1.05, 259 | "$+$", 260 | ha="right", 261 | va="bottom", 262 | transform=plt.gca().transAxes, 263 | fontsize=fontsize, 264 | ) 265 | 266 | show(slice(2), slice(-2, None), approx, "Approx") 267 | 268 | 269 | def plot_pca_interactive(data, n_components=6): 270 | from sklearn.decomposition import PCA 271 | from ipywidgets import interact 272 | 273 | pca = PCA(n_components=n_components) 274 | Xproj = pca.fit_transform(data) 275 | 276 | def show_decomp(i=0): 277 | plot_image_components(data[i], Xproj[i], pca.mean_, pca.components_) 278 | 279 | interact(show_decomp, i=(0, data.shape[0] - 1)) 280 | -------------------------------------------------------------------------------- /notebooks/data/AAPL.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/data/AAPL.h5 -------------------------------------------------------------------------------- /notebooks/data/AAPL.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/data/AAPL.pkl -------------------------------------------------------------------------------- /notebooks/data/HousePricesVsInterestRates.hdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/data/HousePricesVsInterestRates.hdf -------------------------------------------------------------------------------- /notebooks/data/aus_state_populations.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/data/aus_state_populations.h5 -------------------------------------------------------------------------------- /notebooks/data/sp500.csv: -------------------------------------------------------------------------------- 1 | Symbol 2 | MMM 3 | ABT 4 | ABBV 5 | ABMD 6 | ACN 7 | ATVI 8 | ADBE 9 | AMD 10 | AAP 11 | AES 12 | AMG 13 | AFL 14 | A 15 | APD 16 | AKAM 17 | ALK 18 | ALB 19 | ARE 20 | ALXN 21 | ALGN 22 | ALLE 23 | AGN 24 | ADS 25 | LNT 26 | ALL 27 | GOOGL 28 | GOOG 29 | MO 30 | AMZN 31 | AEE 32 | AAL 33 | AEP 34 | AXP 35 | AIG 36 | AMT 37 | AWK 38 | AMP 39 | ABC 40 | AME 41 | AMGN 42 | APH 43 | APC 44 | ADI 45 | ANSS 46 | ANTM 47 | AON 48 | AOS 49 | APA 50 | AIV 51 | AAPL 52 | AMAT 53 | APTV 54 | ADM 55 | ARNC 56 | ANET 57 | AJG 58 | AIZ 59 | ATO 60 | T 61 | ADSK 62 | ADP 63 | AZO 64 | AVB 65 | AVY 66 | BHGE 67 | BLL 68 | BAC 69 | BK 70 | BAX 71 | BBT 72 | BDX 73 | BRK.B 74 | BBY 75 | BIIB 76 | BLK 77 | HRB 78 | BA 79 | BKNG 80 | BWA 81 | BXP 82 | BSX 83 | BMY 84 | AVGO 85 | BR 86 | BF.B 87 | CHRW 88 | COG 89 | CDNS 90 | CPB 91 | COF 92 | CPRI 93 | CAH 94 | KMX 95 | CCL 96 | CAT 97 | CBOE 98 | CBRE 99 | CBS 100 | CE 101 | CELG 102 | CNC 103 | CNP 104 | CTL 105 | CERN 106 | CF 107 | SCHW 108 | CHTR 109 | CVX 110 | CMG 111 | CB 112 | CHD 113 | CI 114 | XEC 115 | CINF 116 | CTAS 117 | CSCO 118 | C 119 | CFG 120 | CTXS 121 | CLX 122 | CME 123 | CMS 124 | KO 125 | CTSH 126 | CL 127 | CMCSA 128 | CMA 129 | CAG 130 | CXO 131 | COP 132 | ED 133 | STZ 134 | COO 135 | CPRT 136 | GLW 137 | COST 138 | COTY 139 | CCI 140 | CSX 141 | CMI 142 | CVS 143 | DHI 144 | DHR 145 | DRI 146 | DVA 147 | DE 148 | DAL 149 | XRAY 150 | DVN 151 | FANG 152 | DLR 153 | DFS 154 | DISCA 155 | DISCK 156 | DISH 157 | DG 158 | DLTR 159 | D 160 | DOV 161 | DOW 162 | DWDP 163 | DTE 164 | DRE 165 | DUK 166 | DXC 167 | ETFC 168 | EMN 169 | ETN 170 | EBAY 171 | ECL 172 | EIX 173 | EW 174 | EA 175 | EMR 176 | ETR 177 | EOG 178 | EFX 179 | EQIX 180 | EQR 181 | ESS 182 | EL 183 | EVRG 184 | ES 185 | RE 186 | EXC 187 | EXPE 188 | EXPD 189 | EXR 190 | XOM 191 | FFIV 192 | FB 193 | FAST 194 | FRT 195 | FDX 196 | FIS 197 | FITB 198 | FE 199 | FRC 200 | FISV 201 | FLT 202 | FLIR 203 | FLS 204 | FLR 205 | FMC 206 | FL 207 | F 208 | FTNT 209 | FTV 210 | FBHS 211 | BEN 212 | FCX 213 | GPS 214 | GRMN 215 | IT 216 | GD 217 | GE 218 | GIS 219 | GM 220 | GPC 221 | GILD 222 | GPN 223 | GS 224 | GWW 225 | HAL 226 | HBI 227 | HOG 228 | HRS 229 | HIG 230 | HAS 231 | HCA 232 | HCP 233 | HP 234 | HSIC 235 | HSY 236 | HES 237 | HPE 238 | HLT 239 | HFC 240 | HOLX 241 | HD 242 | HON 243 | HRL 244 | HST 245 | HPQ 246 | HUM 247 | HBAN 248 | HII 249 | IDXX 250 | INFO 251 | ITW 252 | ILMN 253 | IR 254 | INTC 255 | ICE 256 | IBM 257 | INCY 258 | IP 259 | IPG 260 | IFF 261 | INTU 262 | ISRG 263 | IVZ 264 | IPGP 265 | IQV 266 | IRM 267 | JKHY 268 | JEC 269 | JBHT 270 | JEF 271 | SJM 272 | JNJ 273 | JCI 274 | JPM 275 | JNPR 276 | KSU 277 | K 278 | KEY 279 | KEYS 280 | KMB 281 | KIM 282 | KMI 283 | KLAC 284 | KSS 285 | KHC 286 | KR 287 | LB 288 | LLL 289 | LH 290 | LRCX 291 | LW 292 | LEG 293 | LEN 294 | LLY 295 | LNC 296 | LIN 297 | LKQ 298 | LMT 299 | L 300 | LOW 301 | LYB 302 | MTB 303 | MAC 304 | M 305 | MRO 306 | MPC 307 | MAR 308 | MMC 309 | MLM 310 | MAS 311 | MA 312 | MAT 313 | MKC 314 | MXIM 315 | MCD 316 | MCK 317 | MDT 318 | MRK 319 | MET 320 | MTD 321 | MGM 322 | MCHP 323 | MU 324 | MSFT 325 | MAA 326 | MHK 327 | TAP 328 | MDLZ 329 | MNST 330 | MCO 331 | MS 332 | MOS 333 | MSI 334 | MSCI 335 | MYL 336 | NDAQ 337 | NOV 338 | NKTR 339 | NTAP 340 | NFLX 341 | NWL 342 | NEM 343 | NWSA 344 | NWS 345 | NEE 346 | NLSN 347 | NKE 348 | NI 349 | NBL 350 | JWN 351 | NSC 352 | NTRS 353 | NOC 354 | NCLH 355 | NRG 356 | NUE 357 | NVDA 358 | ORLY 359 | OXY 360 | OMC 361 | OKE 362 | ORCL 363 | PCAR 364 | PKG 365 | PH 366 | PAYX 367 | PYPL 368 | PNR 369 | PBCT 370 | PEP 371 | PKI 372 | PRGO 373 | PFE 374 | PM 375 | PSX 376 | PNW 377 | PXD 378 | PNC 379 | RL 380 | PPG 381 | PPL 382 | PFG 383 | PG 384 | PGR 385 | PLD 386 | PRU 387 | PEG 388 | PSA 389 | PHM 390 | PVH 391 | QRVO 392 | PWR 393 | QCOM 394 | DGX 395 | RJF 396 | RTN 397 | O 398 | RHT 399 | REG 400 | REGN 401 | RF 402 | RSG 403 | RMD 404 | RHI 405 | ROK 406 | ROL 407 | ROP 408 | ROST 409 | RCL 410 | CRM 411 | SBAC 412 | SLB 413 | STX 414 | SEE 415 | SRE 416 | SHW 417 | SPG 418 | SWKS 419 | SLG 420 | SNA 421 | SO 422 | LUV 423 | SPGI 424 | SWK 425 | SBUX 426 | STT 427 | SYK 428 | STI 429 | SIVB 430 | SYMC 431 | SYF 432 | SNPS 433 | SYY 434 | TROW 435 | TTWO 436 | TPR 437 | TGT 438 | TEL 439 | FTI 440 | TFX 441 | TXN 442 | TXT 443 | TMO 444 | TIF 445 | TWTR 446 | TJX 447 | TMK 448 | TSS 449 | TSCO 450 | TDG 451 | TRV 452 | TRIP 453 | FOXA 454 | FOX 455 | TSN 456 | UDR 457 | ULTA 458 | USB 459 | UAA 460 | UA 461 | UNP 462 | UAL 463 | UNH 464 | UPS 465 | URI 466 | UTX 467 | UHS 468 | UNM 469 | VFC 470 | VLO 471 | VAR 472 | VTR 473 | VRSN 474 | VRSK 475 | VZ 476 | VRTX 477 | VIAB 478 | V 479 | VNO 480 | VMC 481 | WAB 482 | WMT 483 | WBA 484 | DIS 485 | WM 486 | WAT 487 | WEC 488 | WCG 489 | WFC 490 | WELL 491 | WDC 492 | WU 493 | WRK 494 | WY 495 | WHR 496 | WMB 497 | WLTW 498 | WYNN 499 | XEL 500 | XRX 501 | XLNX 502 | XYL 503 | YUM 504 | ZBH 505 | ZION 506 | ZTS 507 | -------------------------------------------------------------------------------- /notebooks/img/Wong_Baker_Scale.sr (1).JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/Wong_Baker_Scale.sr (1).JPG -------------------------------------------------------------------------------- /notebooks/img/Wong_Baker_Scale.sr.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/Wong_Baker_Scale.sr.JPG -------------------------------------------------------------------------------- /notebooks/img/confidence_interval_highlight.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/confidence_interval_highlight.png -------------------------------------------------------------------------------- /notebooks/img/facial_recognition.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/facial_recognition.png -------------------------------------------------------------------------------- /notebooks/img/lagged_correlation_plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/lagged_correlation_plot.png -------------------------------------------------------------------------------- /notebooks/img/python_charmers_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/python_charmers_logo.png -------------------------------------------------------------------------------- /notebooks/img/snapshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/snapshot.png -------------------------------------------------------------------------------- /notebooks/img/spurious.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/spurious.png -------------------------------------------------------------------------------- /notebooks/img/tibra_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PythonCharmers/QuantFinance/ef3e103f511ae9b17c77acbc8d9a02681d707b2b/notebooks/img/tibra_logo.png -------------------------------------------------------------------------------- /notebooks/my_secrets_template.py: -------------------------------------------------------------------------------- 1 | 2 | QUANDL_API_KEY = "INSERT YOUR API KEY HERE" -------------------------------------------------------------------------------- /notebooks/plot_priors.ipy: -------------------------------------------------------------------------------- 1 | f, ax = plt.subplots(len(params), len(params), sharex=True, sharey=True, figsize=(12, 12)) 2 | for i in range(4): 3 | for j in range(4): 4 | alpha = params[i] 5 | beta = params[j] 6 | y = prior(x, alpha, beta) 7 | ax[i,j].plot(x, y) 8 | ax[i,j].plot(0, 0, label="$\\alpha$ = {:3.2f}\n$\\beta$ = {:3.2f}".format(alpha, beta), alpha=0) 9 | ax[i,j].legend(fontsize=12) 10 | ax[3,0].set_xlabel(r'$\theta$', fontsize=14) 11 | ax[0,0].set_ylabel(r'$p(\theta)$', fontsize=14); -------------------------------------------------------------------------------- /notebooks/python2_test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | source activate quant-2.7 3 | for filename in *.ipynb; do 4 | echo $filename 5 | jupyter nbconvert --ExecutePreprocessor.kernel_name=python2 --execute --ExecutePreprocessor.timeout=600 "$filename" --output-dir="output" || echo "$filename" >> errors.txt 6 | done 7 | -------------------------------------------------------------------------------- /notebooks/setup.ipy: -------------------------------------------------------------------------------- 1 | 2 | import pandas as pd 3 | import altair as alt 4 | 5 | if not alt.data_transformers.active == 'json': # Check json isn't already active 6 | import os 7 | # Make a temp folder to put these json files in - Altair creates a lot of them! 8 | dataset_temp_name = 'altair-temp-data/' 9 | if not os.path.exists(dataset_temp_name): 10 | # if the folder doesn't exist, create it 11 | os.mkdir(dataset_temp_name) 12 | # Tell Altair to temporary save datasets it needs to that folder 13 | alt.data_transformers.enable('json', prefix=dataset_temp_name) 14 | alt.renderers.enable('default') 15 | 16 | from scipy import stats 17 | 18 | import random 19 | import numpy as np 20 | 21 | import pandas as pd 22 | 23 | %matplotlib inline 24 | from matplotlib import pyplot as plt 25 | -------------------------------------------------------------------------------- /notebooks/show_posteriors_coins.ipy: -------------------------------------------------------------------------------- 1 | """ 2 | Code fragment for plotting the posterior 3 | for the coin-tossing example in module 1.5.2 4 | """ 5 | 6 | import scipy.stats 7 | 8 | dist = scipy.stats.beta 9 | 10 | plt.figure(figsize=(12, 12)) 11 | for idx, N in enumerate(trials): 12 | if idx == 0: 13 | plt.subplot(4,3, 2) 14 | else: 15 | plt.subplot(4,3, idx+3) 16 | y = data[idx] 17 | for (a_prior, b_prior), c in zip(beta_params, ('b', 'r', 'g')): 18 | p_theta_given_y = dist.pdf(x, a_prior + y, b_prior + N - y) 19 | plt.plot(x, p_theta_given_y, c) 20 | plt.fill_between(x, 0, p_theta_given_y, color=c, alpha=0.3) 21 | 22 | # plt.axvline(theta_real, ymax=0.3, color='k') 23 | plt.plot(0, 0, label="{:d} experiments\n{:d} heads".format(N, y), alpha=0) 24 | plt.xlim(0,1) 25 | plt.ylim(0,12) 26 | plt.xlabel(r'$\theta$') 27 | plt.legend() 28 | plt.gca().axes.get_yaxis().set_visible(False) 29 | plt.tight_layout() 30 | -------------------------------------------------------------------------------- /notebooks/solutions/adfuller.py: -------------------------------------------------------------------------------- 1 | 2 | # Question 1 3 | euro_result = adfuller(euro_fit.fittedvalues) 4 | print('ADF Statistic: {:.2f}'.format(euro_result[0])) 5 | print('p-value: {:.2f}'.format(euro_result[1])) 6 | 7 | usd_result = adfuller(usd_fit.fittedvalues) 8 | print('ADF Statistic: {:.2f}'.format(usd_result[0])) 9 | print('p-value: {:.2f}'.format(usd_result[1])) 10 | 11 | 12 | # Question 2 13 | euro_diff = euros.diff() 14 | result = adfuller(euro_diff[~np.isnan(euro_diff)]) 15 | 16 | usd_diff = usd.diff() 17 | result = adfuller(usd_diff[~np.isnan(usd_diff)]) 18 | 19 | # Question 3 20 | 21 | euro_log = np.log(euros) 22 | usd_log = np.log(usd) 23 | -------------------------------------------------------------------------------- /notebooks/solutions/adjusted_increases.py: -------------------------------------------------------------------------------- 1 | increases = prices.diff() 2 | increase_z_score = (increases - increases.mean())/increases.std() 3 | increase_z_score.dropna(inplace=True) 4 | increase_z_score.head() 5 | 6 | print("This analysis shows that AAPL has a 'wider tail' in general.") 7 | print("However, MSFT has much more wild swings that appear rarely.") 8 | alt.Chart(increase_z_score.melt(value_name="z_score_adj_close")).mark_bar(opacity=0.4).encode( 9 | x=alt.X("z_score_adj_close", bin=alt.Bin(maxbins=30)), 10 | y=alt.Y('count()', stack=None), 11 | # column='ticker', 12 | color='ticker', 13 | ) -------------------------------------------------------------------------------- /notebooks/solutions/an_array.py: -------------------------------------------------------------------------------- 1 | 2 | # Question 1 3 | import numpy as np 4 | 5 | A = np.array([[10, 20, 30], [40, 50, 60]]) 6 | print(A) 7 | 8 | # Question 2: 9 | # It's a vector! -------------------------------------------------------------------------------- /notebooks/solutions/arch_models.py: -------------------------------------------------------------------------------- 1 | 2 | y = np.zeros(1000) 3 | np.random.seed(42) 4 | 5 | y[0] = np.random.normal() 6 | for i in range(1, len(y)): 7 | y[i] = np.random.normal() * np.sqrt(5 + 0.5 * y[i-1]**2) + np.sqrt(5 + 0.2 * y[i-3]**2) 8 | 9 | #Try with default, GARCH(1,1) 10 | model = arch_model(y) 11 | results.summary() 12 | 13 | #Retry with GARCH(2,2) 14 | model = arch_model(y,vol="GARCH", p=2, q=2) 15 | result = mod.fit() 16 | result.summary() 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /notebooks/solutions/arima_cryptocurrrency.py: -------------------------------------------------------------------------------- 1 | # Use KPSS to test for stationarity. 2 | from statsmodels.tsa.stattools import kpss 3 | 4 | kpss_stat, p_value, lags, crit = kpss(xrp) 5 | print("XRP p_value:", p_value) 6 | 7 | kpss_stat, p_value, lags, crit = kpss(eth) 8 | print("ETH p_value:", p_value) 9 | 10 | 11 | from statsmodels.tsa.arima_model import ARIMA as arima 12 | 13 | xrp_model_arima = arima(xrp, order=(4,1, 2)) #Remember if we use d=0 we're back to using the ARMA model! 14 | eth_model_arima = sms.tsa.ARMA(eth, order=(3, 1, 2)) 15 | 16 | xrp_results_arima = xrp_model_arima.fit() 17 | eth_results_arima = eth_model_arima.fit() 18 | 19 | xrp_results_arima.summary() 20 | eth_results_arima.summary() 21 | -------------------------------------------------------------------------------- /notebooks/solutions/arima_seasonal.py: -------------------------------------------------------------------------------- 1 | #1. In the above example we have specified a seasonal ARMIMA model of 0, 1, 0 (P,Q,Q) with a period of 4, since 2 | # we are using quarterly data. 3 | 4 | #2. 5 | 6 | wheat_price = quandl.get("ODA/PWHEAMT_USD", collapse="monthly") 7 | seasonal_model_wheat = SARIMAX(changes, order=(1, 1, 1), seasonal_order=(0, 1, 0, 12)) 8 | result_wheat = seasonal_model_wheat.fit() 9 | result_wheat.summary() 10 | -------------------------------------------------------------------------------- /notebooks/solutions/arima_sse.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | start_date = datetime(2015, 1, 1) 4 | end_date = datetime(2029, 10, 1) 5 | 6 | train = changes.loc[:start_date] 7 | test = changes.loc[start_date:end_date] 8 | 9 | model = ARIMA(train, order=(1, 0, 2)) 10 | results = model.fit() 11 | results.summary() 12 | 13 | y_pred = results.predict(start_date, end_date) 14 | y_pred.name = "Predictions" 15 | y_pred.plot(title="Predictions") 16 | test.plot(title="Actual") 17 | 18 | test_s = test["Value"] #Convert to a series to match our predicted data 19 | sse = np.sum((y_pred - test_s)**2) 20 | 21 | sse 22 | -------------------------------------------------------------------------------- /notebooks/solutions/arima_types.py: -------------------------------------------------------------------------------- 1 | 2 | # ARIMA(1, 0, 0) is AR(1) 3 | # ARIMA(0, 0, 0) is just the mean (with an error term) 4 | # ARIMA(0, 1, 0) is I(1), an autoregressive model 5 | -------------------------------------------------------------------------------- /notebooks/solutions/arma_cryptocurrency.py: -------------------------------------------------------------------------------- 1 | %run setup.ipy 2 | 3 | import quandl 4 | import my_secrets 5 | quandl.ApiConfig.api_key = my_secrets.QUANDL_API_KEY 6 | 7 | xrp = quandl.get("BITFINEX/XRPUSD")["Last"] 8 | eth = quandl.get("BITFINEX/ETHUSD")["Last"] 9 | 10 | # Should we replace the index? Some dates are missing so we can't set a frquency to 'D' without actually 11 | # replacing the entire index? This generates a lot of warnings... 12 | 13 | 14 | # When we've played with values a bit, we can then use the below. 15 | from statsmodels.tsa import stattools 16 | xrp_stats = stattools.arma_order_select_ic(xrp) 17 | eth_stats = stattools.arma_order_select_ic(eth) 18 | print("XRP: ", xrp_stats) 19 | print("ETH:", eth_stats) 20 | 21 | from statsmodels import api as sms 22 | xrp_model = sms.tsa.ARMA(xrp, order=(4, 2)) 23 | eth_model = sms.tsa.ARMA(eth, order=(3, 2)) 24 | 25 | xrp_results = xrp_model.fit() 26 | eth_results = eth_model.fit() 27 | 28 | xrp_results.summary() 29 | eth_results.summary() 30 | -------------------------------------------------------------------------------- /notebooks/solutions/bayesian_updating_2.py: -------------------------------------------------------------------------------- 1 | # Both exercises solved here, see commetns for question numbers 2 | import scipy.stats as stats 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | dist = stats.beta 7 | n_trials = [0, 1, 2, 3, 4, 5, 15, 50, 500, 5000] # Exercise 1 - added 5000 (removed 8 to make plots line up) 8 | data = stats.bernoulli.rvs(0.8, size=n_trials[-1]) # Exercise 2 - biased coin 9 | x = np.linspace(0, 1, 100) 10 | 11 | # For the already prepared, I'm using Binomial's conj. prior. 12 | for k, N in enumerate(n_trials): 13 | sx = plt.subplot(len(n_trials)/2, 2, k+1) 14 | plt.xlabel("$p$, probability of heads") \ 15 | if k in [0, len(n_trials)-1] else None 16 | plt.setp(sx.get_yticklabels(), visible=False) 17 | heads = data[:N].sum() 18 | y = dist.pdf(x, 1 + heads, 1 + N - heads) 19 | plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads)) 20 | plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4) 21 | plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1) 22 | 23 | leg = plt.legend() 24 | leg.get_frame().set_alpha(0.4) 25 | plt.autoscale(tight=True) 26 | 27 | 28 | plt.suptitle("Bayesian updating of posterior probabilities", 29 | y=1.02, 30 | fontsize=14) 31 | 32 | plt.tight_layout() 33 | -------------------------------------------------------------------------------- /notebooks/solutions/best_coin.py: -------------------------------------------------------------------------------- 1 | beta_params = ((2, 2), (1, 1), (1, 0.5)) 2 | -------------------------------------------------------------------------------- /notebooks/solutions/bic_results.py: -------------------------------------------------------------------------------- 1 | 2 | # 1. bic = Bayesian Information Criterion 3 | 4 | # 2. See stattools.arma_order_select_ic? for information on other options. The main one is aic 5 | 6 | # 3. The rows are p values, columns are q values. 7 | 8 | # 4. the p values 9 | 10 | # 5. Choose (3, 2) 11 | 12 | # 6. statistics['bic_min_order'] 13 | -------------------------------------------------------------------------------- /notebooks/solutions/capm.py: -------------------------------------------------------------------------------- 1 | import quandl 2 | 3 | import my_secrets 4 | quandl.ApiConfig.api_key = my_secrets.QUANDL_API_KEY 5 | 6 | sp500 = quandl.get("CHRIS/CME_SP1") 7 | 8 | sp500_sample = sp500.loc["2016":"2018"].dropna() 9 | 10 | market = sp500_sample['Last'].pct_change().dropna() * 100 11 | 12 | cola = quandl.get("WIKI/KO") 13 | 14 | cola_sample = cola['2016':"2018"] 15 | 16 | coca = cola_sample['Close'].pct_change().dropna() * 100 17 | 18 | market_variance = market["2016":"2018"].var() 19 | print(f"Market Variance: {market_variance}") 20 | 21 | stock_cov = market.corr(coca) 22 | 23 | print(f"Stock Covariance: {stock_cov}") 24 | 25 | beta = stock_cov / market_variance 26 | 27 | print(f"Beta: {beta}") 28 | 29 | e = ending_balance = sp500_sample.iloc[-1]["Last"] 30 | s = starting_balance = sp500_sample.iloc[0]["Last"] 31 | n = number_years = 3 # 2016, 2017, 2018 32 | return_on_market = (e / s) ** (1 / n) - 1 33 | 34 | print(f"Return on Market: {return_on_market}") 35 | 36 | capm = .025 + beta * (return_on_market - .025) 37 | print(f"CAPM: {capm}") 38 | -------------------------------------------------------------------------------- /notebooks/solutions/cdf_relationships.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Exercise 1 4 | x_values_1 = np.linspace(-5, 5, 1000) 5 | distributions_1 = [stats.norm(x, 1) for x in x_values_1] 6 | y_1 = np.array([distribution.cdf(1) - distribution.cdf(0) 7 | for distribution in distributions_1]) 8 | plt.plot(x_values_1, y_1) 9 | 10 | # Exercise 2 11 | x_values_2 = np.linspace(0.1, 20, 1000) 12 | distributions_2 = [stats.norm(0, x) for x in x_values_2] 13 | y_2 = np.array([distribution.cdf(1) - distribution.cdf(0) 14 | for distribution in distributions_2]) 15 | plt.plot(x_values_2, y_2) 16 | print("This function is *decreasing*, as when the standard deviation is higher, " 17 | "the normal distribution 'spreads out'.") 18 | -------------------------------------------------------------------------------- /notebooks/solutions/confidence_intervals.py: -------------------------------------------------------------------------------- 1 | # 1 & 2 2 | d = data.reset_index().dropna() 3 | d["std"] = np.std(d["InterestRate"]) # Add a column for std 4 | 5 | import altair as alt 6 | 7 | # the base chart 8 | base = alt.Chart(d).transform_calculate( 9 | ymin="datum.InterestRate-datum.std", 10 | ymax="datum.InterestRate+datum.std" 11 | ) 12 | # Data Line 13 | line = base.mark_line().encode(x="Date", y="InterestRate") 14 | # Error Bars 15 | bar = base.mark_errorbar().encode(x="Date", y="ymin:Q", y2="ymax:Q") 16 | line + bar 17 | 18 | 19 | # 3 20 | from math import sqrt 21 | pool = data["InterestRate"].dropna() 22 | 23 | sample_size = int(len(pool)/5) 24 | iters = range(1000) 25 | means = [] 26 | 27 | for i in iters: 28 | sample = np.random.choice(pool, sample_size) 29 | means.append(np.mean(sample)) 30 | 31 | mu = np.mean(means) 32 | std = np.std(means) 33 | stats.norm.interval(0.95, loc=mu, scale=std) 34 | 35 | # 4 36 | pool = data["InterestRate"].dropna() 37 | 38 | sample_size = int(len(pool)/5) 39 | iters = range(1000) 40 | means = [] 41 | 42 | for i in iters: 43 | sample = np.random.choice(pool, sample_size) 44 | means.append(np.mean(sample)) 45 | 46 | idx_lower = int(len(means)*.025) 47 | idx_upper = int(len(means)*.975) 48 | sorted_means = np.sort(means) 49 | lower = sorted_means[idx_lower] 50 | upper = sorted_means[idx_upper] 51 | lower, upper 52 | -------------------------------------------------------------------------------- /notebooks/solutions/control_charts.py: -------------------------------------------------------------------------------- 1 | palladium = quandl.get("JOHNMATT/PALL", collapse="monthly") # Monthly Palladium trading price 2 | palladium = palladium[palladium.columns[0]] #We only need one column of data 3 | 4 | palladium_delta = palladium.diff() 5 | 6 | palladium_ucl = palladium_delta.mean() + 3 * palladium_delta.std() 7 | palladium_lcl = palladium_delta.mean() - 3 * palladium_delta.std() 8 | 9 | fig, ax, = plt.subplots(figsize=(12, 12)) 10 | palladium_delta.plot(ax=ax) 11 | ax.hlines([palladium_ucl, palladium_lcl], xmin=palladium_delta.index.min(), xmax=palladium_delta.index.max()) 12 | -------------------------------------------------------------------------------- /notebooks/solutions/correlations.py: -------------------------------------------------------------------------------- 1 | 2 | # Exercise 1 (note the interference also of the constant in the models) 3 | 4 | import statsmodels.formula.api as smf 5 | est_both = smf.ols(formula='target ~ RAD + TAX', data=boston).fit() 6 | 7 | est_both.summary() # For me, RAD beta is 0.2762, TAX is -0.0386 (nearly zero) 8 | 9 | est_rad = smf.ols(formula='target ~ RAD', data=boston).fit() 10 | est_rad.summary() # RAD coeff = -0.4031 11 | 12 | est_tax = smf.ols(formula='target ~ TAX', data=boston).fit() 13 | est_tax.summary() # TAX coeff = -0.0256 14 | 15 | # Exercise 2 16 | 17 | Y = np.random.random(1000) 18 | 19 | X1 = Y * 3 + 5 20 | X2 = Y / 2 21 | 22 | data = pd.Series({"X1": X1, "X2": X2, "Y": Y}) 23 | 24 | est_corr = smf.ols(formula="Y ~ X1 + X2", data=data).fit() 25 | est_corr.summary() # note how the sum of the beta values is about 1 - they are interfering with each other -------------------------------------------------------------------------------- /notebooks/solutions/credible_interval.py: -------------------------------------------------------------------------------- 1 | def shortest_interval(posterior, alpha=0.05, sensitivity=.01): 2 | """ 3 | A (1 - α) credible interval 4 | 5 | Parameters 6 | ---------- 7 | posterior : function 8 | A posterior probability density function (normalized) 9 | 10 | alpha : float 11 | A significance level (of sorts) 12 | 13 | Returns 14 | ------- 15 | A tuple (lower, upper) giving the lower and upper bounds for 16 | the (1 - α) credible interval 17 | """ 18 | 19 | curr_prob = 0.0 20 | target = 1 - alpha 21 | min_length = 1 22 | optimal_start = 0 23 | 24 | # Initialize starting and ending indexes 25 | start = 0 26 | end = 0 27 | while (end < 1): 28 | 29 | # Increase upper bound while 30 | # sum is smaller than or equal to 1-a 31 | while (curr_prob <= target and end < 1): 32 | end += sensitivity 33 | curr_prob, err = integrate.quad(posterior, start, end) 34 | 35 | 36 | # If current sum becomes greater than x 37 | # start increasing lower bound, and save 38 | # smallest interval. 39 | while (curr_prob > target and start < 1): 40 | 41 | # new min length and new start 42 | if min_length > (end - start): 43 | min_length = end - start 44 | optimal_start = start 45 | 46 | start += sensitivity 47 | curr_prob, err = integrate.quad(posterior, start, end) 48 | 49 | 50 | return (optimal_start, optimal_start+min_length) 51 | 52 | beta = scipy.stats.beta(100,200) 53 | low, high = hpd(beta.pdf, alpha=.10, sensitivity=.005) 54 | beta.cdf(high) - beta.cdf(low) #this is equal to 1-a -------------------------------------------------------------------------------- /notebooks/solutions/cross_validation_one.py: -------------------------------------------------------------------------------- 1 | 2 | # Cross validation splits the data into multiple segments, called folds. Commonly, 3 or 10 folds are used. 3 | # We evaluate our model in an iterative test/train split, where each of the fold takes one turn being the "test" 4 | # and all others are the train. Results are then aggregated, such as by taking the mean of the error over all iterations. 5 | 6 | # There is an additional test split in the diagram, because we cannot use a fold for evaluation. 7 | # The reason is that these folds are part of the training of the algorithm, and therefore we cannot use them for 8 | # evaluation. 9 | -------------------------------------------------------------------------------- /notebooks/solutions/detrending.py: -------------------------------------------------------------------------------- 1 | from scipy.signal import detrend 2 | 3 | prices['gold_detrended'] = detrend(prices['gold']) 4 | prices['wheat_detrended'] = detrend(prices['wheat']) 5 | prices[['gold_detrended', 'wheat_detrended']].plot() 6 | 7 | prices[['gold_detrended', 'wheat_detrended']].corr() -------------------------------------------------------------------------------- /notebooks/solutions/dot.py: -------------------------------------------------------------------------------- 1 | 2 | # Because $X$ is a n by k matrix, and $\beta$ is a k by 1 matrix, it needs to be on the right hand side 3 | # for the matrix multiplication to be valid? 4 | -------------------------------------------------------------------------------- /notebooks/solutions/error_term_u.py: -------------------------------------------------------------------------------- 1 | 2 | # $u$ is of shape $n \times 1$, as there is an error term for each sample. A shape of $n$ is also an allowed answer, but note that it is usually a column vector. 3 | -------------------------------------------------------------------------------- /notebooks/solutions/exponential_smoothing.py: -------------------------------------------------------------------------------- 1 | from statsmodels.tsa.holtwinters import ExponentialSmoothing 2 | 3 | ExponentialSmoothing? 4 | 5 | euro = quandl.get("BUNDESBANK/BBEX3_M_AUD_EUR_CM_AC_A01") # Euros in AUD 6 | 7 | euros = euro['Value'] 8 | euros.name = "EURO" 9 | euros.head() 10 | 11 | usd = quandl.get("BUNDESBANK/BBEX3_M_AUD_USD_CM_AC_A01")['Value'] 12 | usd.name = "USD" 13 | usd.head() 14 | 15 | ExponentialSmoothing? 16 | 17 | euro_model = ExponentialSmoothing(euros) 18 | euro_fit = euro_model.fit() 19 | plt.plot(ts.acf(euro_fit.fittedvalues, nlags=100)) 20 | 21 | usd_model = ExponentialSmoothing(usd) 22 | usd_fit = usd_model.fit() 23 | plt.plot(ts.acf(usd_fit.fittedvalues, nlags=100)) 24 | 25 | print("Note that in both cases, you'll generally want to fit the differences or variances, rather than the raw prices") -------------------------------------------------------------------------------- /notebooks/solutions/false_postives.py: -------------------------------------------------------------------------------- 1 | 2 | def run_experiment(n_datapoints=20, threshold=0.8): 3 | # Note that all data here is randomly chosen 4 | x_random = np.random.random(n_datapoints) 5 | y_random = np.random.random(n_datapoints) 6 | corr = np.corrcoef(x_random, y_random)[0,1] 7 | return corr > threshold 8 | 9 | 10 | def run_many_experiments(n_experiments=100000, n_datapoints=20, threshold=0.8): 11 | false_positives = 0 12 | 13 | for i in range(n_experiments): 14 | if run_experiment(n_datapoints=n_datapoints, threshold=threshold): 15 | false_positives += 1 16 | return false_positives / n_experiments 17 | 18 | # Relationship between data size and FP rate 19 | data_size = np.logspace(1, 7, 7, dtype=np.int) 20 | fp_rate_datapoints = np.fromiter((run_many_experiments(n_datapoints=d) for d in data_size), dtype=np.float32) 21 | 22 | plt.plot(data_size, fp_rate_datapoints) 23 | -------------------------------------------------------------------------------- /notebooks/solutions/fit_linear_plot_residuals.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import statsmodels.api as sm 3 | from matplotlib import pyplot as plt 4 | 5 | def fit_linear_plot_residuals(x, y): 6 | """Fits a linear model and plots a residual plot""" 7 | X = sm.add_constant(x) 8 | model = sm.OLS(y, X) # Capital X, which has constants already 9 | results = model.fit() 10 | y_pred = results.predict(X) 11 | 12 | errors = y_pred - y 13 | plt.plot(x, errors, 'ro') 14 | plt.hlines(0, xmin=x.min(), xmax=x.max()) 15 | -------------------------------------------------------------------------------- /notebooks/solutions/generate_significance_data.py: -------------------------------------------------------------------------------- 1 | # NEW: mu=0.17, std = 0.35 2 | # OLD: mu = 0.12, std=0.25 3 | NEW = 1 + np.random.randn(30) * 0.35 + 0.17 4 | OLD = 1 + np.random.randn(30) * 0.25 + 0.12 5 | -------------------------------------------------------------------------------- /notebooks/solutions/histograms.py: -------------------------------------------------------------------------------- 1 | # Exercise 1: The wikipedia article is good on this topic: https://en.wikipedia.org/wiki/Gauss%E2%80%93Markov_theorem 2 | 3 | # Extended exercise 4 | 5 | def run_experiment(data, target_variable_name='target', sample_size=100): 6 | """Fits an OLS to the data, predicting the target from all other variables 7 | """ 8 | sample = data.sample(sample_size) 9 | 10 | column_names = [col for col in data.columns if col != target_variable_name] 11 | # Create formula, predicting target from the sum of all others 12 | formula = "{} ~ {}".format(target_variable_name, str.join(" + ", column_names)) 13 | model = smf.ols(formula=formula, data=sample).fit() 14 | 15 | return model.params 16 | 17 | 18 | # example: 19 | print(run_experiment(boston)) 20 | 21 | # Run many times, join results in a dataframe 22 | results = pd.concat([run_experiment(boston) for i in range(100)], axis=1) 23 | 24 | columns = results.index.values 25 | n_columns = len(columns) 26 | 27 | n_columns 28 | 29 | n_rows, n_cols = 5, 3 30 | 31 | # Output histogram plot for each varaible 32 | # A plot with n_rows rows, n_cols cols, and sized so each is 5 by 3 (inches) 33 | fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols, figsize=(n_cols * 5, n_rows * 3)) 34 | 35 | for row in range(n_rows): 36 | for col in range(n_cols): 37 | plot_number = (row * n_cols) + col 38 | if plot_number >= n_columns: 39 | break 40 | column_name = columns[plot_number] 41 | ax = axes[row, col] 42 | ax.set_title(column_name) 43 | 44 | ax.hist(results.loc[column_name], bins=30) 45 | -------------------------------------------------------------------------------- /notebooks/solutions/hypothesis_one.py: -------------------------------------------------------------------------------- 1 | 2 | # Exercise 3 | # There is a 95% chance of "not a positive result", so for two experiments , we need both to be "not positive" 4 | # The chance of this is 95% times 95% which is 0.95 * 0.95 = 0.9025, approximately 90%, so we have about a 10% 5 | # chance of getting a positive result from at least one of our tests. 6 | 7 | # For ten experiments, that drops to 0.95^10 = 0.59 for "all not positive", about a 40% chance of "at least one positive" 8 | 0.95 ** 20 9 | # For twenty experiments, we have a 0.95^20 = 0.36 for "all not positive" 10 | # about a 64% chance of at least one being positive - so it's *more* likely to get a positive result than not 11 | 12 | # Extended exercise 13 | 14 | import numpy as np 15 | 16 | def get_sample_mean(n_random=100): 17 | sample = np.random.randn(n_random) 18 | return sample.mean() 19 | 20 | N_TESTS = 10000 21 | 22 | means = np.array([get_sample_mean() for i in range(N_TESTS)]) 23 | 24 | plt.hist(means) # Normal distribution, as expected 25 | 26 | 27 | np.sum(means > 0.166) 28 | -------------------------------------------------------------------------------- /notebooks/solutions/hypothesis_two.py: -------------------------------------------------------------------------------- 1 | #1 2 | import quandl 3 | xrate = quandl.get("RBA/FXRUSD-AUD-USD-Exchange-Rate") 4 | 5 | #2 6 | xdelta = xrate.diff().dropna() 7 | xdelta['lag'] = xdelta['Value'].shift(1) 8 | xdelta = xdelta.dropna() 9 | xdelta['matched_movement'] = xdelta['Value']*xdelta['lag'] > 0 # compare values to lagged values 10 | samp_prop = np.sum(xdelta['matched_movement'])/xdelta.shape[0] # get proportion of movements that match the previous movement 11 | samp_prop 12 | 13 | 14 | #Extended Exercise 15 | 16 | iters = range(1000) #Repeat our experiment 1000 times. 17 | results = [] 18 | distribution = norm(0, 1) 19 | 20 | for i in iters: 21 | X = distribution.rvs(365) # create randomly distributed data for a year 22 | data = pd.DataFrame([X[i] for i in range(len(X))]) 23 | data.columns = ['Value'] 24 | data['lag'] = data['Value'].shift(1) 25 | data = data.dropna() 26 | data['matched_movement'] = data['Value']*data['lag'] > 0 # compare values to lagged values 27 | data_prop = np.sum(data['matched_movement'])/data.shape[0] 28 | results.append(data_prop) 29 | 30 | plt.hist(results) 31 | 32 | stats.ttest_1samp(results, 0.5) 33 | print('t stat: {:.4f}, p value: {:4f}'.format(t_stat, p_val)) 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /notebooks/solutions/increasing_variability.py: -------------------------------------------------------------------------------- 1 | 2 | y_increasing = np.random.random(len(x)) * np.arange(len(x)) * 25 # Your equation may vary 3 | 4 | plt.plot(x, y_increasing, 'bo') 5 | 6 | fit_linear_plot_residuals(x, y_increasing) 7 | -------------------------------------------------------------------------------- /notebooks/solutions/inferring_statistics.py: -------------------------------------------------------------------------------- 1 | 2 | # 1. We say we reject the null hypothesis, as it has a p value of less than 0.05, i.e. a less than 5% chance of occurring purely by chance. 3 | # 2. The likelihood of the samples given the assumptions is 0.08% (i.e. less than a tenth of 1%). 4 | # 3. No. We are confident the expected value is more than 3.5, but we do not know why (it may be loaded to 5s for instance). 5 | 6 | 7 | # ### Extended Solution 8 | 9 | # $H_0$ The dice rolls 6s, on average, in 1/6 rolls 10 | 11 | # $H_A$ The dice rolls 6s, on average, more then 1/6 rolls 12 | 13 | # Roll a normal dice 1000 times, and record the number of 6s rolled. Repeat many times. 14 | 15 | # Roll the suspected dice 1000 times and record the number of 6s rolled. Repeat many times. 16 | 17 | # Perform the `stats.ttest_1samp` test above. 18 | -------------------------------------------------------------------------------- /notebooks/solutions/jarque_bera.py: -------------------------------------------------------------------------------- 1 | 2 | from statsmodels.stats import stattools 3 | 4 | # In a notebook cell, run: 5 | stattools.jarque_bera? 6 | 7 | jbstat, pvalue, skew, kurtosis = stattools.jarque_bera(heights) 8 | print(pvalue) 9 | 10 | if pvalue < 0.05: 11 | print("We reject the null hypothesis that the data is normal") 12 | else: 13 | print("We cannot reject that the data came from a normal distribution") -------------------------------------------------------------------------------- /notebooks/solutions/kalman_basics.py: -------------------------------------------------------------------------------- 1 | 2 | # Question 1 3 | class KalmanFilter: 4 | 5 | def __init__(self, original_estimate, estimated_measurement_error, original_estimated_error=0): 6 | self.current_estimate = original_estimate 7 | self.estimated_measurement_error = estimated_measurement_error 8 | self.current_error = original_estimated_error 9 | self.estimates = [] 10 | 11 | def update(self, new_data): 12 | kalman_gain = 1e-6 + self.current_error / (1e-6 + self.current_error + self.estimated_measurement_error) 13 | # print(kalman_gain, self.current_error, self.current_estimate) 14 | # Update estimate 15 | self.current_estimate = self.current_estimate + kalman_gain * (new_data - self.current_estimate) 16 | self.current_error = (1 - kalman_gain) * self.current_error # Update error 17 | self.estimates.append(self.current_estimate) 18 | return self.current_estimate 19 | 20 | data = np.random.randn(1000) * 5 + 25 21 | temperature_filter = KalmanFilter(30, 5, 2) 22 | 23 | for measurement in data: 24 | estimated_temperature = temperature_filter.update(measurement) -------------------------------------------------------------------------------- /notebooks/solutions/lagged_correlations.py: -------------------------------------------------------------------------------- 1 | 2 | # combined comes from previous data 3 | 4 | def compute_lagged_correlation(combined, lag=1): 5 | combined['Lagged Inflation'] = combined['Inflation'].shift(lag) 6 | return combined.corr().loc[('Cash Rate', "Lagged Inflation")] 7 | 8 | lag = list(range(-12, 13, 1)) 9 | lagged_correlation = pd.Series([compute_lagged_correlation(combined, lag=lag) for lag in lag], index=lag) 10 | lagged_correlation.index.name = "Lag" 11 | lagged_correlation.name = "Cross Correlation" 12 | 13 | lagged_correlation.plot(); 14 | 15 | # Answer to question: 16 | # The -1 to -3 lag indicates that the cash rate appears to change in response to inflation, 17 | # rather than the other way around. -------------------------------------------------------------------------------- /notebooks/solutions/linear_regression_intro.py: -------------------------------------------------------------------------------- 1 | 2 | # Question 1 3 | # You wouldn't use the actual error, as the "negative" errors would cancel out the positive errors 4 | raw_error = np.sum(predicted_prices - prices['MedianPrice']) 5 | print(raw_error) # note how "small" this is, compared to the absolute error 6 | 7 | 8 | # Question 2 9 | # (beta, intercept) 10 | models = [(-100, 1100), 11 | (-130, 1200), 12 | (-90, 900)] 13 | 14 | best_error = None 15 | best_model = None 16 | 17 | for model in models: 18 | print("Model is: {}".format(model)) 19 | m, c = model 20 | predicted_scores = prices['CashRate'] * m + c # Same values as before - this is our "model" 21 | squared_error = np.sum((predicted_prices - prices['MedianPrice']) ** 2) 22 | print(" The squared error is {:.2f}".format(squared_error)) 23 | 24 | if best_error is None or squared_error < best_error: 25 | best_error = squared_error 26 | best_model = model 27 | 28 | print("The best model was {}".format(best_model)) -------------------------------------------------------------------------------- /notebooks/solutions/ljungbox.py: -------------------------------------------------------------------------------- 1 | 2 | # We reject that the data is independently distributed for lags of 1 and 2, giving evidence for H_A 3 | # that there is a serial correlation for these two lag periods. 4 | -------------------------------------------------------------------------------- /notebooks/solutions/ma_model.py: -------------------------------------------------------------------------------- 1 | # Exercise solution 2 | import my_secrets 3 | quandl.ApiConfig.api_key = my_secrets.QUANDL_API_KEY 4 | 5 | data = quandl.get_table('WIKI/PRICES', ticker = ['AAPL'], 6 | qopts = { 'columns': ['adj_close'] }, 7 | date = { 'gte': '2017-01-01', 'lte': '2019-01-01' }, 8 | paginate=True) 9 | 10 | changes = data['adj_close'].diff().dropna() 11 | model = sm.tsa.ARMA(changes, order=(0,1)) 12 | stock_results= model.fit() 13 | 14 | stock_results.summary() 15 | 16 | # Extended exercise solution 17 | epsilons = np.array([0, 0, 0, 1, 0, 1, 1, 1, 1, 0]) # Try different combinations here. 18 | 19 | theta = -2 20 | print("theta: ", theta) 21 | 22 | X = epsilons[1:] + theta * epsilons[:-1] 23 | print(np.mean(epsilons)) 24 | 25 | plt.plot(X) 26 | -------------------------------------------------------------------------------- /notebooks/solutions/make_stationary.py: -------------------------------------------------------------------------------- 1 | 2 | from statsmodels.tsa.tsatools import detrend 3 | 4 | Xst_detrended = detrend(X_stationary) 5 | Xnonst_detrended = detrend(X_non_stationary) 6 | Xar1_detrended = detrend(X_AR1) 7 | 8 | 9 | from statsmodels.tsa.stattools import adfuller 10 | 11 | # X_stationary 12 | plt.plot(X_stationary, alpha=0.5) 13 | plt.plot(Xst_detrended, 'r--', alpha=0.5) # No difference 14 | 15 | adf, p_value, *_ = adfuller(Xst_detrended) 16 | 17 | p_value < 0.05, p_value # Reject hypothesis of a unit root, which indicates stationary 18 | 19 | plt.plot(X_non_stationary, alpha=0.5) 20 | plt.plot(Xnonst_detrended) # Removed linear increase 21 | 22 | adf, p_value, *_ = adfuller(Xnonst_detrended) 23 | 24 | p_value < 0.05, p_value # Reject hypothesis of a unit root, which indicates stationary 25 | 26 | plt.plot(X_AR1, alpha=0.5) 27 | plt.plot(Xar1_detrended) # linear detrends aren't perfect 28 | 29 | adf, p_value, *_ = adfuller(Xar1_detrended) 30 | 31 | p_value < 0.05, p_value # Do NOT hypothesis of a unit root, which indicates stationary 32 | 33 | # In this case, linear detrend is not sufficient to make stationary 34 | -------------------------------------------------------------------------------- /notebooks/solutions/many_normal_tests.py: -------------------------------------------------------------------------------- 1 | from statsmodels import api as sm 2 | from statsmodels.stats import stattools 3 | 4 | max_sample_size = 200 5 | distribution = stats.norm() 6 | 7 | 8 | sample_size_values = np.linspace(10, max_sample_size, 20, dtype=np.int) 9 | results = [] # Store all results here 10 | 11 | for sample_size in sample_size_values: 12 | 13 | scipy_normal_test_passed = 0 14 | scipy_kstest_passed = 0 15 | statsmodels_kstest_passed = 0 16 | statsmodels_jarque_bera_passed = 0 17 | 18 | for i in range(1000): 19 | data = distribution.rvs(sample_size) 20 | 21 | # scipy normaltest 22 | stat, p = stats.normaltest(data) 23 | if p > 0.05: 24 | scipy_normal_test_passed += 1 25 | 26 | # scipy kstest 27 | stat, p = stats.kstest(data, 'norm') 28 | if p > 0.05: 29 | scipy_kstest_passed += 1 30 | 31 | # statsmodels kstest 32 | statistic, p_value = sm.stats.diagnostic.kstest_normal(data) 33 | if p_value > 0.05: 34 | statsmodels_kstest_passed += 1 35 | 36 | # statsmodels jarque_bera 37 | jbstat, pvalue, skew, kurtosis = stattools.jarque_bera(data) 38 | if pvalue > 0.05: 39 | # Same as scipy.normaltest! 40 | statsmodels_jarque_bera_passed += 1 41 | 42 | row = [scipy_normal_test_passed, scipy_kstest_passed, statsmodels_kstest_passed, statsmodels_jarque_bera_passed] 43 | 44 | results.append(row) 45 | 46 | results = np.array(results) # Convert to NumPy for fancy indexing 47 | 48 | plt.plot(sample_size_values, results[:,0], alpha=0.5, label='scipy.normaltest') 49 | plt.plot(sample_size_values, results[:,1], alpha=0.5, label='scipy.kstest') 50 | plt.plot(sample_size_values, results[:,2], alpha=0.5, label='statsmodels.kstest_normal') 51 | plt.plot(sample_size_values, results[:,3], alpha=0.5, label='statsmodels.jarque_bera') 52 | plt.legend(bbox_to_anchor=(1.05, 1.0)) 53 | -------------------------------------------------------------------------------- /notebooks/solutions/matrix_products.py: -------------------------------------------------------------------------------- 1 | # Exercise 1 2 | print(B.shape) # Shape is (3, 2), so V2 must be (2, 1) 3 | V2 = np.array([1, 2]) # Shape is (2,), NumPy figures out the rest, but the result is the wrong shape: 4 | 5 | result1 = B.dot(V2) 6 | print(result1, result1.shape) 7 | 8 | result2 = B.dot(V2.reshape(-1, 1)) 9 | 10 | print(result2, result2.shape) # Better shape for future matrix multiplication 11 | 12 | B 13 | 14 | # Exercise 2 15 | B.dot(np.ones(shape=(2, 1))) # Note: row-wise sum 16 | 17 | # Exercise 3 18 | B.T # Rotates by 90 degress. Rows become columns, columns become rows -------------------------------------------------------------------------------- /notebooks/solutions/matrix_terminology.py: -------------------------------------------------------------------------------- 1 | "" 2 | # 1. Use the np.arange and np.reshape functions to create a square matrix 3 | S = np.arange(16).reshape(4, 4) 4 | print(S) 5 | 6 | # 2. Use the np.diag function to create a diagonal matrix 7 | D = np.diag([1, 2, 3]) 8 | print(D) 9 | 10 | # 3. Use the np.eye function to create an identity matrix 11 | I = np.eye(4) 12 | print(I) 13 | 14 | # 4. Create a scalar matrix 15 | C = np.eye(4) * 5 16 | print(C) 17 | 18 | # 5. Use the np.zeros function to create a null matrix of size 4 by 5 19 | N = np.zeros(shape=(4, 5)) 20 | print(N) -------------------------------------------------------------------------------- /notebooks/solutions/moments.py: -------------------------------------------------------------------------------- 1 | # Exercise 1 2 | aapl['Gain'] = aapl['Close'] - aapl['Open'] 3 | 4 | # Exercise 2 5 | alt.Chart(aapl).mark_bar().encode( 6 | alt.X("Gain", bin=alt.Bin(maxbins=100)), 7 | y='count()' 8 | ) 9 | 10 | # Exercise 3 11 | skew = stats.skew(aapl['Gain']) 12 | print("The skew is {}".format(skew)) 13 | kurtosis = stats.kurtosis(aapl['Gain']) 14 | print("The kurtosis is {}".format(kurtosis)) -------------------------------------------------------------------------------- /notebooks/solutions/multiple_comparisons.py: -------------------------------------------------------------------------------- 1 | 2 | # After modify the threshold, the result is no longer significant. -------------------------------------------------------------------------------- /notebooks/solutions/normal_distributions.py: -------------------------------------------------------------------------------- 1 | 2 | # Question 2 answer 3 | 4 | def plot_histogram_normal(mean, standard_deviation): 5 | distribution = stats.norm(mean, standard_deviation) 6 | normal_values = pd.DataFrame({"value": distribution.rvs(10000)}) 7 | 8 | chart = alt.Chart(normal_values).mark_bar().encode( 9 | alt.X("value", bin=alt.Bin(maxbins=100)), 10 | 'count()' 11 | ) 12 | return chart 13 | 14 | 15 | # Same function, but with colour as an option 16 | def plot_histogram_normal(mean, standard_deviation, color): 17 | distribution = stats.norm(mean, standard_deviation) 18 | normal_values = pd.DataFrame({"value": distribution.rvs(10000)}) 19 | 20 | chart = alt.Chart(normal_values).mark_bar().encode( 21 | alt.X("value", bin=alt.Bin(maxbins=100)), 22 | y='count()', 23 | color=alt.value(color) 24 | ) 25 | return chart 26 | 27 | chart1 = plot_histogram_normal(1, 7, color="#8b8378") 28 | 29 | chart1 # Running just "chart1" in a Jupyter Notebook cell will show the chart 30 | 31 | chart2 = plot_histogram_normal(10, 1, color="#cd5c5c") 32 | 33 | chart3 = plot_histogram_normal(-10, 5, color="#9acd32") 34 | 35 | chart1 + chart2 + chart3 # Running this in it's own cell will show all three charts overlaid -------------------------------------------------------------------------------- /notebooks/solutions/ols_basic_ensemble.py: -------------------------------------------------------------------------------- 1 | # Question 1 2 | mask = cash_rate < 6 3 | cash_rate_cleaned = cash_rate[mask] 4 | house_prices_cleaned = house_prices[mask] # Don't forget to use the same mask for both X and Y 5 | 6 | plt.plot(cash_rate_cleaned, house_prices_cleaned, 'ro') 7 | plt.xlabel("Cash Rate") 8 | plt.ylabel("SAT Score") 9 | 10 | ones_cleaned = np.ones((len(cash_rate_cleaned))) 11 | X_cleaned = np.vstack([ones_cleaned, cash_rate_cleaned]).T 12 | 13 | Y_cleaned = house_prices_cleaned.reshape((len(house_prices_cleaned), 1)) 14 | 15 | beta_cleaned = np.linalg.inv(X_cleaned.T.dot(X_cleaned)).dot(X_cleaned.T.dot(Y_cleaned)) 16 | print(beta_cleaned) 17 | 18 | plt.plot(cash_rate_cleaned, house_prices_cleaned, 'ro') 19 | plt.xlabel("Cash Rate") 20 | plt.ylabel("House Prices") 21 | 22 | # Here we create x values for "each hour of study" so we can plot the results 23 | x_model = np.arange(0, 8, 0.25) 24 | y_model = x_model * beta[1] + beta[0] # Use our learned model to fit the line of best fit. 25 | 26 | plt.plot(x_model, y_model, 'b-') 27 | 28 | # Question 2 29 | 30 | # Store parameter versions here 31 | models = [] 32 | 33 | n = len(cash_rate_cleaned) 34 | 35 | for i in range(100): 36 | 37 | # Choose random indexes 38 | # replace=True is better statistically, we will come back to it later on... 39 | random_indexes = np.random.choice(np.arange(n), size=int(n/2), replace=True) 40 | cash_rate_sample = cash_rate[random_indexes] 41 | house_prices_sample = house_prices[random_indexes] 42 | 43 | ones_sample = np.ones((len(cash_rate_sample))) 44 | X_sample = np.vstack([ones_sample, cash_rate_sample]).T 45 | 46 | Y_sample = house_prices_sample.reshape((len(house_prices_sample), 1)) 47 | 48 | beta_sample = np.linalg.inv(X_sample.T.dot(X_sample)).dot(X_sample.T.dot(Y_sample)) 49 | models.append(beta_sample) 50 | # Average all parameters 51 | final_model = np.mean(models, axis=0) 52 | print(final_model) -------------------------------------------------------------------------------- /notebooks/solutions/ols_train_test.py: -------------------------------------------------------------------------------- 1 | split_point = int(2 * len(X) / 3) 2 | X_train, X_test = X[:split_point], X[split_point:] 3 | y_train, y_test = y[:split_point], y[split_point:] 4 | 5 | 6 | # Fit an OLS model and get a summary 7 | est = sm.OLS(y_train, X_train).fit() 8 | 9 | y_pred = est.predict(X_test) 10 | y_pred.name = "PredictedInflation" 11 | 12 | pd.concat([y_test, y_pred], axis=1).plot() # Not as good... -------------------------------------------------------------------------------- /notebooks/solutions/ordinal_encoding.py: -------------------------------------------------------------------------------- 1 | 1. sklearn.preprocessing.OrdinalEncoder - Takes an array-like of strings or integers and creates an 2 | # encoder to transform the data into an array of integer categories. 3 | # sklearn.preprocessing.OneHotEncoder - Takes nominal data in an array-like and encodes into a binary array with 4 | # one place per feature. 5 | 6 | #Extended Exercise 7 | 8 | #1. Unsure, though it looks like if you 'fit()' a dataset and it's NOT already ordered correctly the function 9 | # will categorise the data, but not necessarily in the order you want? 10 | 11 | #2. Using Customer survey data for value of primary residence from University of Michigan. 12 | %run setup.ipy 13 | 14 | import quandl 15 | import my_secrets 16 | quandl.ApiConfig.api_key = my_secrets.QUANDL_API_KEY 17 | 18 | housing_prices = quandl.get("UMICH/SOC22-University-of-Michigan-Consumer-Survey-Current-Market-Value-of-Primary-Residence") 19 | housing_prices = housing_prices.iloc[:,0:6] #Trim data down to price categories only 20 | housing_prices 21 | 22 | from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder 23 | 24 | ord_enc = OrdinalEncoder() 25 | ord_enc.fit(housing_prices) 26 | ord_prices = ord_enc.transform(housing_prices) 27 | 28 | hot_enc = OneHotEncoder(categories='auto') 29 | hot_enc.fit(housing_prices) 30 | hot_enc.transform(housing_prices).toarray() 31 | -------------------------------------------------------------------------------- /notebooks/solutions/ordinal_nominal.py: -------------------------------------------------------------------------------- 1 | 2 | # 1) Ratio, has a true zero 3 | # 2) Ratio, has a true zero 4 | # 3) Ordinal, the data can be ordered from "less education" to "more education" 5 | # 4) Nominal, as there is no ordering 6 | -------------------------------------------------------------------------------- /notebooks/solutions/overfitting_arma.py: -------------------------------------------------------------------------------- 1 | # Solution 2 | training = employment.loc[:"2000-01-01"] 3 | testing = employment.loc["2000-01-02":] 4 | 5 | statistics = stattools.arma_order_select_ic(training) # May take a few minutes 6 | 7 | statistics['bic'] 8 | 9 | statistics.bic_min_order 10 | 11 | model = sms.tsa.ARMA(training, order=(p, q)) 12 | 13 | results = model.fit() 14 | 15 | results.summary() 16 | 17 | y_pred = results.predict(start=testing.index.min(), end=testing.index.max()) 18 | 19 | plt.plot(y_pred, 'r--') 20 | plt.plot(testing) 21 | -------------------------------------------------------------------------------- /notebooks/solutions/overfitting_one.py: -------------------------------------------------------------------------------- 1 | # 50 points randomly from 0 to 100 2 | x_test = np.random.random(50) * 100 3 | error_test = np.random.randn(len(x_test)) * 5 4 | y_test = x_test * 3 + 1 + error_test 5 | 6 | # Training errors 7 | SSE_linear = np.sum((y_pred_linear - y) ** 2) 8 | SSE_overfit = np.sum((y_pred_overfit - y) ** 2) 9 | 10 | print(SSE_linear, SSE_overfit) # Overfit is lower for training error 11 | 12 | plt.plot(x_test, y_test, 'go', alpha=0.5) 13 | 14 | y_est_linear = model(x_test) 15 | y_est_poly = model_30(x_test) 16 | 17 | # Training errors 18 | SSE_est_linear = np.sum((y_est_linear - y_test) ** 2) 19 | SSE_est_overfit = np.sum((y_est_poly - y_test) ** 2) 20 | 21 | print(SSE_est_linear, SSE_est_overfit) # SSE is **very** high for the overfit model. 22 | -------------------------------------------------------------------------------- /notebooks/solutions/overfitting_three.py: -------------------------------------------------------------------------------- 1 | #1 2 | from sklearn.linear_model import Ridge 3 | # Create a dataset 4 | 5 | x = (np.random.random(20) * 10) 6 | y = 3 * x + (np.random.rand(20) * 25) 7 | plt.plot(x, y, 'ro', label="Data") 8 | 9 | x = x.reshape(-1,1) 10 | l_model = LinearRegression() 11 | r_model = Ridge(alpha=100) 12 | l_model.fit(x,y) 13 | r_model.fit(x,y) 14 | l_pred = l_model.predict(x) 15 | r_pred = r_model.predict(x) 16 | plt.plot(l_pred, label="Linear") 17 | plt.plot(r_pred, label="Ridge") 18 | 19 | 20 | #2 21 | from sklearn.model_selection import GridSearchCV 22 | 23 | test_range = np.arange(100) 24 | param_grid = {"alpha": test_range} 25 | gs = GridSearchCV(Ridge(),param_grid) 26 | gs.fit(x, y) 27 | gs.best_params_ 28 | -------------------------------------------------------------------------------- /notebooks/solutions/pca_different_kinds.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from sklearn.datasets import make_friedman1 3 | from sklearn.decomposition import PCA 4 | from sklearn.decomposition import SparsePCA 5 | 6 | def pca_transform(pca, X): 7 | pca.fit(X) 8 | X_transformed = pca.transform(X) 9 | 10 | # Generate datasets 11 | X, _ = make_friedman1(n_samples=10000, n_features=1000, random_state=0) 12 | sparse_X = np.diag(np.random.normal(size=1000)) 13 | 14 | # Different kinds of PCA 15 | pca = PCA(n_components=2, svd_solver= 'full') 16 | randomizedpca = PCA(n_components=2, svd_solver= 'randomized') 17 | sparsepca = SparsePCA(n_components=2, random_state=0) 18 | 19 | # Evaluate on a normal dataset 20 | %time pca_transform(pca, X) 21 | %time pca_transform(randomizedpca, X) # Fastest 22 | %time pca_transform(sparsepca, X) # it would cost too much time 23 | 24 | # Evaluate on a sparse dataset 25 | %time pca_transform(pca, sparse_X) 26 | %time pca_transform(randomizedpca, sparse_X) # still Fastest 27 | %time pca_transform(sparsepca, sparse_X) -------------------------------------------------------------------------------- /notebooks/solutions/pca_explained_variance.py: -------------------------------------------------------------------------------- 1 | 2 | # Fit a PCA model to the data 3 | full_pca = PCA(n_components=64) 4 | full_pca.fit(X) 5 | 6 | # Plot the cumulative sum 7 | plt.plot(np.cumsum(full_pca.explained_variance_ratio_)) 8 | -------------------------------------------------------------------------------- /notebooks/solutions/pca_numpy.py: -------------------------------------------------------------------------------- 1 | # Solution to extended exercise, 2 | # based on https://medium.com/100-days-of-algorithms/day-92-pca-bdb66840a8fb 3 | 4 | def PCA(X, n_components): 5 | # normalize to zero mean 6 | mu = X.mean(axis=0) 7 | X = X - mu 8 | 9 | # eigenvectors of covariance matrix 10 | sigma = X.T @ X 11 | eigvals, eigvecs = np.linalg.eig(sigma) 12 | 13 | # principal components 14 | order = np.argsort(eigvals)[::-1] 15 | components = eigvecs[:, order[:n_components]] 16 | 17 | # projection 18 | Z = X @ components 19 | 20 | # result 21 | return Z, components 22 | -------------------------------------------------------------------------------- /notebooks/solutions/pca_statsmodels.py: -------------------------------------------------------------------------------- 1 | 2 | from statsmodels.multivariate.pca import PCA 3 | 4 | model = PCA(X) 5 | 6 | transformed = model.transformed_data 7 | 8 | components = model.eigenvecs 9 | 10 | components 11 | -------------------------------------------------------------------------------- /notebooks/solutions/plotting_distributions.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Exercise 1 4 | def calculate_mean_of_random_iterations(distribution, n_random=10000): 5 | """Computes 10,000 random values from a given distribution and returns the mean""" 6 | random_values = distribution.rvs(n_random) 7 | return random_values.mean() 8 | 9 | distributions = dict([("normal", stats.norm()), 10 | ("gamma", stats.gamma(0.5)), 11 | ("uniform", stats.uniform(0, 1)) 12 | ]) 13 | 14 | for distribution_name, distribution in distributions.items(): 15 | print(distribution_name, calculate_mean_of_random_iterations(distribution)) 16 | 17 | def create_many_means(distribution, n_iterations=1000): 18 | """Performs many iterations of `calculate_mean_of_random_iterations` and records the values""" 19 | # Note: you can do this with a list comprehension. A rolled out loop 20 | # is used here for clarity 21 | means = [] 22 | for iteration in range(n_iterations): 23 | means.append(calculate_mean_of_random_iterations(distribution)) 24 | return means 25 | 26 | means = pd.DataFrame({distribution_name: create_many_means(distribution) 27 | for distribution_name, distribution in distributions.items()}) 28 | data = pd.melt(means, var_name='Distribution', value_name='Sample Mean') 29 | 30 | charts = {} 31 | 32 | for distribution_name in distributions: 33 | print(distribution_name) 34 | current_data = data[data["Distribution"] == distribution_name] 35 | cur_chart = alt.Chart(current_data).mark_area( 36 | opacity=0.3, 37 | interpolate='step' 38 | ).encode( 39 | alt.X('Sample Mean', bin=alt.Bin(maxbins=100)), 40 | alt.Y('count()', stack=None), 41 | alt.Color( 42 | 'Distribution', 43 | scale=alt.Scale(range=['#0000ff', '#008000', '#ff0000']) 44 | ), 45 | ) 46 | charts[distribution_name] = cur_chart 47 | 48 | 49 | alt.layer(*charts.values()).resolve_scale(x='independent') -------------------------------------------------------------------------------- /notebooks/solutions/polyfit.py: -------------------------------------------------------------------------------- 1 | #1 2 | train_err = y_pred_low[0:50] - y_low 3 | train_SSE = np.sum(train_err **2) 4 | train_SSE 5 | 6 | test_err = y_pred_low[50:100] - y_high 7 | test_SSE = np.sum(test_err **2) 8 | test_SSE 9 | 10 | #2 11 | 12 | # Fit model to each 13 | params_low = np.polyfit(x_low, y_low, 2) 14 | params_high = np.polyfit(x_high, y_high, 2) 15 | 16 | plt.plot(x, y, 'r-') # Actual data in red 17 | 18 | y_pred_low = np.poly1d(params_low)(x) 19 | plt.plot(x, y_pred_low, 'g--') # Predictions from "low" model in green 20 | 21 | y_pred_high = np.poly1d(params_high)(x) 22 | plt.plot(x, y_pred_high, 'k--') # Predictions from "high" model in black 23 | 24 | # Rerun our SSE calculations 25 | 26 | train_err = y_pred_low[0:50] - y_low 27 | train_SSE = np.sum(train_err **2) 28 | train_SSE 29 | 30 | test_err = y_pred_low[50:100] - y_high 31 | test_SSE = np.sum(test_err **2) 32 | test_SSE 33 | -------------------------------------------------------------------------------- /notebooks/solutions/prior_postcode_given_state.py: -------------------------------------------------------------------------------- 1 | 2 | def prior_postcode_given_state(postcode, state): 3 | postcodes = postcodes_by_state[state] 4 | return 1.0 / len(postcodes) if postcode in postcodes else 0 5 | 6 | prior_postcode_given_state(3122, 'Victoria') 7 | 8 | prior_postcode(3122) 9 | -------------------------------------------------------------------------------- /notebooks/solutions/public_medical.py: -------------------------------------------------------------------------------- 1 | # Solution question 2 2 | def prior(model): 3 | return {'chickenpox': 1e-4, 'not chickenpox': 1 - 1e-4}.get(model) 4 | 5 | def posterior(model, data, normalize=True, x=0.2): 6 | """ 7 | Posterior probability of the model ('chickenpox' / 'not chickenpox') 8 | given the data ('spots' / 'no spots') 9 | 10 | 11 | x here is P("not chickenpox" | "spots") 12 | """ 13 | numerator = likelihood(data, model, x) * prior(model) 14 | if not normalize: 15 | return numerator 16 | else: 17 | return numerator / evidence(data) 18 | 19 | def likelihood(data, model, x=0.2): 20 | """ 21 | Conditional probability of the data ('spots' / 'no spots') given the model ('chickenpox' / 'not chickenpox'). 22 | 23 | x here is P("not chickenpox" | "spots") 24 | """ 25 | if data == 'spots': 26 | return {'chickenpox': 0.8, 'not chickenpox': x}[model] 27 | else: 28 | # no spots 29 | return {'chickenpox': 0.2, 'not chickenpox': 1 - x}[model] 30 | 31 | def evidence(data): 32 | """ 33 | The proportion of people in the general population who have spots or no spots 34 | """ 35 | return (posterior('chickenpox', data, normalize=False) + 36 | posterior('not chickenpox', data, normalize=False)) 37 | 38 | conditional_sum = (posterior('chickenpox', 'spots', normalize=True) + 39 | posterior('not chickenpox', 'spots', normalize=True)) 40 | 41 | conditional_sum 42 | 43 | posterior('chickenpox', 'spots') 44 | -------------------------------------------------------------------------------- /notebooks/solutions/ratio_interval.py: -------------------------------------------------------------------------------- 1 | 2 | # 1) No, the ratios stay the same (all currencies that I'm aware of are Ratios) 3 | # 2) It's a Ratio! Unlike Celcius and Fahrenheit, Kelvin has a clear zero - the absolute zero 4 | -------------------------------------------------------------------------------- /notebooks/solutions/representing_prior_information.py: -------------------------------------------------------------------------------- 1 | 2 | def in_cbd(postcodes): 3 | return [postcode in CBD_POSTCODES for postcode in postcodes] 4 | 5 | features2 = features + [in_cbd] 6 | 7 | k2 = np.c_[k, 0.25] 8 | k2 9 | 10 | assert len(features2) == k2.shape[1] 11 | 12 | model2 = MinDivergenceModel(features2, samplespace, vectorized=True) 13 | 14 | model2.fit(k2); 15 | 16 | assert np.allclose(model2.expectations(), k2, atol=1e-6) 17 | 18 | p2 = model2.probdist() 19 | 20 | fig, axes = plt.subplots(1, figsize=(12, 5)) 21 | plt.plot(samplespace, p2, '.', ) 22 | axes.set_xlabel('postcode') 23 | axes.set_ylabel('probability') 24 | 25 | # We can see more by using a logarithmic vertical axis: 26 | 27 | fig, axes = plt.subplots(1, figsize=(12, 5)) 28 | plt.semilogy(samplespace, p2, '.', ) 29 | axes.set_xlabel('postcode') 30 | axes.set_ylabel('probability') 31 | -------------------------------------------------------------------------------- /notebooks/solutions/residual_analysis_one.py: -------------------------------------------------------------------------------- 1 | #1 2 | from statsmodels.tsa.stattools import bds 3 | 4 | X = x 5 | X = sm.add_constant(x) 6 | model = sm.OLS(y_quad, X) 7 | results = model.fit() 8 | y_pred = results.predict(X) 9 | 10 | errors = y_pred - y_quad 11 | plt.plot(x, errors, 'ro') 12 | 13 | stat, p = bds(x) 14 | stat, p 15 | 16 | 17 | #2 18 | from statsmodels.stats.diagnostic import acorr_ljungbox 19 | 20 | lb, p = acorr_ljungbox(errors) 21 | lb, p 22 | 23 | 24 | -------------------------------------------------------------------------------- /notebooks/solutions/residual_analysis_two.py: -------------------------------------------------------------------------------- 1 | from statsmodels.tsa.seasonal import seasonal_decompose 2 | 3 | X = sm.add_constant(x) 4 | model = sm.OLS(y_seasonal, X) 5 | results = model.fit() 6 | y_pred = results.predict(X) 7 | 8 | errors = y_pred - y_seasonal 9 | plt.plot(x, errors, 'ro') 10 | 11 | # Apply seasonal decomposition to our data 12 | result = seasonal_decompose(y_seasonal, model="additive", freq=12) 13 | # Plot the residuals after decomposition 14 | plt.plot(x, result.resid, 'ro') 15 | 16 | #Remove the seasonal trending from our data 17 | y_clean = y_seasonal - result.seasonal 18 | 19 | model = sm.OLS(y_clean, X) 20 | results = model.fit() 21 | y_pred = results.predict(X) 22 | 23 | errors = y_pred - y_clean 24 | #Plot our cleaned Data 25 | plt.plot(x, y_clean) 26 | # Check residuals 27 | plt.plot(x, errors, 'ro') 28 | -------------------------------------------------------------------------------- /notebooks/solutions/residual_plotting.py: -------------------------------------------------------------------------------- 1 | from scipy import stats 2 | 3 | n = int(len(X) / 2) 4 | 5 | stats.levene(X[:n], X[n:]) 6 | 7 | # Extended exercise solution 8 | import statsmodels.api as sm 9 | 10 | # Create some random 11 | y = np.random.random(len(X)) 12 | est = sm.OLS(y, X).fit() 13 | 14 | y_pred = est.fittedvalues 15 | 16 | residuals = y_pred - y 17 | 18 | plt.plot(y_pred, residuals, 'ro') # No clear pattern == white noise 19 | -------------------------------------------------------------------------------- /notebooks/solutions/rolling_forecast.py: -------------------------------------------------------------------------------- 1 | # Rolling Forecast Origin Function 2 | def rolling_forecasting_origin(time_series, m=1): 3 | """Performs a rolling forecasting origin with steps of m 4 | 5 | parameters: 6 | time_series: pandas data frame with a time series index 7 | m: positive non-zero integer. 1 by default 8 | 9 | returns: 10 | folds: a list of each of the training and testing folds for pandas. 11 | """ 12 | 13 | idx_max = len(time_series) 14 | iters = np.arange(1, idx_max - m + 1) 15 | folds = [[[0],m]] # np.arange does not return a valid result, so start from 1 16 | 17 | for i in iters: 18 | train_fold = np.arange(0, i + 1) 19 | test_fold = min(i + m, idx_max) 20 | folds.append([train_fold, test_fold]) 21 | 22 | return folds 23 | 24 | # Let's test our function! 25 | dates = np.array('2015-07-04', dtype=np.datetime64) + np.arange(100) 26 | dates 27 | rolling_forecasting_origin(date, 10) 28 | 29 | # Here is essentially the same function code, but presented as a python generator which 30 | # can be iterated over, for example in a for loop. 31 | def rolling_forecasting_origin_generator(time_series, m=1): 32 | """Performs a rolling forecasting origin with steps of m 33 | 34 | parameters: 35 | time_series: pandas data frame with a time series index 36 | m: positive non-zero integer. 1 by default 37 | 38 | returns: 39 | folds: a list of each of the training and testing folds for pandas. 40 | """ 41 | 42 | idx_max = len(time_series) 43 | iters = np.arange(1, idx_max - m + 1) 44 | folds = [[[0],m]] # np.arange does not return a valid result, so start from 1 45 | 46 | for i in iters: 47 | train_fold = np.arange(0, i + 1) 48 | test_fold = min(i + m, idx_max) 49 | # yield returns a value, but does not end our function, it will resume when the 50 | # next value is called for, running the next iteration of our for loop. 51 | yield [train_fold, test_fold] 52 | 53 | #When we reach return, our generator is exhausted. 54 | return 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /notebooks/solutions/scipy_normal_tests.py: -------------------------------------------------------------------------------- 1 | 2 | stats.normaltest(heights) 3 | 4 | stats.kstest(heights, 'norm') -------------------------------------------------------------------------------- /notebooks/solutions/simulation_ttest.py: -------------------------------------------------------------------------------- 1 | from math import floor, ceil 2 | import numpy as np 3 | import pandas as pd 4 | 5 | def run_experiment(dof): 6 | """Runs a single t-value experiment""" 7 | 8 | n1 = floor(dof/2) + 1 9 | n2 = ceil(dof/2) + 1 10 | 11 | assert(dof == n1 + n2 - 2) 12 | 13 | X1 = np.random.randn(n1) 14 | X2 = np.random.randn(n2) 15 | 16 | e1 = np.std(X1) / np.sqrt(n1) 17 | e2 = np.std(X2) / np.sqrt(n2) 18 | 19 | sed = np.sqrt(e1**2 + e2**2) 20 | 21 | t_stat = abs((np.mean(X1) - np.mean(X2)) / sed) 22 | return t_stat 23 | 24 | N_EXPERIMENTS = 10000 25 | dofs = [5, 10, 20, 50, 100] 26 | p_values = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5] 27 | 28 | results = {} 29 | 30 | for dof in dofs: 31 | results[dof] = {} 32 | values = [run_experiment(dof) for _ in range(N_EXPERIMENTS)] 33 | values.sort(reverse=True) # In place operation 34 | for p_value in p_values: 35 | n = int(N_EXPERIMENTS * p_value) 36 | results[dof][p_value] = values[n-1] 37 | 38 | results = pd.DataFrame.from_dict(results) 39 | print(results) 40 | 41 | # Check our results: 42 | from scipy.special import stdtrit 43 | 44 | true_results = {} 45 | for dof in dofs: 46 | true_results[dof] = {} 47 | for p_value in p_values: 48 | true_results[dof][p_value] = stdtrit(dof, 1 - p_value / 2) 49 | 50 | true_results = pd.DataFrame.from_dict(true_results) 51 | print(true_results) 52 | -------------------------------------------------------------------------------- /notebooks/solutions/stationarity.py: -------------------------------------------------------------------------------- 1 | 2 | # Solutions 3 | from statsmodels.tsa.stattools import kpss 4 | 5 | kpss_stat, p_value, lags, crit = kpss(X_stationary) 6 | 7 | p_value > 0.05, p_value # Accept hypothesis of stationarity 8 | 9 | kpss_stat, p_value, lags, crit = kpss(X_non_stationary) 10 | 11 | p_value > 0.05, p_value # Reject hypothesis of stationarity 12 | 13 | kpss_stat, p_value, lags, crit = kpss(X_AR1) 14 | 15 | p_value > 0.05, p_value # Reject hypothesis of stationarity 16 | 17 | from statsmodels.tsa.stattools import adfuller 18 | 19 | adf, p_value, *_ = adfuller(X_stationary) 20 | 21 | p_value < 0.05, p_value # Reject hypothesis of a unit root, which indicates stationary 22 | -------------------------------------------------------------------------------- /notebooks/solutions/statsmodels_formula_ols.py: -------------------------------------------------------------------------------- 1 | 2 | split_point = int(2 * len(X) / 3) 3 | data_train, data_test = data[:split_point], data[split_point:] 4 | 5 | 6 | import statsmodels.formula.api as smf 7 | est = smf.ols(formula='Inflation ~ InterestRate + AUDUSD', data=data_train).fit() # Adds the constant for us 8 | 9 | y_pred = est.predict(data_test) 10 | y_pred.name = "PredictedInflation" 11 | pd.concat([data_test["Inflation"], y_pred], axis=1).plot() -------------------------------------------------------------------------------- /notebooks/solutions/uniform.py: -------------------------------------------------------------------------------- 1 | #1 2 | 3 | distribution = stats.norm(0, 1) 4 | 5 | x_values = np.linspace(-3, 3, 1000) 6 | y = distribution.pdf(x_values) 7 | plt.plot(x_values, y) 8 | 9 | #2 10 | distribution = stats.uniform(-2, 4) 11 | 12 | x_values = np.linspace(-3, 3, 1000) 13 | y = distribution.pdf(x_values) 14 | plt.plot(x_values, y) 15 | print("The expected value for a uniform distribution is E[x] = (a + b) / 2") 16 | -------------------------------------------------------------------------------- /notebooks/solutions/white_noise_break.py: -------------------------------------------------------------------------------- 1 | 2 | # Mean not 0 3 | 4 | X = np.random.random(100) + 10 # Mean is about 10.5 5 | 6 | plt.plot(X) 7 | 8 | pd.plotting.autocorrelation_plot(X) 9 | 10 | # Variance not constant 11 | 12 | i = np.arange(100) 13 | X = np.random.random(len(i)) * i 14 | 15 | plt.plot(X) 16 | 17 | pd.plotting.autocorrelation_plot(X) 18 | 19 | # Lagged correlation 20 | X = [1] * 100 21 | for i in range(1, 100): 22 | X[i] = X[i-1] * np.random.random() * 2 23 | 24 | plt.plot(X) 25 | 26 | pd.plotting.autocorrelation_plot(X) 27 | -------------------------------------------------------------------------------- /notebooks/solutions/why_not_normal.py: -------------------------------------------------------------------------------- 1 | # Solution: the random data I chose was from a uniform distribution. qqplot tests for normally distributed errors 2 | -------------------------------------------------------------------------------- /notebooks/tools/check_headings.py: -------------------------------------------------------------------------------- 1 | import json 2 | from glob import glob 3 | 4 | filenames = glob("../*.ipynb") 5 | filenames = sorted(filenames) 6 | 7 | 8 | for filename in filenames: 9 | print("Filename:", filename) 10 | with open(filename) as inf: 11 | notebook = json.load(inf) 12 | new_cells = [] 13 | for cell in notebook['cells']: 14 | cell_type = cell['cell_type'] 15 | if cell_type == 'markdown': 16 | new_lines = [] 17 | for line in cell['source']: 18 | if line.strip().startswith("#"): 19 | if "exercise" in line.lower() or "question" in line.lower(): 20 | line = "#### " + line.replace("#", "").replace(":", "").strip() + "\n" 21 | else: 22 | if "Introduction" in line: 23 | line = "# " + line.replace("#", "").strip() + "\n" 24 | elif "Module " in line: 25 | line = "## " + line.replace("#", "").strip() + "\n" 26 | else: 27 | line = "### " + line.replace("#", "").strip() + "\n" 28 | print(" ", line.strip()) 29 | new_lines.append(line) 30 | 31 | cell['source'] = new_lines 32 | new_cells.append(cell) 33 | notebook['cells'] = new_cells 34 | with open(filename, 'w') as inf: 35 | json.dump(notebook, inf, indent=1) 36 | 37 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | altair 2 | vega_datasets 3 | vega 4 | matplotlib 5 | numpy 6 | scipy 7 | pandas 8 | jupyter 9 | notebook 10 | pytest 11 | statsmodels 12 | scikit-learn 13 | tensorflow 14 | tables 15 | quandl 16 | maxentropy 17 | arch 18 | 19 | --------------------------------------------------------------------------------