<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by John You on Medium]]></title>
        <description><![CDATA[Stories by John You on Medium]]></description>
        <link>https://medium.com/@johnswyou?source=rss-832499040d53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q6qHgE82Udu9EN6egXwmWg.jpeg</url>
            <title>Stories by John You on Medium</title>
            <link>https://medium.com/@johnswyou?source=rss-832499040d53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:34:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnswyou/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stock price prediction using Temporal Convolutional Networks]]></title>
            <link>https://medium.com/@johnswyou/stock-price-prediction-using-temporal-convolutional-networks-451a7f9164dd?source=rss-832499040d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/451a7f9164dd</guid>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[John You]]></dc:creator>
            <pubDate>Thu, 09 Nov 2023 02:04:40 GMT</pubDate>
            <atom:updated>2023-11-09T02:04:40.289Z</atom:updated>
            <content:encoded><![CDATA[<h4>A short tutorial using the darts Python library</h4><p>In this short article, I will apply the Temporal Convolutional Network (TCN) model to predict the stock price of Tesla 60 minutes ahead.</p><p>The TCN is a time series forecasting model that received a lot of attention when first introduced in the paper <a href="https://arxiv.org/abs/1803.01271">“An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling”</a> by Bai, Kolter, and Koltun. I suggest you take a look at that paper for technical details.</p><p>I will use the TCN implementation provided by the excellent <strong>darts</strong> Python library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5561f35b2aaf8b25360daa38f6941b59/href">https://medium.com/media/5561f35b2aaf8b25360daa38f6941b59/href</a></iframe><h3>Tesla stock price data</h3><p>To obtain stock price data for TSLA, I will utilize the <a href="https://www.alphavantage.co/">Alpha Vantage API</a>. The API is free to use (but has daily usage and rate limits). However, you can access premium API functionality if you purchase some Alpha Vantage Coin (AVC), which is a crypto asset that Alpha Vantage created. It’s a pretty good deal and allows you to access arguably one of the best financial data APIs available to lay folks like myself without breaking the bank.</p><p>NOTE: There is a <a href="https://pypi.org/project/alpha-vantage/">Python library</a> with functionality to fetch data from Alpha Vantage. However, since the Alpha Vantage API undergoes frequent changes, the classes and functions in the Python library often break. For this reason, I prefer to use the Alpha Vantage API by writing my own code to make requests.</p><p>The following is code to fetch data from the Alpha Vantage API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbafc29e37f4a7e531290f9484a4e19a/href">https://medium.com/media/bbafc29e37f4a7e531290f9484a4e19a/href</a></iframe><p>We build our data set, which will be minute-level data (including extended hours) from January of 2022 to the end of September 2023 (about a year and a half worth of data).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81c75659cf18a1d8c962a601c2560127/href">https://medium.com/media/81c75659cf18a1d8c962a601c2560127/href</a></iframe><p>Here’s what <strong>tsla_df </strong>looks like so far:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1397acf4a2c0a7b51b7048c331e05a74/href">https://medium.com/media/1397acf4a2c0a7b51b7048c331e05a74/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5-pdp-TfS1hUbtQuP5VBA.png" /></figure><p>Next, I will add all missing timestamps (for timestamps where no trading activity occurred), and then use a forward fill strategy to fill these newly added timestamps (forward fill just means using the most recently observed value to fill a missing value).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f414f069b68132546c0f5054f9abcb4f/href">https://medium.com/media/f414f069b68132546c0f5054f9abcb4f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJZ15Fv2CkqZMA3P3zACgw.png" /></figure><p>Here’s what the minute-level price series looks like for TSLA (each price in the series is the highest price during a given minute):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/867cdee45a08c26fffc084b747d1630c/href">https://medium.com/media/867cdee45a08c26fffc084b747d1630c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*BAWIApXlj-tkHcFxHfxerA.png" /></figure><h3>TCN price forecasting using darts</h3><p>For simplicity, I will test the Temporal Convolutional Network model using a training and evaluation workflow that is erroneous. The workflow is erroneous because we will scale both the train and evaluation sets in one go. This leads to data leakage from the evaluation set into the training set. This leads to overly optimistic evaluation metrics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f09b23d0386f04e9e9b68fac4a80888/href">https://medium.com/media/9f09b23d0386f04e9e9b68fac4a80888/href</a></iframe><p>For me, the output of the above code looked as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iELwE1SolaJp1YktF7A5VQ.png" /></figure><p>The following code evaluates the model using “out of sample” observations (again, not truly out of sample due to our erroneous data scaling strategy).</p><p>The following code evaluates the trained TCN model in a “rolling” fashion (i.e., as you would make forecasts in practice). You can find more details in the <a href="https://unit8co.github.io/darts/generated_api/darts.models.forecasting.tcn_model.html?highlight=tcn#module-darts.models.forecasting.tcn_model">darts documentation</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64aad4bb68db6040f342957fe593cab9/href">https://medium.com/media/64aad4bb68db6040f342957fe593cab9/href</a></iframe><p>Finally, we plot both the observed price series and the 60-minute ahead forecasts. Empirically, the forecasts seem reasonable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/553c7306ac30988464750b1f5634f40a/href">https://medium.com/media/553c7306ac30988464750b1f5634f40a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*01uBkqvTFmxzuaVY2mE9Dg.png" /></figure><h3>Conclusion</h3><p>My intention in this article was not to build a performant stock price forecasting model but to show you how to use the <strong>darts</strong> library to build a powerful time-series forecasting model with many options available to the user for customization.</p><p>Hopefully, you were able to get something out of this article.</p><p>John</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=451a7f9164dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Random variable or observation?]]></title>
            <link>https://medium.com/@johnswyou/random-variable-or-observation-5aaddb7bc4a5?source=rss-832499040d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aaddb7bc4a5</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[understanding]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[John You]]></dc:creator>
            <pubDate>Sun, 22 Oct 2023 21:55:20 GMT</pubDate>
            <atom:updated>2023-10-22T22:06:00.265Z</atom:updated>
            <content:encoded><![CDATA[<h4>Knowing the difference is a prerequisite for understanding statistics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Z1uioxljs3KEaaJ" /><figcaption>Photo by <a href="https://unsplash.com/@riverse?utm_source=medium&amp;utm_medium=referral">DEAR</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In statistics, you will deal with two distinct scenarios:</p><ol><li>Calculations involving random variables</li><li>Calculations involving <em>realizations</em> of random variables</li></ol><p>Understanding which of the two situations you’re dealing with is absolutely essential. Typically, random variables are denoted using uppercase letters (e.g., <em>X</em>) and realizations (or observations) are denoted using lowercase letters (e.g., x).</p><p>In this article, I will focus on continuous probability distributions.</p><h3>Preliminaries</h3><p>A random variable X can be thought of as a “random number generator”, and you won’t know for sure what number X will generate. However, after you generate a number (called a realization), you have a fixed observation. This observation/realization is denoted by lowercase x.</p><p>A random variable will generate random numbers based on a probability distribution (for instance, the normal distribution).</p><p>Continuous probability distributions (i.e., probability density functions) are mathematical functions that tell you <strong>with what probability any number in a certain range will be observed</strong>.</p><p>The probability that X will generate a number between a and b is denoted by P(a &lt; X &lt; b). This probability can be found directly by integrating the probability density function between the bounds a and b.</p><h3>Sampling distributions</h3><p>When you take the sample mean (i.e., average) of an <strong>observed</strong> random sample, you get one number: the sample mean.</p><p>However, a different way to think about the sample mean is seeing the sample mean as the average of n independent and identically distributed (iid) random variables X_1, X_2, …, X_n. Each data point in your observed sample of n numbers was a realization from each of these n random variables. In other words, the first sample x_1 in your observed data set was an observation from X_1, the second observed sample x_2 in your data set was an observation from X_2, and so on.</p><p>Since each X_1, X_2, …, X_n is a random variable, <strong>the average of these random variables will also be a random variable</strong>. When you observe a random sample (these are fixed numbers once they are observed) and find its average, you are effectively taking a <strong>realization</strong> from the sample mean random variable (make sense?)</p><p>What I just described applies also to the sample standard deviation, and in general, to any statistic that you wish to construct.</p><p><strong>NEVER forget this</strong>: You have to understand 1) when you’re working with a random variable, and 2) when you’re working with a <em>realization</em> from that random variable. Once you realize a value from a random variable, that value is fixed. But a random variable does not have a fixed value; it is more like a random number generator that has not yet produced a realization; it’s value can only be known probabilistically. Such probabilities can be calculated using the probability distribution that governs the random variable.</p><h3>Example: The t-distribution</h3><p>The t-distribution is the distribution that governs the t-statistic. The t-statistic is a random variable that is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*h6zFT6iapTpNwpPc5EV8Og.png" /><figcaption>The t-statistic random variable</figcaption></figure><p>The t-statistic arises when you normalize the sample mean random variable by subtracting the expected value of the sample mean random variable and dividing that difference by the standard deviation of the sample mean random variable (usually called the standard error of the sample mean random variable).</p><p>In order for the t-statistic random variable to be distributed according to a t-distribution, the random variables X_1, X_2, …, X_n that are used to produce X_bar and S MUST be iid normal random variables.</p><p>When you take an observed sample x_1, x_2, …, x_n (note the lower case here) from a set of normal random variables (i.e., x_1 is a realization from X_1, x_2 is a realization from X_2, and so on) and compute the t-statistic using that observed (fixed) sample, you are getting a realization from the t-statistic random variable.</p><h3>Example Problem</h3><blockquote>Suppose we have 15 iid observations from a normal distribution and want to find a value k such that the probability that a realization from the t-statistic random variable lies between k and -1.761 is 0.045. Assume the true mean of the normal distribution is known.</blockquote><p>Our random sample size is 15, which means we have 15 realizations from 15 iid normal random variables. This means:</p><p>x_1 is from X_1</p><p>x_2 is from X_2</p><p>…</p><p>x_15 is from X_15.</p><p>If we compute the t-statistic using the random variables (X_1, X_2, …, X_15), we will get the t-statistic random variable.</p><p>First, note that t_0.05=-1.761.</p><p>To find k, you just look up the value of t_0.005 in the t-tables and conclude with: k=-2.977. Just make sure to use the t-distribution with the correct number of degrees of freedom, which can be determined based on the sample size (n=15 in our case). See the illustration below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djECuwK7UxcPxOpUij03-A.png" /></figure><p>Note that to solve this problem, we did not even have to know the values of the observations x_1, x_2, …, x_15.</p><h3>Conclusion</h3><p>The important distinction between a random variable and a realization from a random variable was not made clear to me when I first learned statistics. I hope this article may be of use to anyone either learning statistics for the first time or those of you who never really understood statistics the first time you learned the subject.</p><p>John</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aaddb7bc4a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why the t-test is robust to normality]]></title>
            <link>https://medium.com/@johnswyou/why-the-t-test-is-robust-to-normality-4fdd26334fdd?source=rss-832499040d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fdd26334fdd</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[John You]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 15:58:41 GMT</pubDate>
            <atom:updated>2023-10-14T15:58:41.552Z</atom:updated>
            <content:encoded><![CDATA[<h4>I never got a straight answer to this question in statistics class.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EIEnO5M9djriBT_8" /><figcaption>Photo by <a href="https://unsplash.com/@jdjohnston?utm_source=medium&amp;utm_medium=referral">Jessica Johnston</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Student’s t-test, usually just called “t-test”, was invented by William Sealy Gosset while working for the brewery Guinness. Presumably, he was using the t-test to determine the quality of barley. At the time, Guinness didn’t want employees to use their real names when publishing papers, so Gosset used the pseudonym “Student” to publish his work. Interestingly, it was Ronald Fisher (the father of modern statistics) who popularized the term “Student’s t-distribution”. In an alternate world, we would call the t-test, “Gosset’s t-test”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*fDhJEZXcePZY4eQb98HuDQ.png" /><figcaption>Gosset’s famous paper from which the name “Student” originated.</figcaption></figure><p>If you’ve ever taken an introductory statistics class before, you will likely have heard that the t-test is “robust to normality when the number of samples is large”. But what exactly does this mean? And why is this true? This article is my attempt to answer these questions.</p><p>I will assume you already know about the t-test and came here because of a burning curiosity to know why the t-test works for large samples even when the data were generated from a non-normal distribution.</p><h3>The t-test for data generated by a normal distribution</h3><p>When data can be reasonably assumed to have been generated by a normal distribution (which is what is meant when we say the “normality assumption”), the computed t-statistic will be a realization from the t-distribution, and the t-test will work for small, moderate and large sample sizes. This is because the definition of the t-distribution follows from assuming that observed data were generated by a normal distribution.</p><p>Viewing the t-statistic as a random variable and not a realization from the t-distribution, the t-statistic depends on two random variables: the sample mean and the sample variance.</p><ol><li>The sample mean will have a normally distributed sampling distribution, and</li><li>the sample variance will follow a chi-square sampling distribution.</li></ol><p>When both (1) and (2) above are satisfied, the t-statistic will follow the t-distribution exactly. These two conditions are met when data is generated by a normal distribution. There may be other esoteric cases when (1) and (2) are met (in which case the t-statistic will follow a t-distribution exactly), but such cases are rare if not impossible. In this article, I will assume that the the t-statistic can only follow a t-distribution exactly when the data-generating distribution (i.e., the distribution of X) is normal.</p><h3>The t-test for data generated by a non-normal distribution</h3><p>When data cannot be reasonably assumed to have been generated by a normal distribution, the t-statistic will not follow the t-distribution and hence the t-test will fail for small and moderately sized data samples.</p><p>When data is not generated by a normal distribution, the sampling distribution of the sample mean and sample variance will NOT be normal and chi-square, respectively. This means that the t-statistic constructed from data generated by a non-normal distribution will NOT be a realization from a t-distribution, but rather, some other esoteric distribution whose form we generally will be unable to determine.</p><p>However, we are not completely out of luck because the t-test can perform reasonably well (in terms of Type 1 Error) when the sample size is large, and theoretically will perform better as the sample size gets larger.</p><p>The “robustness” of the t-test to data generated by a non-normal distribution (when the sample size is large) can be explained by two statistical truths:</p><ol><li>The central limit theorem (CLT)</li><li>The law of large numbers</li></ol><p>Consider the central limit theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*UZzjsBqfPkSahRT_mWBo2A.png" /><figcaption>The central limit theorem</figcaption></figure><p>Where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*m6Ot1_NFwWf11gXNfDCxhw.png" /><figcaption>Expected value of the data-generating distribution</figcaption></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*4IClBqD-62ktgAKnxXNirQ.png" /><figcaption>Variance of the data-generating distribution</figcaption></figure><p>The small “d” above the arrow in the CLT formula stands for “convergence in distribution” (see more about this technicality <a href="https://www.probabilitycourse.com/chapter7/7_2_4_convergence_in_distribution.php#:~:text=Convergence%20in%20distribution%20is%20in,discussed%20the%20central%20limit%20theorem.">here</a>). “n” is the sample size.</p><p>Next, consider the <a href="https://en.wikipedia.org/wiki/Law_of_large_numbers">law of large numbers</a>, which says that the sample variance (seen as a random variable) <a href="https://www.probabilitycourse.com/chapter7/7_2_5_convergence_in_probability.php">converges in probability</a> to the true variance of the data generating distribution (i.e., the distribution of X):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*oVgifai_tOekmvYLsRQOVQ.png" /></figure><p>Following from these two results, we arrive at the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*A03rnYX8-9ZH8AScBwrMeA.png" /><figcaption>The t-statistic converges in distribution to the standard normal</figcaption></figure><p>This is a profound result, which states that the t-statistic (when viewed as a random variable) converges in distribution to the standard normal distribution.</p><p>The key practical implication of this result is that the t-statistic (when viewed as a random variable) <strong>approximately </strong>follows a standard normal distribution <strong>when the sample size is large</strong>, <strong>even when the data-generating distribution is not normal</strong>. Given that the standard normal distribution approximates the t-distribution when the sample size is large, we arrive at our conclusion: the t-test is robust to normality when the sample size is large.</p><h3>Summary</h3><p><strong>When your data can reasonably be assumed to have been generated from a normal distribution</strong> (which can be assessed using tools such as the QQ-plot):</p><ul><li>The t-test will work for small, moderate, and large sample sizes</li></ul><p><strong>When your data CANNOT be reasonably assumed to have been generated from a normal distribution</strong>:</p><ul><li>The t-test will not work for small and moderate sample sizes</li><li>The t-test will work for large sample sizes, and you can even swap out the t-distribution for the standard normal distribution (in fact, the standard normal distribution is the preferred and technically correct distribution to use when the sample size is large)</li></ul><p>Determining what constitutes a “small”, “moderate” or “large” sample size is more of an art than a science. For data that seems to have been generated from a highly non-normal distribution, you can expect to require more samples until you are in the “large” sample size zone compared to data that appears to have been generated from a unimodal and symmetric distribution.</p><p>I hope this article provided further depth to your understanding of the Student’s t-test.</p><p>John</p><h3>References</h3><p>Student. (1908). The probable error of a mean. <em>Biometrika</em>, <em>6</em>(1), 1. <a href="https://doi.org/10.2307/2331554">https://doi.org/10.2307/2331554</a></p><p>Hansen, B. (2022). <em>Probability and Statistics for Economists</em>. Princeton University Press.</p><p>Britannica, T. Editors of Encyclopaedia (2023, October 10). Student’s t-test. Encyclopedia Britannica. <a href="https://www.britannica.com/science/Students-t-test">https://www.britannica.com/science/Students-t-test</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fdd26334fdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We need to talk about charter schools]]></title>
            <link>https://medium.com/@johnswyou/we-need-to-talk-about-charter-schools-5c2cc9af92b8?source=rss-832499040d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c2cc9af92b8</guid>
            <category><![CDATA[charter-schools]]></category>
            <category><![CDATA[education-reform]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[John You]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 20:33:05 GMT</pubDate>
            <atom:updated>2023-10-10T20:56:36.822Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reflecting on Thomas Sowell’s insights on charter schools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kiL8U9b0HF9vZBoz" /><figcaption>Photo by <a href="https://unsplash.com/@renebbernal?utm_source=medium&amp;utm_medium=referral">Rene Bernal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A core tenet motivating this article is that all children and youth, regardless of their inherited socioeconomic and racial background, should be provided with equal educational opportunities. This should be the responsibility of the state, since education, especially for children from low-income families, is the most important enabler for living a civil and fulfilling life. The prosperity of a nation rests on its ability to foster citizens with high moral character, strong work ethic, and low crime involvement. Equal access to education contributes to all of these and hence should be a central concern of the state. Unfortunately, the United States, the pre-eminent global superpower of our era, often fails to provide education of equal quality, irrespective of race or class, to those who seek it. Later in this article, I present a brief case study that demonstrates the failure of the US public school system’s ability to live up to the US Education Department’s stated mission “to promote student achievement and preparation for global competitiveness by fostering educational excellence and ensuring equal access”.</p><p>Rising nations tend to foster a strong educational environment, whereas declining nations tend to do the opposite. The American educational trends observable in recent times have far-reaching implications for its position on the world stage. Education is no light matter.</p><h4>Differences in Educational Attainment and Income</h4><p>The causes of deviations in educational attainment and income among different racial groups are a highly contested and hotly debated topic. My goal in this subsection is simply to illustrate that such differences exist, without speculating on what might cause such differences.</p><p>The stratification of the US population into racial groups for analysis is useful for many reasons. A key reason for dividing up the population by race is that it illuminates (1) the interwovenness between socioeconomic status (i.e., “class”) and race, and (2) a clear separation among the classes (which implies marked socioeconomic differences between different racial groups).</p><p>To set the stage for illustrating group differences in educational attainment and income, the following chart demonstrates the relationship between educational attainment, median weekly earnings, and rate of unemployment for the year 2022.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TebvMrMwFdQBttteXTVAPA.png" /><figcaption>Relationship between educational attainment, earnings, and unemployment.</figcaption></figure><p>The next chart compares the educational attainment of four major racial groups in the US (Asian, Black, Hispanic, White), with educational attainment measured by the proportion of each racial group that possesses a Bachelor’s degree. The darker shades indicate higher educational attainment, while lighter shades indicate lower educational attainment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whI3bos0_e4kt_2ci_kyuA.png" /><figcaption>Percentage of Population Aged 25 Years and Over With a Bachelor’s Degree or Higher: 2015–2019, Source: United States Census Bureau</figcaption></figure><p>Given the two charts presented, one might expect there to be marked differences in income among different racial groups. And this is exactly what existing data suggests. For instance, the following chart from the US Census Bureau plots historical (inflation-adjusted) median household income for different racial groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSrZp9n-92ZTuEm_A3NMRQ.png" /></figure><p>From the data, it is evident that addressing poverty by, in part, raising educational outcomes through policy in the US is intimately linked with addressing the educational outcomes of Black and Hispanic youth.</p><p>The prevailing rhetoric seems to be that some new revolutionary and exotic policy is needed to address the educational attainment gap between the White/Asian group and the Black/Hispanic group. However, a key insight given to us by Thomas Sowell, a renowned public intellectual and Senior Fellow at Stanford’s Hoover Institution, is that we need not look to such highly speculative and often misdirected solutions, but rather to study institutions that have already fostered (and continue to foster) educational excellence among the Black/Hispanic group.</p><h4>The Rise of Alternative Schooling for Low-Income Youth</h4><p>In a landmark 1954 ruling (Brown v. Board of Education) by the Supreme Court of the United States (SCOTUS), Chief Justice Earl Warren declared racially segregated schools to be “inherently unequal”. Hence, racially segregated schools became the prevailing explanation for low achievement in racially segregated all-black schools. The great irony was that Dunbar High School, an all-black high school that sent a higher proportion of its graduates to college than any other all-white high school in the city, with graduates that included the first black general (Benjamin O. David), the first black cabinet member (Robert C. Weaver), the discoverer of blood plasma (Charles Drew), and the first black senator (Edward W. Brooke), was only about a mile away from the Supreme Court where Earl Warren’s historic decision was made.</p><p>Had the educational practices of highly performant all-black high schools such as Dunbar High School been studied and scaled instead of implementing often destructive and politically motivated policies that were often misguided and/or disregarded hard facts, history may have turned out differently.</p><p>A logical consequence of the landmark Brown v. Board of Education ruling was the implementation of mostly vain attempts at racial integration such as desegregation busing where black students were bused to schools within or outside their local school district to promote racial diversity in hopes of improving the educational outcomes of black students.</p><p>Driven largely by the failure of integration attempts to bring about meaningful improvements to the educational achievements of black students, a variety of schemes to enable low-income parents to send their children to alternate schools when the public school system failed to meet expectations began to gain momentum. High-income parents already had such options available, primarily by means of enrolling their children in private schools. Schemes that extended low-income parents’ choice of schooling included tuition-covering vouchers at low-cost private schools and tuition tax credits. However, about 40 years after the landmark Brown v. Board of Education ruling, one of the most successful alternate forms of schooling, known as “charter schools”, began to emerge.</p><h4>Charter Schools</h4><p>Charter schools are special public schools that are not constrained by many of the stringent rules governing regular public schools. Funding of charter schools comes from taxpayer dollars but can be revoked if the educational outcomes of its students fail to meet various educational criteria. This incentive structure means that charter schools only receive money if they can demonstrate positive educational outcomes for their students. This “outcome first” operational mode of charter schools starkly contrasts the operational mode of regular schools, which has come to put heavy emphasis on what “goes in” to teaching (and the behemoth bureaucracy surrounding it), even if the educational outcomes are not correlated to such efforts.</p><p>Charter schools operate under a specific charter or contract, which grants them greater autonomy in certain areas compared to regular public schools. They have more freedom to innovate in areas such as curriculum, teaching methods, staffing, and operations. Charter schools can pursue a wide variety of educational approaches, from project-based learning to classical education to schools focused on arts, STEM, or language immersion. In return for this autonomy, charter schools are held accountable for achieving certain performance outcomes, as outlined in their charter. Their charter outlines specific goals and benchmarks. If a charter school fails to meet these standards or runs into serious operational issues, its authorizing entity can choose not to renew the school’s charter, effectively closing the school.</p><p>Charter schools are established based on a contract or “charter” between the school’s organizers and an authorizing entity, which might be a state education agency, a local school district, or another designated entity, depending on state laws.</p><p>Like all public schools, charter schools are tuition-free and open to any student who wishes to attend. If there are more applicants than available slots, admission is typically determined by a lottery system. In the United States, there are long lines of students waiting for admission into charter schools. In New York alone, there are over 50,000 such students on waiting lists.</p><p>As with regular public schools, charter schools receive public funds (i.e., taxpayer dollars) based on student enrollment. However, the amount and method of funding can vary by state and locality. Some charter schools also secure additional funding through grants, donations, or other sources. As will be illustrated later, charter schools face constant hostility from the much larger public school system, teachers unions, politicians, and countless other actors that try to prevent them from securing funds and obtaining schooling space, in an attempt to to slow their ascendence.</p><h4>Charter Schools and Educational Outcomes of Low-Income Students</h4><p>Charter schools are disproportionally located in low-income neighborhoods, and hence are most relevant to those students who come from low-income families. Although a commonly quoted statistic is that charter schools, on average, perform as well as regular public schools, such a statement is the result of an “apples to oranges” comparison, since the population of regular public school students includes those from affluent families and groups that have historically outperformed the national average academic performance, thereby raising the average performance of regular public school students. A fair comparison can only be facilitated by comparing students from similar socioeconomic and racial backgrounds. As will be shown in the case study that follows, <strong>controlling for socioeconomic status and race reveals that charter schools, on average, vastly outperform regular public schools in student performance</strong>.</p><p>In fact, if it is true that the average performance of students in charter schools rivals that of students in regular public schools, this would indicate a great achievement on the part of charter schools, since its student demographic is disproportionally comprised of those that have historically sat on the lower end of the regular public school performance distribution.</p><p>Not all charter schools are successful, but the same can be said for regular public schools. On average, however, a careful analysis of existing data about the educational outcomes of students from charter school reveal that they achieve far better results compared to neighboring regular public schools. Some charter schools even surpass the performance of not only neighboring public schools but also most schools in surrounding affluent public schools.</p><h4>Case Study: New York State</h4><p>To illustrate the positive performance gap between charter schools and regular public schools, I took data from the appendix of Dr. Thomas Sowell’s book “Charter Schools and Their Enemies” and constructed a variety of summarizing charts. The data originally comes from the New York State Education Department and consists of 95 schools in total; 23 charter schools and 72 regular public schools in New York City. To facilitate an “apples to apples” comparison, data was taken for charter schools that house both the charter school and one or more public schools in the same building. This was done to control for both racial and socioeconomic demographics since students in the same building can be reasonably expected to reside in similar neighborhoods, and hence exhibit similar racial and socioeconomic backgrounds.</p><p>The vast majority of students in both the charter and regular public schools were either Black or Hispanic, and most were classified as being “Economically Disadvantaged” by the New York State Education Department.</p><p>Student outcome was measured using two different statewide tests: the New York State English Language Arts Test (ELA), and the New York State Mathematics Test (MATH). Four scores are possible on these two tests:</p><p><strong>Level 1</strong>: Well Below Proficient</p><p><strong>Level 2</strong>: Below Proficient</p><p><strong>Level 3</strong>: Proficient</p><p><strong>Level 4</strong>: Above Proficient</p><p>Level 3 is the key threshold for predicting future academic success since education has a compounding effect; what you learn in succeeding years depends on what you learn in the present year. It is thus critical for students to reach the Level 3 threshold or above in their early years to prepare them for success in later years.</p><p>Results from these two tests for the 2017–2018 academic year are shown below. First, the New York State English Language Arts Tests (grades 3 to 8):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvM5JToiQU-AVTWU2tfIpw.png" /><figcaption>NY State English Language Arts Test Results, Source: New York State Education Department</figcaption></figure><p>Next, the New York State Mathematics Test (grades 3 to 8):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFfPQDISwYXtOKrSVaBWOQ.png" /><figcaption>NY State Mathematics Test Results, Source: New York State Education Department</figcaption></figure><p>In all 12 charts shown above, charter schools systematically deliver superior outcomes on both the ELA and MATH state-wide tests compared to their public school counterparts. Charter schools consistently demonstrate a greater proportion of students that score in the level 3 (proficient) and level 4 (above proficient) categories compared to their public school counterparts, and repeatedly show a lower proportion of students that score in the level 1 (well below proficient) and level 2 (below proficient) categories compared to their public school counterparts.</p><p>Further analysis (not shown here for brevity) reveals that the results are statistically significant.</p><h4>Enemies</h4><p>Given the success of charter schools in raising academic scores in areas of New York (and elsewhere) that have academically underachieved for generations, why might some be so adamantly against the rise and spread of charter schools? A glimpse into the answer might be had by following the money.</p><p>In New York City, where the average per-student expenditure exceeds $20,000 USD per year, the more than 50,000 students on charter school waiting lists represent a sum of more than a billion dollars that could be lost by the public school system. And that is the loss of the public school system for just one city in one state. Growth in regular public school enrollment from 2001 to 2016 was a mere 1%, while growth in charter school enrollment during the same period was 571%. With the unrestricted growth of charter schools, the public school system would risk rapidly growing financial losses. This would inevitably lead to the need for fewer teachers in regular public schools, which leads to another pain point for the public school system: declining union dues.</p><p>Union dues are fees that educators and other school employees pay to belong to their labor union. The largest of these unions are the National Education Association (NEA) and the American Federation of Teachers (AFT). Union dues fund union operations, and are used to facilitate activities such as:</p><ul><li>negotiating contracts (collective bargaining agreements) with school districts</li><li>representing members in grievance procedures</li><li>providing legal representation</li><li>engaging in lobbying efforts</li><li>supporting political activities</li></ul><p>Most teachers in the regular public school system are unionized, whereas most charter school teachers are not.</p><p>A clear narrative that arises is that the spread of successful charter schools presents an existential threat to the existing public school system and must therefore be subdued to preserve the status quo, even if this comes at the expense of providing quality education to low-income children and youth, for whom education is their best hope for escaping poverty.</p><p>Across many cities, there are many multiples of the number of existing charter school students who are on waiting lists to get into charter schools. Charter schools are often housed in the same buildings as existing regular public schools, and hence are subject to the whims of local school district authorities. There have been numerous cases of charter schools being blocked by teachers’ unions from using vacant school spaces that have been empty for years and engaging in the blocking of sales and leasing of unused school space to charter schools. Teachers’ unions have also attempted to put legal limits on the number of charter schools that can operate, with some states already having implemented such arbitrary limits. Furthermore, teacher’s unions have advocated for barring charter schools’ right to appeal adverse decisions by local school district authorities. As Thomas Sowell remarks half comedically:</p><blockquote>“Murderers convicted in the court of law have the right to appeal, but apparently charter schools should not.”</blockquote><blockquote>- Thomas Sowell</blockquote><p>An honest encapsulation of the hidden motives of teacher’s unions was provided by the president of the AFT between 1974 and 1997:</p><blockquote>“When school children start paying union dues, that’s when I’ll start representing the interests of school children.”</blockquote><blockquote>- Albert Shanker</blockquote><p>On the political front, there has been heavy opposition and attempts to kill charter schools by politicians funded by teacher’s unions. That is a story far too involved to include in this article, but I highly recommend looking into the clashes between Success Academy Charter Schools founder and CEO Eva Moskowitz and former mayor of New York City, Bill de Blasio. Thomas Sowell provides a brief yet vivid account of their clash in his book “Charter Schools and Their Enemies”.</p><h4>The Future</h4><blockquote>“Charter schools are like many education reforms; they have broad but shallow support among a majority of the population, and intense but narrow opposition from teachers’ unions and their allies.”</blockquote><blockquote>- David Osborne</blockquote><p>As Thomas Sowell illustrates in the final chapter of his book “Charter Schools and Their Enemies”, the plane pioneered by the Wright brothers had a far shorter wingspan and an even less impressive range than a modern Boeing 747. Nonetheless, their experiment proved the science of flight and the feasibility of engineering aircraft that would revolutionize travel. Using this analogy, Thomas Sowell drives home the point that charter schools have illuminated a way forward to improve the educational outcomes of groups that have historically underachieved the national average academic performance, which has wide-ranging implications for poverty, crime, and the prosperity of the nation. Charter schools have demonstrated that low achievement among certain groups does not have to be a fate-bound reality via notions such as genetic determinism, which only helps rid existing public schools of accountability for educational outcomes.</p><p>The future of charter schools appears to be uncertain at present. With many states, including many blue states such as California, that seemingly oppose the proliferation of charter schools (as is made clear by legislation being passed regarding charter schools), only time will tell how events unfold. I will not speculate on what may be to come, but rather, hope that more dialogue and debates are had in the public sphere regarding charter schools, making sure to leverage hard data and a thoughtful evaluation of the motivations of different actors, the nature of what constitutes quality education, and the differing circumstances of children and youth from varying backgrounds.</p><p>Thanks for reading,</p><p>John</p><h3>References</h3><p>Dalio, R. (2021). <em>The Changing World Order</em>. Simon &amp; Schuster.</p><p>Sowell, T. (2020). <em>Charter Schools and Their Enemies</em>. Basic Books.</p><p>Sowell, T. (1974). <em>Black Excellence: The Case of Dunbar High School</em>. Public Interest.</p><p>Sowell, T. (1976). <em>Patterns of Black Excellence</em>. Public Interest.</p><p>Bowdler, J., &amp; Harris, B. (2022, July 21). <em>Racial inequality in the United States</em>. U.S. Department of the Treasury. <a href="https://home.treasury.gov/news/featured-stories/racial-inequality-in-the-united-states">https://home.treasury.gov/news/featured-stories/racial-inequality-in-the-united-states</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c2cc9af92b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What They Didn’t Teach You In Statistics Class]]></title>
            <link>https://medium.com/@johnswyou/what-they-didnt-teach-you-in-statistics-class-22866a361cec?source=rss-832499040d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/22866a361cec</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[theory]]></category>
            <dc:creator><![CDATA[John You]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 18:24:25 GMT</pubDate>
            <atom:updated>2023-04-24T15:00:38.464Z</atom:updated>
            <content:encoded><![CDATA[<h4>Parametric statistics uses models, and models are not real</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XwY72N8Kf-2QW6m-" /><figcaption>Photo by <a href="https://unsplash.com/@svetacreative?utm_source=medium&amp;utm_medium=referral">Sveta Fedarava</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Statistics is instrumental to our understanding of the world. It is a bedrock of science that leads to technological innovations and subsequent economic improvements (which could not be measured without statistics). Statistics is foundational to artificial intelligence, the operations of central banks, and public health policy design; all very relevant topics of the times.</p><p>It is also, in my view, the least well-understood math discipline among those primed in mathematics beyond the high school level.</p><p>I believe there are three big drivers behind the widespread misunderstandings (or lack of understanding thereof) of statistics:</p><ol><li><strong>We are not used to thinking of “randomness” in a principled way.</strong> Most mathematical education up until the end of high school focuses on deterministic mathematics such as algebra and calculus.</li><li><strong>The foundations of statistics</strong> (which, honestly, borders on being philosophical) <strong>are rarely addressed in statistics courses</strong> but are necessary to know for a full understanding of the basics. Said differently, <strong>statistics is not often taught from first principles</strong>.</li><li><strong>Statistics requires keen attention to detail</strong>. Capital <em>X</em> and lowercase <em>x</em> refer to two very different things, and it doesn’t help that the two are often indistinguishable in lectures, where instructors write on a board by hand. Also, certain words in statistics have very specific meanings, and it does not help that statistical statements often switch context back and forth from “statistics speak” to plain English, effectively making the reader see-saw from taking a word to mean one thing in one context, to meaning an entirely different thing in another context, all without any sort of warning. To be frank, written natural language is not the most compatible (in terms of clarity of communication) with statistics. Written language (specifically English) is often imprecise, whereas mathematics can be used to make very precise statements.</li></ol><p>If I were to add a fourth point, it would be that educators may not always be prepared for the task of teaching statistics; either due to a lack of deep understanding of statistics themselves, a lack of time to work on their pedagogy, or in the worst case, a lack of care and effort.</p><p>Now that we have listed out what I think are three major problems that drive statistical illiteracy; let’s zoom in on the first two. The third driver should be easier to address once you get a handle on the first two drivers. After that, it’s just practice and focus.</p><p>To really understand statistics, you need to read statistics texts like you would read a love letter. Every word and its meaning should be assessed and understood within the context of the words surrounding it. Try to categorize thoughts, stitch together the flow of ideas, and infer what the author had in mind when they were writing. Learning by reading is a dance between you and the author, albeit blocked by a glass wall that separates the two of you by time and space.</p><p><strong>Note</strong>: I have scattered digressions throughout the article. Feel free to skip them. They take the following form:</p><blockquote><strong>Aside</strong>: This is a digression.</blockquote><h3>Thinking of Randomness In a Principled Way</h3><p>What does “random” mean? <strong>It means we cannot know for sure what the outcome of an event will be prior to the event occurring</strong>. For example, if I throw a die onto the ground, I do not know which face will come up when the die comes to rest. Hence, the event “die toss” has an unknown outcome, which is “face of die that comes up when die comes to rest”. Of course, the outcome is only unknown prior to the event occurring and the outcome being observed. Once the event occurs and the outcome is observed, the outcome is fixed and written into the books of history.</p><p>Many events in life can be seen through the lens of randomness. What the closing price of AAPL is tomorrow (assuming tomorrow is a trading day) is a random event. Whether the Federal Reserve will raise interest rates next quarter is a random event. Whether Justin Bieber will perform in Montreal (Canada) next August is a random event. You get the idea. All of these events have unknown or uncertain outcomes prior to them coming to pass. Even if Justin Bieber had an event scheduled for next year in Montreal, it is possible that his show gets cancelled the night before due to unforeseen circumstances. You won’t know for sure until his show happens (or doesn’t happen). After random events come to pass, the outcome of each event is forged into history.</p><p>In statistics, the outcome of a random event that has not yet occurred is denoted by <em>X. </em>Note the upper case! We call <em>X</em> a <strong>random variable</strong>. Once the event has occurred and the outcome has been observed and sealed into history, we denote the fixed observed outcome by <em>x</em>. Note the lowercase! We call <em>x</em> a <strong>realization</strong> of <em>X</em>.</p><blockquote><strong>Aside</strong>: It is useful to think about the “lifetime” of a random variable <em>X</em>. For example, if <em>X</em> denotes the next trading day’s closing price of AAPL, then the lifetime of <em>X</em> must clearly be however long AAPL remains listed on a public stock exchange. If Apple ever gets delisted for any reason, the event “the next trading day’s closing price of AAPL” dissolves into an impossibility (since there won’t be a closing price for AAPL at the end of the next trading day) and the lifetime of <em>X</em> may be said to have been “spent”.</blockquote><p>How might we use symbols to communicate the situation where multiple dice are thrown to see which face each die comes to rest on? Easy. Denote the unknown outcome of each die using a subscript:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*OJs6-43hOsk-fdNuMB2qhw.png" /></figure><p>We call the above a <strong>random sample</strong>. Technically, a random variable can also be called a random sample, although it is more common to refer to a sole random variable as a “random variable”.</p><p>Once the dice have been thrown and they all have come to rest, the value of each die is recorded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*PM4q383gJRQHpMak05iabA.png" /></figure><p>We call the above a <strong>realization of a random sample</strong>. The above is a realization because it is just one possible set of outcomes that happened to be observed/realized. If we picked up all <em>n</em> dice and threw them to the ground and waited for them to come to rest again, we would most likely get a different set of outcomes (i.e., another realization).</p><h3>The Foundations of Statistics</h3><p>There are two important ideas that need to be understood to grasp statistics:</p><ol><li>The idea of a data-generating process (DGP)</li><li>The idea of a mathematical distribution</li></ol><p>One of the main goals of statistics is performing “inference”, the foundations of which are addressed by four sub-topics:</p><p>3. The idea of a parameter</p><p>4. The idea of a statistic</p><p>5. How math operations on a random variable change its distribution</p><p>6. The central limit theorem (CLT)</p><p>Methods of inference that you learn in school such as hypothesis testing and confidence intervals are just logical consequences of the above 6 foundational ideas.</p><h4>The Idea of a Data-Generating Process</h4><p>A DGP is a black box “machine” which determines the outcome of an event. In other words, if we could look inside the “black box” (i.e., DGP) of an event of interest, we could perfectly predict the event’s outcome (if the DGP is deterministic). There would then be no need for statistics at all! Of course, in real life we usually do not know what the DGP of a given event is.</p><p>However, in the case of the event “die toss”, we DO know what the DGP is and it is deterministic. This is where things descend quickly into the realm of philosophy. Hold on to your seat.</p><p>The DGP of the event “die toss” is the full physical specification of the action, from the moment the die has momentum imparted onto it via one’s hand, to the time that the die comes to rest on the ground. If we could know the release angle of the die, momentum imparted over time onto the die, the motion of air molecules surrounding the die as it flies through open air, the way in which it hits the ground, and so on, all the way up to the point where the die comes to rest, we could perfectly know what face comes up every time a die is thrown, and hence the event “die toss” would not have a random outcome at all. The outcome would be deterministic. Note that I am dismissing the possibility that weird quantum mechanical effects somehow influence the predictability of macroscopic object motion when using Newtonian/classical physics.</p><blockquote><strong>Aside</strong>: If you’re anything like me, you might quickly find yourself getting into a rabbit hole of wondering whether the universe is deterministic and we use the idea of randomness as a catch-all for all things that we do not know, or whether the universe is probabilistic (however that might come about). In other words, are all DGP’s deterministic or is it possible that some DGP’s are probabilistic? It’s kind of scary to think about the possibility of the universe being deterministic. Wouldn’t that mean all things are predetermined and that our fates have already been sealed since the dawn of time? Wouldn’t that mean we have no “free will”? Thinking about the origin of randomness hasn’t really led me to any answers yet …</blockquote><p>The idea of a DGP is very generally applicable. There exists a DGP whenever something produces anything observable (either using the five senses or using engineered sensing devices such as SONAR). There is a DGP at play even for things that we cannot yet measure but may one day in the future be able to measure (e.g., dark matter).</p><h4>The Idea of a Mathematical Distribution</h4><p><strong>Note</strong>: For the remainder of the article, I will focus on <strong>continuous random variables</strong>. Although until this point I have been using the die toss as a running example (which is a discrete valued random event), I tend to think of statistical ideas within the context of continuous random variables, and hence this biased the pedagogy that I have chosen.</p><p>We first need to understand what is meant by the term “model”. A model is a mathematical construction that aims to replicate something of interest. An example of a model is the game world of “Grand Theft Auto 5” (GTA5). The GTA5 world is partially a model of Los Angeles. The game world of GTA5 is also ultimately a mathematical construct because, in the final analysis, it is nothing more than dot products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*3Z0kLqpz-nUodwYoqIOIfQ.png" /><figcaption>Two comparisons of GTA5 (top) and LA (bottom). Photo credits: <a href="https://www.quora.com/profile/Raymond-Villafana-1"><strong>Raymond Villafana</strong></a></figcaption></figure><blockquote><strong>Aside</strong>: If the goal of modelling is to create the most accurate possible “copy” of something, then one could argue that the best possible model of something is that “something” itself! This idea is encapsulated in the widely circulated quote “The best model of a cat, is a cat”.</blockquote><p>In our case, we are interested in creating a model of the DGP of an event of interest. <strong>A mathematical distribution is a model of an unknown DGP</strong> (DGP’s are almost always unknown in real life). A good mathematical distribution should be able to simulate data/outcomes/observations/realizations (all synonyms) in a way that makes the simulated data look as though it might have come from the true DGP.</p><p><strong>Note</strong>: I will use the terms “mathematical distribution” and “distribution” interchangeably.</p><p>There are many kinds of mathematical distributions. The most famous by far is the normal distribution, also called the Gaussian distribution. Remember that this is a DGP model. The question is: the DGP for what event? Well, the normal distribution can be used to model the DGP of many different events, such as:</p><ul><li>human height</li><li>IQ score</li><li>reaction time</li><li>measurement error</li><li>human body temperature</li><li>income</li></ul><p>Any distribution has associated with it a deterministic function called a <strong>probability density function (PDF)</strong>. Here is the PDF of the normal distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*F3OiZ8etyj_QooPMAGAOeQ.png" /></figure><p>Note the two Greek letters mu and sigma. <strong>mu is called the “mean parameter”</strong> and <strong>sigma is called the “standard deviation parameter”</strong>. Suppose we give them the following values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/102/1*704qrkjDFYh72S_jGefQyA.png" /></figure><p>the function would now look as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*I9w2st_FupV9MxH2uBqsHQ.png" /></figure><p>and we call this the <strong>standard normal distribution</strong>, which looks like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WwJbNoJ7QVxV_b5fUZUU1w.png" /></figure><p>You may be wondering what PDF’s have to do with helping us create a model for a DGP. We can use a PDF to create a data generation rule for generating random numbers. This means that by using the right PDF <em>f(x)</em>, we can simulate data that looks like something the DGP of an event of interest (e.g., human heights) could have produced. In short, a<strong> mathematical distribution = PDF + data generation rule</strong>.</p><p>The data generation rule is simple:</p><blockquote>The probability that a simulated number will be between A and B (where A ≤ B) is equal to the area under f(x) between x=A and x=B.</blockquote><p>For example, suppose <em>A = 0.2</em> and <em>B = 0.8</em>. The area under the standard normal curve between <em>x = 0.2</em> and <em>x = 0.8</em> is <em>0.209</em>, visualized below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*U22lG-mxzfibdMsGHuY4Mw.png" /></figure><p>We interpret the area as a probability; that is, the probability that a (standard) normally distributed random variable <em>X</em> will produce a realization that falls between 0.2 and 0.8 is 20.9%.</p><p>But what exactly do we mean by “probability”?</p><blockquote><strong>Aside</strong>: There are two paradigms in statistics: the frequentist paradigm and the Bayesian paradigm. Basically all statistics education at the high school and undergraduate levels adhere to the frequentist paradigm, which was championed by Sir Ronald Fisher, who essentially single-handedly created modern statistics as we know it. Bayesian statistics, named after Thomas Bayes, a Presbyterian minister and statistician who came up with what is now called Bayes&#39; Theorem, has been very popular in recent times among academic and professional statisticians. For a long time, Bayesian statistics was impractical due to its high computational demands but advances in computing technology and software have enabled the widespread use of Bayesian methods. Interestingly, Sir Ronald Fisher was a strong and vocal critic of Bayesian probability (which was then called the “theory of inverse probability”).</blockquote><p>Probability is a purely mathematical idea which can be defined as follows:</p><blockquote>Suppose the random variable <em>X</em> produces random observations according to some mathematical distribution (e.g., the standard normal). If we repeatedly draw realizations from <em>X</em> forever, then we will observe that the fraction of realizations that fall between x=A and x=B (where A ≤ B) will converge to some value between 0 and 1 as the number of realizations obtained goes to infinity. We call this value the probability that a given realization will fall between A and B.</blockquote><p>Here’s a tough question:</p><p>Suppose <em>X</em> is a real valued random variable. What is the probability that a realization <em>x</em> will be equal to <em>C</em>, where <em>C</em> is any real number?</p><p>Answer:</p><p>zero.</p><p>Think about it. For any number <em>C</em> specified prior to a realization, it is impossible for that realization to be equal to <em>C</em> with infinite decimal point precision. This would be harder (infinitely harder actually) than dropping a needle from space and making it land in a pinhole poked into a matchbox on the ground at a pre-specified location. For any number <em>C</em>, there are an infinite number of other values that can be realized; the probability that your number <em>C</em> will be realized is 1 divided by infinity, which is 0.</p><p>Let’s go through an example of comparing data generated by a real (but unknown DGP) and data generated by a constructed mathematical distribution.</p><p>Below, the plot on the left shows a histogram of adult male heights. The data is from the US National Health and Nutrition Examination Survey (NHANES, 1999–2004). The plot on the right shows 2289 realizations obtained from a normal distribution which I specified (recall that there are only two parameters to specify for the normal distribution: the mean and standard deviation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*ocWq_TEOxCl-omcJuP9OEg.png" /></figure><p>The two histograms look pretty similar and if it weren’t for the titles, I wouldn’t be able to tell which histogram represented the real data and which represented the simulated data.</p><h4>What Is Inference?</h4><p>An inference is an educated guess. For example, if there is heavy traffic on the highway, it’s reasonable to infer that there was an accident up ahead.</p><p>Likewise, a statistical inference is an educated guess. To the extent that statistics is about making inferences, statistics is all about making educated guesses. Statistical inferences are deduced logically from the models and assumptions that we use to describe something of interest.</p><p>Statistics addresses the problem of making inferences (guesses) about certain characteristics of an unknown DGP by using a finite set of realizations from whatever DGP we are interested in. We make inferences by:</p><ol><li>Momentarily neglecting the reality that observed data was produced by a DGP</li><li>Pretending the observed data was produced by some unknown distribution (e.g., Gaussian, Poisson, Exponential, etc.)</li><li>Estimating parameters (such as the mean and variance) of the unknown distribution and (often using the central limit theorem) computing probable ranges of values that the true parameters might reside in, which is only possible by assuming 1) and 2) above.</li></ol><p>Do not forget that a distribution is merely a mathematical construction, which is described by 1) a deterministic mathematical function (i.e., a PDF), and 2) a data-generating rule.</p><p>A key underlying assumption of statistical inference is that the true unknown parameters of the unknown distribution will tell us something useful and/or true about the unknown DGP. To me, it’s amazing that this assumption seems to hold in many real life applications of statistics, because I have no reason to believe that it should.</p><p>We should pause here. Has it hit you how profound the first two points above are? <strong>We are imposing a belief on <em>how</em> the data were generated</strong> <strong>all the</strong> <strong>while acknowledging that we are “bending the truth” to make inference tractable</strong>. In other words, <strong>statistical inference relies on the core assumption that observed data was generated from some distribution, which is itself just an abstract mathematical construction</strong>. This really drives home George Box’s famous quote “All models are wrong, but some are useful”.</p><h4>The Idea of a Parameter</h4><p>We now know that in statistics, observed data is assumed to come from this abstract mathematical construct called a “mathematical distribution”. The task of inference really begins with asking</p><p><em>“what shape is the distribution from which we assume the data came from?”</em></p><p>Recall that the normal distribution has two parameters associated with it: the mean parameter (represented by the Greek letter mu), and the standard deviation parameter (represented by the Greek letter sigma). The sigma parameter changes how wide <em>f(x)</em> is, and the mu parameter changes the location (along the x-axis) of the peak of <em>f(x)</em>. Quite often, parameters change the shape of a distribution <em>f(x)</em>.</p><p>Typically in introductory statistics courses, statistical inference amounts to inferring parameter values from a set of observed realizations that we assume were realized from some distribution. Since all we have at hand for inferring parameter values is observed data, you can logically deduce that whatever we decide to do, any calculations must come down to doing mathematical operations on our observed data. No black magic involved.</p><p>To infer parameter values, we compute statistics. But we will get to that later. First, we need to understand the precise definition of a “parameter”. Here it is:</p><blockquote>A parameter is any function of a distribution <em>f(x)</em></blockquote><p>Two widely known parameters are the mean and variance parameters. Mathematically, the mean parameter is defined to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsgPOAgFPutU2c5lMbBUXQ.png" /></figure><p>and the variance parameter is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVrAhdLS5DspG-zGVcPHNg.png" /></figure><p>You will immediately notice that the above definitions are abstract mathematical definitions and not helpful to us for inferring mu and sigma from a given collection of observations. They aren’t helpful because the definitions rely on <em>f(x)</em>, which itself relies on knowing the very parameter values that we are trying to find! This unhelpfulness of parameter definitions when inferring their values from observed data is true for any parameter, not just the mean and variance.</p><h4>The Idea of a Statistic</h4><p>So how do we incorporate observed data to help us infer parameter values? We create an analog of a parameter definition that we CAN compute using observed data. We call such an analog a “sample analog” because it is an analog of a parameter definition (such as the mean parameter) that we can evaluate using a sample of observations. We call any sample analog of a parameter a statistic. I will refine this definition shortly.</p><p>From high school or first-year calculus, you probably know that the discrete analog of integration is summation. This analog is the golden ticket that allows us to estimate a parameter such as mu and sigma (or any other parameter) via the construction of a statistic.</p><p>Here’s an example of the integration-summation analog in action. The integral below integrates from 1 to positive infinity, while the summation on the right sums all natural numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqiDIRixgP8Tnnd2f7tbeA.png" /><figcaption>The discrete analog of integration is summation.</figcaption></figure><p>Let’s refine our definition of a statistic. Note that I wouldn’t be surprised if most students couldn’t define what a statistic is after taking an introductory statistics course (this was certainly the case for me). Here’s a definition:</p><blockquote>A statistic is a function of a random sample (and thus is necessarily a random variable itself).</blockquote><p>Remember what a random sample is: it is a collection of random variables.</p><p>You’re probably familiar with the sample mean statistic. I show the definition of the sample mean below, along with the definition of the mean parameter mu to demonstrate the sample analog method in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*9d1gyMh9BzXs7WzH_70VMQ.png" /><figcaption>Sample analog of the mean parameter: the sample mean.</figcaption></figure><p>Note that the sample analog method did 4 things:</p><ol><li>Take out <em>f(x)</em></li><li>Replace the integral symbol with a summation</li><li>Replace the infinity bounds with the size of our random sample</li><li>Multiply the summation by the reciprocal of our sample size</li></ol><p>In short, the sample analog method converted a weighted average over all possible observation values (which is impossible to calculate in practice) into a simple average over our random sample (which is easy to calculate for a realized sample). This is the best we can do to estimate (guess) the value of mu.</p><p>Let’s do one more sample analog conversion of a parameter into a statistic. We will do variance this time. Again, we follow the same 4 steps that we used to convert the mean parameter into a statistic (the sample mean):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*mfWacpMiOsFbcAZCWxEvlA.png" /><figcaption>Sample analog of the variance parameter: sample variance.</figcaption></figure><p>Note that I replaced mu with the sample mean. In general, the sample analog method replaces unknown parameters with their sample analogs, so you will often have to perform the sample analog method of converting a parameter into a statistic several times to convert a parameter of interest into a statistic.</p><p>A very important point that you need to be aware of is that a statistic (such as the sample mean and sample variance) is a random variable, and <strong>you need to know when you are talking about a statistic as a random variable, and when you are talking about a statistic as a realization</strong>. The distinction can be made using upper and lower case letters (random variable and realization, respectively). For example, for sample mean, this looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/37/1*eCCS-OaPnaaSgZM8KNnUXw.png" /></figure><p>the notation for sample variance doesn’t often follow this uppercase/lowercase convention; instead, I often see authors use the following notation to denote sample variance as a random variable and realization, respectively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/44/1*-z8ag3icETa05aF7a-pGtw.png" /></figure><p>Any statistic has its own distribution known as its <strong>sampling distribution</strong> (the term sampling distribution is reserved only for the distribution of a statistic). Later, we will talk more about how to derive the sampling distribution from a random sample containing random variables that follow a known distribution.</p><p>Usually when we talk about a statistic, and certainly if we talk about its sampling distribution, expected value or variance, we are talking about the statistic as a random variable. A realization of a statistic cannot have a sampling distribution because its value is fixed. Also, a fixed value always has an expected value equal to the fixed value, and a variance of zero.</p><p><strong>Note</strong>: There is a step that I am skipping here for the sake of brevity whereby a check is made to determine if a statistic is “unbiased”. A biased statistic is one whose expected value does not equal the parameter value. In fact, the sample variance that I showed above is a biased statistic of the variance parameter. It turns out that when you replace the reciprocal of <em>n</em> with the reciprocal of <em>n-1</em>, the sample variance statistic becomes unbiased. This is the reason you’ll commonly see the sample variance equation using the reciprocal of <em>n-1</em>.</p><h4>How Math Operations On a Random Variable Change Its Distribution</h4><p>Say we have a <strong>random sample</strong> taken from a <strong>known distribution</strong> and we want to determine the <strong>distribution of its sample mean</strong> (i.e., we want to find the sampling distribution of the sample mean). Where do we even start? What if we extend this problem and decide that we want to know how to find the sampling distribution of any statistic from a random sample?</p><p>Things start to get a little bit complicated here. First of all, let me make one thing crystal clear:</p><blockquote>There is no general way to know what applying some function <em>b()</em> on a random variable <em>X</em> will do to the distribution of <em>X.</em> That is, there is no general rule to tell us what the distribution of <em>b(X)</em> will be. The answer depends on both <em>b()</em> and the distribution of <em>X</em>.</blockquote><p>Generalizing the above statement gives the following fact:</p><blockquote>There is no general way to know what the resulting distribution will be from applying some multivariable function c() on a random sample.</blockquote><p>Suppose you have multiple random variables, each having its own distribution. You might be tempted to think that adding the random variables to get a new random variable like so:</p><p><em>Z = V + W + X + Y</em></p><p>will result in the distribution of <em>Z</em> being the sum of the distributions of <em>V</em>, <em>W</em>, <em>X</em> and <em>Y</em>. <strong>This is completely wrong</strong>!</p><p>All hope is not lost though, because for certain functions <em>c()</em>, we DO know how to determine the distribution of the function’s output. And lucky for us, those “certain functions” happen to include the ones that we need to determine the distribution of the sample mean of a random sample.</p><p>Let’s think about how to determine the distribution of the sample mean of some random sample. The sample mean statistic is created by performing a simple averaging operation on a random sample. The average operation can be decomposed into 2 sub-operations:</p><ol><li>A summation</li><li>Multiplication by the constant <em>1/n</em></li></ol><p>where <em>n</em> is the sample size. In essence, we need to figure out two things:</p><ol><li>If the distribution of the random variables <em>X</em> and <em>Y</em> are known, what is the distribution of <em>Z = X + Y</em>?</li><li>How does multiplying a random variable by a constant change its distribution?</li></ol><p>Point 1 above amounts to applying a function <em>c(X, Y) = X + Y</em> on a random sample containing <em>X</em> and <em>Y</em>, and point 2 above amounts to applying a function <em>d(Z) = k*Z</em>, where <em>k</em> is a constant and <em>Z</em> is a random variable with a know distribution. If there is a way to figure out the distribution of <em>c(X, Y)</em> and <em>d(Z)</em> (given that we know the distribution of <em>X</em>, <em>Y</em> and <em>Z</em>), we can successfully determine the distribution of the sample mean of a random sample.</p><p>Lucky for us, there is an analytical way to achieve both points 1 and 2 above. Let’s address the first point. To figure out the distribution of the sum of two random variables with known distributions, we do:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZTJvgEt-RGLuSLzOektJg.png" /><figcaption>Convolution of two probability density functions.</figcaption></figure><p>For a sample of <em>n</em> random variables, you would repeatedly apply the above operation <em>n-1</em> times so that you cover every random variable in your sample.</p><p>To address the second point, we can obtain the distribution of a random variable <em>V = k*Z</em> (where <em>k</em> is a constant and <em>Z</em> is a random variable with a known distribution) by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*XYlniQLGarTMePjp7yYVsA.png" /></figure><p>and that’s all we need to compute the distribution of the sample mean of a random sample analytically.</p><p>Here’s a worked example using 2 Gaussian random variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*qHDn6voPLgytGNdFhT5iFQ.png" /></figure><p>Finally, let’s address the question</p><p>“How can I find the distribution of any statistic computed from a random sample?”</p><p>The answer depends on the kinds of sub-operations involved in computing your statistic. If the only sub-operations are the addition of random variables and multiplication of random variables by constants, then you’re in luck; you can follow a similar process to finding the distribution of the sample mean that we just went through.</p><p>However, if computing your statistic requires nonlinear sub-operations (e.g., squaring, cubing, square rooting, logging, sine transforms, etc.), then you will need to consult the internet (or some other resource like ChatGPT) for the relevant equations that show what applying your sub-operations to your random sample will do, distributionally speaking. The answer may depend on the distribution(s) of your random variables.</p><h4>The Central Limit Theorem</h4><p>In practice, you usually do not know which distribution family is most appropriate to use for inference. But you need to decide on one to proceed with inferring parameters. Luckily, there is a beautiful theorem known as the central limit theorem (CLT) which says:</p><blockquote>For any random sample that contains independent and identically distributed (IID) random variables, the distribution of the sample mean will converge to a normal distribution as the sample size increases to infinity.</blockquote><p>In symbols, the CLT states that given a large enough sample size,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*cRF19BZ-D9iUuQ6GqRtIqA.png" /></figure><p>The tilde symbol means “distributed according to”, and the “approx.” modifies the meaning of the tilde symbol to mean “approximately distributed according to”. The capital <em>N</em> indicates the Gaussian distribution.</p><p>There’s a lot to unpack here. First of all, what do I mean by “independent” in the phrase “independent and identically distributed”? Two random variables are said to be independent if the realized value of one of them does not influence the realized value of the other one. Mathematically, two random variables, <em>X</em> and <em>Y, </em>are independent if their joint distribution <em>f(x, y)</em> equals <em>g(x)h(y)</em>, where <em>g()</em> is the distribution of <em>X</em> and <em>h()</em> is the distribution of <em>Y</em>.</p><p>Think for a moment why <em>f(x, y)</em> <em>=</em> <em>g(x)h(y) </em>if<em> X </em>and<em> Y</em> are independent. Suppose you have a coin and make two tosses. What is the probability of getting two heads? It is</p><p>0.5 * 0.5 = 0.25</p><p>or 25%, because there’s a 50% probability for each coin toss that you will get heads. Each toss is independent of the other because the first toss’s outcome does not influence the fairness of the coin, and the second toss’s outcome cannot possibly change the outcome of the first toss. So if <em>X</em> denotes the (unknown) outcome of toss 1 and <em>Y</em> denotes the (unknown) outcome of toss 2, then</p><p><em>Prob(X = heads, Y = heads) = Prob(X = heads) * Prob(Y = heads)</em></p><p>or in words, the probability that both tosses yield heads is the probability that the first toss yields heads, multiplied by the probability that the second toss yields heads.</p><p>The exercise that we just went through can be generalized to random variables that take real number values. The only change that needs to be made is the swapping out of the discrete probability function “Prob” with probability density function notation. And thus we get the result: if <em>X </em>and<em> Y</em> are independent, then <em>f(x, y)</em> <em>=</em> <em>g(x)h(y).</em> The analogy is somewhat weak because the probability of getting any particular value <em>x </em>and <em>y</em> is 0 for continuous random variables <em>X</em> and <em>Y</em>, but when we consider integrating both sides of the equation <em>f(x, y)</em> <em>=</em> <em>g(x)h(y) </em>for specified bounds, the analogy holds nicely.</p><p>Next, what does “identically distributed” mean? This one is pretty easy. It just means that each random variable in our random sample is governed by the exact same distribution (including parameters).</p><p>Lastly, the key claim of the CLT is that given a large enough random sample, the distribution of its sample mean will approximate a normal distribution. This is where the magic resides. The fact that sample means approximately follow a normal distribution (regardless of what distribution each observation in a sample was drawn from) enables us to <strong>make inferences about unknown distributions</strong>. This is because common statistics include sums and/or averages of sample observations, and anytime there is a sufficient number of data points being summed/averaged, we know that the sum/average will be approximately normally distributed, and hence we have a starting point for further analysis. Without the CLT, we wouldn’t know where to start because we likely would not know what distribution to use to make a DGP model.</p><p>One question you may have is “When do I know I have a large enough sample size?” Good question. A rule of thumb sample size that I often hear get thrown around is 30 (it’s also what I was recommended in my statistics classes), so I will recommend 30 also. Do note though that if your sample appears to come from a highly non-normal distribution, you may want to collect more than 30 observations.</p><blockquote><strong>Aside</strong>: So why do so many real-life observations appear to come from a normal distribution? I will suggest one argument.</blockquote><blockquote>The reason that we see so many natural processes generate data that look similar to what a normal distribution would generate is that many real processes “under the hood” are aggregates (i.e., sums and averages) of sub-processes that are completely hidden from us. For instance, what is the mechanism by which a person’s height is determined? One could speculate that height is the result of many factors or “sub-processes”, and each of these sub-processes may be modelled using some distribution. Although I do not go into it here, there is an extension of the central limit theorem that lets us break free from the “identically distributed” part of the IID assumption (known as the Lindberg CLT). Using this extended CLT, it is possible to see that when such sub-processes are modelled with distributions, and we denote each sub-process using a random variable, then the sample mean of all sub-process random variables will be approximately normally distributed.</blockquote><blockquote>This argument, however, is weak; the math working out when the various sub-processes are modelled as distributions does not at all guarantee that we will see the same behavior in real life.</blockquote><blockquote>But we do.</blockquote><blockquote>So there’s something going on here; mathematics seemingly works unreasonably well to model the world. To be honest with you, I find it amazing that statistics is useful in the first place. There is no guarantee that it should work well in the real world, but it often does work well. Indeed, in 1960, Eugene Wigner (a nuclear physicist) wrote an article titled “The Unreasonable Effectiveness of Mathematics in the Natural Sciences”.</blockquote><h3>Concluding Words</h3><p>This was a LONG article. First of all, if you made it to this point, I want to thank you deeply for taking the time to read this. I think statistics is a subject which needs to be taught from first principles, and this article was my attempt at providing a brief overview of what I perceive to be foundational material. If you found any logical gaps in my writing, please do reach out and let me know where you believe my thinking is flawed/erroneous. If you have suggestions/comments/criticisms or questions, also reach out. Until next time my friend.</p><p>John</p><h3>References</h3><p>Hansen, B. E. (2022). <em>Probability and statistics for economists</em>. Princeton University Press.</p><p>Zabell, S. (1989). R. A. Fisher on the history of inverse probability. <em>Statistical Science</em>, <em>4</em>(3). <a href="https://doi.org/10.1214/ss/1177012488">https://doi.org/10.1214/ss/1177012488</a></p><p><a href="https://www.britannica.com/biography/Thomas-Bayes">https://www.britannica.com/biography/Thomas-Bayes</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22866a361cec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pairwise Correlation and Cointegration Among Listed US Equities]]></title>
            <link>https://medium.com/@johnswyou/pairwise-correlation-and-cointegration-among-listed-us-equities-12cc14293baa?source=rss-832499040d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/12cc14293baa</guid>
            <category><![CDATA[usa]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[cointegration]]></category>
            <category><![CDATA[correlation]]></category>
            <dc:creator><![CDATA[John You]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 17:41:48 GMT</pubDate>
            <atom:updated>2023-04-07T17:41:48.380Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1gm1RbIWoN0L3KMq" /><figcaption>Photo by <a href="https://unsplash.com/@rayhennessy?utm_source=medium&amp;utm_medium=referral">Ray Hennessy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Pairs_trade">Pairs trading</a> is a widely known trading strategy said to have been developed at Morgan Stanley in the 1980’s [1]. Simple versions of this strategy rely on finding a pair of assets that appear to have cointegrated price histories. The first logical step in building a simple pairs trading strategy, therefore, would be to find pairs of assets that appear to be cointegrated. This article shows one way to do just that.</p><h3>Methodology</h3><p>In this article, I restrict myself to one universe: listed US equities. I use the <a href="https://www.alphavantage.co/">Alpha Vantage API</a> to download the price histories of all listed US equities provided by the API. As of writing this article, I am able to obtain price histories (in CSV format) of 11,257 tickers. Each CSV file has the same column headers: Date, Open, High, Low, Close, Adjusted Close, Volume, Dividend, and Split Coefficient. I use daily data in this article.</p><p>My data from the Alpha Vantage API extends back to, at the earliest, November 1, 1999. I decided to consider all equities with no missing adjusted closing prices between March 30, 2003 and March 30, 2023. This resulted in 2,142 tickers.</p><p>Enumerating all possible pairwise combinations of our 2,142 tickers leads to 2,293,011 possible pairings. Computing this many cointegration tests is intractable using my humble 5 year old laptop, so I need a method to reduce the number of stock pairs from 2,293,011 down to something more manageable. I decided to use Pearson’s correlation between the adjusted closing price of stock pairs to filter the 2,293,011 possible pairs for those with a correlation greater than 0.99. This resulted in a mere 1,390 stock pairs.</p><p>Finally, I ran a cointegrated augmented Dickey-Fuller (CADF) test on each of the 1,390 pairs (using adjusted closing price), and did one last filtering to extract from the 1,390 pairs those that resulted in a CADF test p-value of less than 0.05. In the end I obtained 848 stock pairs.</p><h3>Results</h3><p>The distribution of pairwise correlation (obtained by computing Pearson’s correlation for all 2,293,011 possible pairings) looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*lUA_nPkiPoYiodoS_4TMVA.png" /></figure><p>Here’s the distribution of the CADF test p-values (computed on the 1,390 highly correlated (&gt; 0.99) equity pairs):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*onAZlPJHGr_z1_DCVAVfJw.png" /></figure><p>848 pairs had a CADF test p-value of less than 0.05:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*Wu45M6wYqYeM-Lv4bQQHaQ.png" /></figure><p>You can see that the index column above indicates a stock pair (e.g., “WSO-B” and “WSO” indicates a pair of Watsco tickers, with “WSO-B” indicating the class B share of Watsco).</p><p>We can take a look at the daily adjusted close price series of 4 randomly selected pairs from the 848 pairs above (prices are in USD):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*Xi91TmLI04ys20xv-syi2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*3KZnVCkQhrEJBxHUT3gzRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*LoNnBBMZLGc1YMkv0j4v9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*7O78Btr64mS30mtYVxS-2A.png" /></figure><p>Very neat!</p><h3>Code</h3><p>Code used to generate the results in this article can be found on my GitHub page:</p><p><a href="https://github.com/johnswyou/Pairwise-Cointegration-Medium">GitHub - johnswyou/Pairwise-Cointegration-Medium: Code for my Medium article &quot;Pairwise Correlation and Cointegration Among Listed US Equities&quot;</a></p><h3>Conclusion</h3><p>By screening asset pairs using an approach similar to the one shown in this article, you’ll have a list of asset pairs to further scrutinize for developing your pairs trading strategy. Best of luck!</p><p>John</p><h3>References</h3><p>[1] Bookstaber, Richard. <em>A Demon Of Our Own Design</em>, p. 186. Wiley, 2006.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12cc14293baa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Have Blind Faith in ChatGPT]]></title>
            <link>https://medium.com/@johnswyou/dont-have-blind-faith-in-chatgpt-aaa93059e6b2?source=rss-832499040d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaa93059e6b2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[John You]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 20:45:28 GMT</pubDate>
            <atom:updated>2023-03-25T21:01:49.046Z</atom:updated>
            <content:encoded><![CDATA[<h4>ChatGPT can’t replace data scientists… yet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FGlwXKBeGQqFXT2C" /><figcaption>Photo by <a href="https://unsplash.com/@elliottengelmann?utm_source=medium&amp;utm_medium=referral">Elliott Engelmann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ChatGPT can code ideas in seconds what would have taken me hours in the past. While I was (and continue to be) floored by ChatGPT’s ability to generate code from plain English prompts, we must never fully trust ChatGPT’s code responses without carefully inspecting them first. As ChatGPT improves (and OpenAI’s competitors roll out their own versions of ChatGPT), we may find ourselves increasingly trusting these language models to help us write code. While the productivity boost enabled by services like ChatGPT is certainly worthy of celebration, we should never submit to the sweet temptation of not checking generated code responses. Yes, it takes effort to read and understand code responses. However, unless you take the time to carefully inspect and understand ChatGPT’s generated code responses, you may let subtle errors creep into your projects that may only be detected later on when it’s too late.</p><p>In this article, I will show that ChatGPT, while often excellent, has limitations that can lead to invalid code being generated. This is demonstrated using a short case study that involves building a prediction model, with all ideas originating from ChatGPT. You will see that while ChatGPT is able to come up with ideas worth testing (and code to implement those ideas), ChatGPT (when prompted in plain English) fails to</p><ol><li>account for code execution time</li><li>avoid leaking out of sample information into the training set</li></ol><p>I will use the free version of ChatGPT in this article, available here:</p><p><a href="https://openai.com/blog/chatgpt">Introducing ChatGPT</a></p><h3>Predicting Glassdoor Ratings</h3><p>Glassdoor is a US based employer review website where employees (both current and former) can review and rate their company and position. Our prediction task will be to predict what rating a user will give (ratings go from 1 to 5) by using information such as the time of posting a review, the reviewer’s position and company, etc.</p><p>The data set that we will be using (taken from Kaggle) contains 553,678 rows and 10 columns. Here’s the first 4 rows and 6 columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*0V_4r1rfFxC5pKj_BqSjSg.png" /></figure><p>and here’s columns 7 to 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*-irxGt-5wCcgw9YXw6jFTg.png" /></figure><p>The target variable is the first column overall_rating, and our goal is to train a prediction model to predict overall_rating for new (previously unseen) user reviews.</p><p>The dataset can be downloaded here:</p><p><a href="https://github.com/johnswyou/kaggle_glassdoor_reviews">GitHub - johnswyou/kaggle_glassdoor_reviews</a></p><p>Note that I provide 2 versions: glassdoor_training_large.csv and glassdoor_training_small.csv. glassdoor_training_small.csv (which contains 110,729 rows) is a subset of glassdoor_training_large.csv (which contains 553,678 rows).</p><h3>Chat Session</h3><h4>Feature Engineering</h4><p>I started my chat session with ChatGPT with the following prompt:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*FNFcDJwzAzqhTzNl-Yu0GA.png" /><figcaption>Prompt 1.</figcaption></figure><p>and here’s how ChatGPT responded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*v0c-uMIUdxeg2yJkAVE_fQ.png" /><figcaption>Response 1.</figcaption></figure><p>The hard part is turning ideas into code. Not so for ChatGPT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*Z28a2uqbsCESQAqN7JnO7Q.png" /><figcaption>Prompt 2, response 2.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a40cde3bec3d787d741b941bab0afe2/href">https://medium.com/media/9a40cde3bec3d787d741b941bab0afe2/href</a></iframe><p>An interesting observation here is that ChatGPT decided to use RandomForestClassifier from Scikit-Learn. I did not specify which classifier to use, but ChatGPT was able to independently select one of the best “out of the box” classifiers. Although there is no guarantee that random forest will work well, it is a reasonable first choice for multi-label classification, which is exactly the kind of problem we are dealing with.</p><p>Note that on line 11 of the code snippet above, ChatGPT inserted an intelligently named placeholder CSV file name called glassdoor_ratings.csv. When we run the above code snippet, we would replace glassdoor_ratings.csv with glassdoor_training_large.csv (which, again, can be found here: <a href="https://github.com/johnswyou/kaggle_glassdoor_reviews">https://github.com/johnswyou/kaggle_glassdoor_reviews</a>).</p><h4>Model</h4><p>I wanted to probe ChatGPT further about its model choice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*Ssy3AOvWvK4jZi74zHxh2w.png" /><figcaption>Prompt 3, response 3.</figcaption></figure><p>In the spirit of letting ChatGPT lead the model building process, I let ChatGPT expand on its suggestions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*jEDHTrr-zkdArosK5ydixQ.png" /><figcaption>Prompt 4, response 4.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6996fd360932a9e000ed582389531ffa/href">https://medium.com/media/6996fd360932a9e000ed582389531ffa/href</a></iframe><p>ChatGPT ended its response (after presenting the code above) with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*-KEKwuXAu7lZzcwJkYL_iw.png" /><figcaption>Last sentence of response 4.</figcaption></figure><p>Naturally, I followed up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*KrjdEllymiAJhtOJy_IHbw.png" /><figcaption>Prompt 5, response 5.</figcaption></figure><p>ChatGPT went with grid search, and provided reasonable grid bounds:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c67b45dca5c2d21a7271806e5b10856/href">https://medium.com/media/2c67b45dca5c2d21a7271806e5b10856/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*pFdj7vlkvRaz-coMEqLcmg.png" /><figcaption>Response 5 (continued).</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f385fb16f3ec29dbafd0acaf5db4c14d/href">https://medium.com/media/f385fb16f3ec29dbafd0acaf5db4c14d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*y7Msd_tpF-xplvMe-B-CFg.png" /><figcaption>Response 5 (continued).</figcaption></figure><h3>Limitations</h3><p>So ChatGPT seems to work great right? Well, it certainly appears that way until you actually run the codes (or read through the codes carefully, which is what you should always do with ChatGPT code output). In this section, I present 2 key limitations of ChatGPT for data science that were observed above.</p><h4>Limitation 1: Limited domain knowledge</h4><p>Though this may not itself be a problem since I do not expect ChatGPT to be an expert in every human endeavor, there is a danger present when ChatGPT <em>appears </em>to have domain knowledge. In our case, there were 2 fatal flaws:</p><ol><li>Leakage of out of sample data into the training set</li><li>No input feature scaling, which resulted in a ValueError when fitting the multinomial naive Bayes model suggested by ChatGPT.</li></ol><p>Leakage of out of sample data into the training set occurs because the code ChatGPT generated 1) engineers features using the full data set and 2) splits the resulting feature set into train and test sets. The valid way to engineer features would have been to 1) split the original full data set first and 2) engineer features on the train and test sets separately. This way, information from the test set would not leak into the training set due to the way job_similarity_mean and location_similarity_mean are computed.</p><p>Input feature scaling, which is generally recommended prior to training machine learning models, was not included in the code generated by ChatGPT. This would have been acceptable, had it not been for ChatGPT’s suggestion to use multinomial naive Bayes, which requires having only positive valued input features.</p><p>So, the first fatal flaw in ChatGPT’s code was about validity of methodology. The second fatal flaw resulted in a ValueError being raised.</p><h4>Limitation 2: Code execution time</h4><p>The code generated by ChatGPT cannot be run in a reasonable amount of time because of 3 areas in the code:</p><ol><li>Computation of the feature job_similarity_mean</li><li>Computation of the feature location_similarity_mean</li><li>The use of support vector machine (SVM)</li></ol><p>Points 1 and 2 above take impractically long on our data set because computing both job_similarity_mean and location_similarity_mean requires calling compute_similarity N squared times, where N is the number of rows in the full data set.</p><p>Support vector machine is not suitable for training sets containing more than a few tens of thousands of samples, because its time complexity scales quadratically with the number of training samples. SVM took painfully long to compute, and although not incorrect to suggest SVM, it would have been nice for ChatGPT to insert a comment about the feasibility of SVM (and, for that matter, the feasibility of its generated code applied to our data set).</p><h3>Conclusion</h3><p>ChatGPT has revolutionized the development experience for myself and many others. I no longer find myself using stack overflow or GitHub issue forums (which are usually filled with completely useless answers that are all talk no action) as much as I used to before ChatGPT was released. I am definitely in the camp that ChatGPT has been the biggest revolution in tech since the original iPhone.</p><p>With that being said, ChatGPT’s apparent domain knowledge in different technical fields (such as machine learning) must be leveraged with caution. Always check sources, and ALWAYS understand code that ChatGPT generates for you.</p><p>Thanks for reading!</p><p>John</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaa93059e6b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>