<?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 Gerwyn Ng on Medium]]></title>
        <description><![CDATA[Stories by Gerwyn Ng on Medium]]></description>
        <link>https://medium.com/@gerwynng?source=rss-b8d0c4ff0bb9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*uAwWhQceVV7SC9RL6jGr2A.jpeg</url>
            <title>Stories by Gerwyn Ng on Medium</title>
            <link>https://medium.com/@gerwynng?source=rss-b8d0c4ff0bb9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:23:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gerwynng/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[Regression Difference in Differences]]></title>
            <link>https://medium.com/eatpredlove/regression-difference-in-differences-208c2e787fd2?source=rss-b8d0c4ff0bb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/208c2e787fd2</guid>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[empirical]]></category>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[econometrics]]></category>
            <dc:creator><![CDATA[Gerwyn Ng]]></dc:creator>
            <pubDate>Fri, 20 Dec 2019 16:36:47 GMT</pubDate>
            <atom:updated>2019-12-23T09:24:12.658Z</atom:updated>
            <content:encoded><![CDATA[<h3>Generalised Regression Difference in Differences</h3><h4>with Fixed Effects, Multiple Treatment Periods and Dynamic Treatment Effects</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-x5Ce3EhZS6dh7L7YLuomw.png" /></figure><h3>What is Difference in Differences?</h3><p>Difference in differences (DiD) is a non-experimental statistical technique used to estimate treatment effects by comparing the change (difference) in the differences in observed outcomes between treatment and control groups, across pre-treatment and post-treatment periods.</p><p>DiD is commonly used to recover the causal effect of interest from observational study data — where the experimental design is out of the researcher’s control (e.g. natural experiment) and usually subjected to unobserved confounders and some form of selection bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*KiRkxO-fUCfXSkJMR0bDig.png" /><figcaption><strong>Causal Pathway Illustration:</strong> Z (confounder) is the cause of both X (independent variable) and Y (dependent variable) and thus, obscures the relationship between X and Y.</figcaption></figure><blockquote>The DiD estimator is, in fact, a version of the Fixed Effects Model which uses aggregated data. As such, its data requirements are much less and work wells with repeated cross-sectional data. In contrast, panel data are relatively more expensive and difficult to collect.</blockquote><h4>Intuition</h4><p>DiD is a combination of time-series difference (compares outcomes across pre-treatment and post-treatment periods) and cross-sectional difference (compares outcomes between treatment and control groups).</p><p>There are two equivalent strategies to think about the two “differences”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYT04dz8Mn80Bw3zyvTG_g.png" /><figcaption><strong>Mechanical Description</strong></figcaption></figure><p>Visually, the DiD is the difference between these two changes:</p><ol><li>changes in outcomes from pre-treatment to post-treatment</li><li>changes in outcomes between treatment and control groups</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yyVOO-oWeSPlgblipljulg.png" /><figcaption><strong>Graphical Illustration</strong></figcaption></figure><h3>Regression DiD</h3><p>While it is possible to obtain the DiD estimator by calculating the means by hand, using a regression framework may be more advantageous as it:</p><ul><li>outputs standard errors for hypothesis testing</li><li>can be easily extended to include multiple periods and groups</li><li>allows the addition of covariates</li></ul><h4>Simple DiD</h4><p>The simplest setup involves observed outcomes for two groups for two time periods:</p><ol><li>The treatment group is exposed to treatment in the second period but not the first</li><li>The control group is not exposed to treatment during either period</li></ol><p>In this case, the treatment effect can be estimated by subtracting the average change in the control group from the average change in the treatment group. Doing so removes <strong>unobserved and fixed biases</strong> in the second-period comparison that could be the result of:</p><p>a. inherent differences between the two groups and,</p><p>b. changes in trend from first to the second period that is common to both groups.</p><p>With repeated cross-sectional data, the regression model can be defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbpjTgRvNLgFMDvbANpt-w.png" /></figure><p>where <em>y </em>is the outcome of interest, <em>P </em>is a dummy variable for the second time period and <em>T </em>is a dummy variable for the treatment group<em>. </em>The interaction term, <em>P </em>×<em> T</em>, is equivalent to a dummy variable equals 1 for observations in the treatment group, in the second period.</p><p>The coefficients can be interpreted as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJItSwzDDFe-YW4C9BZ1cw.png" /><figcaption>The simple DiD estimator allows for the intercepts to vary between the treatment (β₀ + β₂) and the control group (β₀) and assumes constant outcomes within the two time periods (β₁).</figcaption></figure><ul><li><strong>β₁:</strong> Average change in <em>y</em> from the first to the second time period that is common to both groups</li><li><strong>β₂: </strong>Average difference in <em>y</em> between the two groups that is common in both time periods</li><li><strong>β₃: </strong>Average differential change in <em>y</em> from the first to the second time period of the treatment group relative to the control group</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etuwZRKQ-0cCfFO5jkMftw.png" /><figcaption><strong>Graphical Illustration of Coefficients</strong></figcaption></figure><p>By OLS, the simple DiD estimator is given as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wxSJkeLCmsQJeeXCRReGQA.png" /></figure><h4>Generalised DiD: Fixed Effects and Multiple Treatment Periods</h4><p>Since the regression framework allows us to add more covariates, we can formulate a more general DiD regression with allows for:</p><ol><li>the intercept term to vary for each cross-sectional unit (αᵢ instead of β₂)</li><li>the common change in outcomes to vary across time (δt instead of β₁)</li><li>different timing of the treatment for different treated units, (<em>dt</em> instead <em>Pt</em>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32TwgqKuvkq-rl4Of422QQ.png" /></figure><ul><li><strong>αᵢ:</strong> Individual fixed effects that change across individuals (state-specific characteristics, individual’s gender, etc.)</li><li><strong>δt:</strong> Time fixed effects that change across time (e.g. year dummies to allow intercept to vary across different years)</li><li><strong><em>dt</em>:</strong> dummy variable which equals 1 if the unit of observation is in the post-treatment period (in contrast to <em>Pt</em> equals 1 in the second time period)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1p3yCA2SzdoT8TvQ21orw.png" /><figcaption><strong>Graphical Illustration: </strong>In the generalised model, we allow the intercepts to vary across both time and individuals</figcaption></figure><h4>Generalised DiD with Dynamic Treatment Effects</h4><p>To capture dynamic treatment effects, we allow our DiD estimator, β₃, to vary across time by using a time-variant coefficient, ρt, on the interaction term, <em>Dt</em> × <em>Tᵢ.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GQTqA1CL8H1V-4rgbb8dg.png" /></figure><p>where <em>Dt </em>= 1 in period <em>t </em>and 0 otherwise.</p><p>This specification allows us to capture leads and lags of the treatment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlVj9rXukhkR4Rs1DzXY_g.png" /><figcaption><strong>Graphical Illustration: With dynamic treatment effects, the outcomes for the treated in the post-treatment period are no longer parallel to the assumed counterfactual</strong></figcaption></figure><h3><strong>Keeping it Causal: The Parallel Trends Assumption</strong></h3><p>For our DiD estimator to be causal, we require the parallel trends assumption to hold. This assumption allows us to use the control group as a proxy for the assumed counterfactual trend (which is unobserved) of the treatment group. That is, in the absence of treatment, both the treatment and control groups should experience the same change in outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YGByVHg0CYW-9-AnXiPIA.png" /><figcaption><strong>Graphical Illustration: </strong>In the absence of treatment, the treated should observe the same trend as the control group. If this assumption holds, we can then attribute the change in the trend of the treated, in the presence of treatment, to the treatment itself.</figcaption></figure><h3><strong>Threats to Causal Inference using DiD</strong></h3><p>Although the DiD method is intended to mitigate the effects of confounders and selection bias, it may still be subjected to threats that can invalidate its causal inference.</p><h4>Violation of the Parallel Trends Assumption</h4><p>The most important assumption is violated when there exist unobserved factors that are correlated with both treatment status and timing of the treatment. In other words, there could be factors (besides the treatment) that cause a change in one group but not the other at the same time as the treatment. Various issues that could compromise the results include autocorrelation and the Ashenfelter dips (where treatment is assigned primarily based on pre-existing differences in outcome).</p><p>While the Parallel Trends Assumption is typically untestable (since counterfactual is never observed), the following strategies are often applied to improve the credibility of results:</p><ul><li>Verify that pre-treatment trends are parallel for a reasonable timeframe</li><li>Cross validate results using alternative control or treatment groups</li><li>Test if there exists a treatment reversal effect</li></ul><h4>Compositional Difference</h4><p>Because DiD is often implemented using repeated cross-sectional data, significant changes in the composition of the samples across periods may simply reflect changes in the composition of each group, rather than the treatment effect.</p><h4><strong>Extrapolation</strong></h4><p>Depending on the setting of interest, results may be unable to generalise to other populations or even a longer timeframe.</p><h3>Implementation with R</h3><p>Since the DiD estimator is a version of the Fixed Effects Model, the DiD regression may be modeled using a Fixed Effect Linear Regression using the lfe package in R.</p><p>The dummy syntax is as follows:</p><pre>felm(causal relation of interest | fixed effects | IVs | clusters, data = your_data)</pre><p>An example:</p><ol><li>The dependent variable, y</li><li>The independent variable whose coefficient is of interest, x</li><li>Fixed effects, f1 and f2</li><li>Endogenous variables Q and W instrumented by z1 and z2</li><li>Clusters, c1 and c2, to compute standard errors which allow for correlation within all combinations of c1 and c2</li></ol><pre>#import<br>library(lfe)</pre><pre>#fit your regression<br>felm(formula = y ~ x | f1 + f2 | (Q|W ~ z1 + z2) | c1 + c2, data = df) %&gt;%<br>  summary(robust = TRUE) #display results w/ robust standard errors</pre><h3>References</h3><p>[1] Angrist and Pischke (2008). Mostly Harmless Econometrics: An Empiricist’s Companion. Princeton University Press.</p><p>[2] C. Junxing (2019). Empirical Economics Course Materials.</p><p>[3] Imbens and Woodridge (2007). <a href="http://www.nber.org/WNE/lect_10_diffindiffs.pdf">Difference-in-Differences Estimation</a>. NBER</p><p>[4] J. Pischke (2019). <a href="http://econ.lse.ac.uk/staff/spischke/ec533/did.pdf">Differences-in-Differences</a>. LSE</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=208c2e787fd2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eatpredlove/regression-difference-in-differences-208c2e787fd2">Regression Difference in Differences</a> was originally published in <a href="https://medium.com/eatpredlove">eat-pred-love</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Cubic Splines Implementation with Python]]></title>
            <link>https://medium.com/eatpredlove/natural-cubic-splines-implementation-with-python-edf68feb57aa?source=rss-b8d0c4ff0bb9------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf68feb57aa</guid>
            <category><![CDATA[numerical-methods]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interpolation]]></category>
            <dc:creator><![CDATA[Gerwyn Ng]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 13:57:25 GMT</pubDate>
            <atom:updated>2019-12-06T10:18:32.452Z</atom:updated>
            <content:encoded><![CDATA[<h4>Piece-wise interpolation with a global interpretation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DR8ihMpKQg9F9aWHObtfVg.png" /></figure><p>Before we jump into the algorithm for computing natural cubic splines, let us build some motivation for interpolation methods.</p><h3>Connect the Dots</h3><p>Interpolation is the process of using a function that fits the given data. Given a (limited) number of data points, interpolation provides a means of estimating the value of that function for any intermediate value.</p><h3>Can’t I Just Use a Pencil?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHTzg3XPt3L_gX3--V7u2w.png" /><figcaption>Classes of Common Interpolants</figcaption></figure><p><strong>Algebraic polynomials</strong> are one of the well-known classes of functions that are able to map the set of data points into itself. The idea is to approximate arbitrary functions to fit the data points using a single polynomial. The problem, however, is that high-degree polynomials often oscillate erratically and thus, tend to overfit. This problem is often referred to as <em>Runge’s Phenomenon</em>.</p><p>A workaround would be a <strong>piecewise-polynomial approximation</strong>. That is, we divide the interval into a collection of sub-intervals and fit different polynomial on each sub-interval. In other words, we are connecting sequential data points by a series of polynomials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*4QpPyqI9AivRe_fQLuJcsQ.png" /><figcaption>Visual comparison between linear and cubic piece-wise interpolation</figcaption></figure><p>The simplest example would be to join a set of data points using straight lines. One disadvantage of using linear functions, however, is a lack of smoothness from one sub-interval to another. Mathematically, this implies that at every end-point of each sub-interval, the slope of the interpolant is likely to be undefined. <strong>Cubic spline interpolation </strong>addresses this shortcoming by using third-degree polynomials. Doing so ensures that the interpolant is not only continuously differentiable but also has a continuous second derivative.</p><h3>Connecting the Dots &amp; Reading between the Lines</h3><p>By construction, cubic spline interpolation fits a set of data points with <em>n-1</em> cubic polynomials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OckyhZSYd3PyXgQYXfyYkQ.png" /><figcaption>A total of 3(n-1) unknowns to be solved for</figcaption></figure><p>with the following properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ji1wev3B5cIMyMYFvl620Q.png" /><figcaption>Property 1 imposes n-1 conditions while properties 2 and 3 impose<em> n-2 </em>conditions each</figcaption></figure><p>Property 1 guarantees that the interpolant passes through all data points while properties 2 and 3 force the slope and curvature of the splines, at the end-point of each sub-interval, to agree where they meet. The latter characteristic also creates some form of “relationship” between the data points, allowing the interpolant to have a <em>global interpretation</em>.</p><p>Because we have <em>3n-3 </em>unknowns to solve for and only <em>3n-5 </em>conditions imposed, we still need two additional conditions to construct the splines. The natural (or free) boundary condition is one way to impose the two addition conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*xAZmgshi-TsSzqTwGOsLFA.png" /></figure><p>When the free boundary condition is satisfied, the spline is called a <strong>natural spline</strong>. In practice, the coefficients of the natural splines are solved for as follows:</p><ol><li>Solve for <em>c</em> from:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rze5kYcjlmvcoksJ9BD8-g.png" /></figure><p>Note that since the left-most matrix is strictly diagonally dominant, it makes sense to solve this iteratively using <em>Jacobi’s Method</em>.</p><p>2. Solve for <em>b</em> and <em>d</em> from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSUzaye4fnh9TcnNetMeCQ.png" /></figure><h3><strong>Constructing Natural Cubic Splines with Python</strong></h3><p>Finally, let us explore how we can code the algorithm.</p><h4><strong>Step 1: Create our Own Jacobi Method</strong></h4><p>Here, we define <strong>tolerance</strong> as <em>the norm of the difference between the matrices of the current and previous iteration</em>. In addition, the Seidel technique (where we use the updated x values for the next iteration) is also applied for faster convergence.</p><pre><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong></pre><pre><strong>def</strong> jacobi(A, b, x0, tol, n_iterations=300):<br>    <em>&quot;&quot;&quot;</em><br><em>    Performs Jacobi iterations to solve the line system of</em><br><em>    equations, Ax=b, starting from an initial guess, ``x0``.</em><br><em>    </em><br><em>    Returns:</em><br><em>    x, the estimated solution</em><br><em>    &quot;&quot;&quot;</em><br>    <br>    n = A.shape[0]<br>    x = x0.copy()<br>    x_prev = x0.copy()<br>    counter = 0<br>    x_diff = tol+1<br>    <br>    <strong>while</strong> (x_diff &gt; tol) <strong>and</strong> (counter &lt; n_iterations): <em>#iteration level</em><br>        <strong>for</strong> i <strong>in</strong> range(0, n): <em>#element wise level for x</em><br>            s = 0<br>            <strong>for</strong> j <strong>in</strong> range(0,n): <em>#summation for i !=j</em><br>                <strong>if</strong> i != j:<br>                    s += A[i,j] * x_prev[j] <br>            <br>            x[i] = (b[i] - s) / A[i,i]<br>        <em>#update values</em><br>        counter += 1<br>        x_diff = (np.sum((x-x_prev)**2))**0.5 <br>        x_prev = x.copy() <em>#use new x for next iteration</em><br>        <br>    <br>    print(&quot;Number of Iterations: &quot;, counter)<br>    print(&quot;Norm of Difference: &quot;, x_diff)<br>    <strong>return</strong> x</pre><h4><strong>Step 2: Solve for the Unknowns</strong></h4><p>To compute the coefficients of our splines, we first define the strictly diagonally dominant matrix “A” and then apply the Jacobi Method to solve for <em>c </em>iteratively. With <em>c </em>solved,<em> b </em>and<em> d </em>can be solved arithmetically.</p><pre><strong>def</strong> cubic_spline(x, y, tol = 1e-100):<br>    <em>&quot;&quot;&quot;</em><br><em>    Interpolate using natural cubic splines.</em><br><em>    </em><br><em>    Generates a strictly diagonal dominant matrix then applies Jacobi&#39;s method.</em><br><em>    </em><br><em>    Returns coefficients:</em><br><em>    b, coefficient of x of degree 1</em><br><em>    c, coefficient of x of degree 2</em><br><em>    d, coefficient of x of degree 3</em><br><em>    &quot;&quot;&quot;</em> <br>    x = np.array(x)<br>    y = np.array(y)<br>    <em>### check if sorted</em><br>    <strong>if</strong> np.any(np.diff(x) &lt; 0):<br>        idx = np.argsort(x)<br>        x = x[idx]<br>        y = y[idx]<br><br>    size = len(x)<br>    delta_x = np.diff(x)<br>    delta_y = np.diff(y)<br>    <br>    <em>### Get matrix A</em><br>    A = np.zeros(shape = (size,size))<br>    b = np.zeros(shape=(size,1))<br>    A[0,0] = 1<br>    A[-1,-1] = 1<br>    <br>    <strong>for</strong> i <strong>in</strong> range(1,size-1):<br>        A[i, i-1] = delta_x[i-1]<br>        A[i, i+1] = delta_x[i]<br>        A[i,i] = 2*(delta_x[i-1]+delta_x[i])<br>    <em>### Get matrix b</em><br>        b[i,0] = 3*(delta_y[i]/delta_x[i] - delta_y[i-1]/delta_x[i-1])<br>        <br>    <em>### Solves for c in Ac = b</em><br>    print(&#39;Jacobi Method Output:&#39;)<br>    c = jacobi(A, b, np.zeros(len(A)), tol = tol, n_iterations=1000)<br>    <br>    <em>### Solves for d and b</em><br>    d = np.zeros(shape = (size-1,1))<br>    b = np.zeros(shape = (size-1,1))<br>    <strong>for</strong> i <strong>in</strong> range(0,len(d)):<br>        d[i] = (c[i+1] - c[i]) / (3*delta_x[i])<br>        b[i] = (delta_y[i]/delta_x[i]) - (delta_x[i]/3)*(2*c[i] + c[i+1])    <br>    <br>    <strong>return</strong> b.squeeze(), c.squeeze(), d.squeeze()</pre><h3>So, Why Natural Cubic Splines?</h3><p>In most interpolation problems, spline interpolation is often preferred to single polynomial interpolation since it produces similar results (even with low degree polynomials) while avoiding Runge’s Phenomenon for higher degrees polynomials. As for the natural boundary condition, it is a convenient way for computing the coefficients since it allows us to have an equal number of unknowns and equations to solve for.</p><h3>References</h3><p>[1] Richard L. Burden and J. Douglas Faires, <em>Numerical Analysis 9th Edition</em>, Cengage Learning</p><p>[2] Zhao Liang, <em>Numerical Methods for Economics and Finance</em> course material</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edf68feb57aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/eatpredlove/natural-cubic-splines-implementation-with-python-edf68feb57aa">Natural Cubic Splines Implementation with Python</a> was originally published in <a href="https://medium.com/eatpredlove">eat-pred-love</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>