<?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 Austin Wolff on Medium]]></title>
        <description><![CDATA[Stories by Austin Wolff on Medium]]></description>
        <link>https://medium.com/@austinwolff?source=rss-db21aa43a93e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*S-fW9UAlVq8xgFzcgJfhOw.jpeg</url>
            <title>Stories by Austin Wolff on Medium</title>
            <link>https://medium.com/@austinwolff?source=rss-db21aa43a93e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:33:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@austinwolff/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[Ranking The Best MSAs in 2024 for Real Estate Investment]]></title>
            <link>https://medium.com/@austinwolff/ranking-the-best-msas-in-2024-for-real-estate-investment-50d085fbcdaf?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/50d085fbcdaf</guid>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[real-estate-investments]]></category>
            <category><![CDATA[real-estate-data]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Wed, 01 May 2024 23:30:08 GMT</pubDate>
            <atom:updated>2024-05-01T23:30:08.684Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oFu9XEIBxBUND3NR" /></figure><p>What are the best MSAs for Real Estate Investment in 2024? My previous analyses have been read by multi-billion dollar firms, so I decided it was time to update the rankings and add a few more filters.</p><p>I gathered job market, home price, and rental price data for each MSA, and created an algorithm to rank the results.</p><p>You may have read my previous post where I ranked the MSAs by job growth alone. <a href="https://www.linkedin.com/pulse/real-estate-data-science-ranking-msas-job-growth-only-austin-wolff-zle2f/?trackingId=WI%2BNBNQ2Q7WQnj2ZAZksMw%3D%3D&amp;trk=article-ssr-frontend-pulse_little-text-block">You can read that article here</a> .</p><p>As promised, I’ll now be adding in price and rent data, as well as additional filtering using average insurance and property tax rates. Here’s a sneak peak at the data used:</p><p><strong>Variables used for ranking:</strong></p><ol><li>Job Growth (U.S. Bureau of Labor Statistics) [1]</li><li>Price (Zillow’s ZHVI — “Typical Home Value”) [2]</li><li>Rent (Zillow’s ZORI — “Observed Rent”) [2]</li></ol><p><strong>Variables used for further filtering:</strong></p><ol><li>Average homeowners insurance (web-scraped)</li><li>Average property tax rate (web-scraped)</li><li>Total Jobs (U.S. Bureau of Labor Statistics)</li><li>Price (Zillow’s ZHVI — “Typical Home Value”)</li></ol><p>The U.S. Bureau of Labor Statistics (BLS) and Zillow both offer data up to the most recent month, which is why I’ll be using their datasets as opposed to something like the U.S. American Community Survey datasets, which are always outdated by at least 1 year.</p><h3>Ranking By Job Growth Only</h3><p>Using the ranking algorithm I discuss in <a href="https://www.linkedin.com/pulse/creating-etl-data-pipeline-using-airflow-austin-wolff/?trackingId=HVmSWDWRSV2mGOknjjBO2g%3D%3D&amp;trk=article-ssr-frontend-pulse_little-text-block">very technical</a> , our initial top 10 MSAs ranked only by their Average Monthly Growth, from 2015–2024, are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/0*H8xzCDRUJ3XQIk7f" /></figure><p>Almost every column should be straightforward. The <strong>average_pct_Jobs</strong> column measures the average percent of job growth an MSA experiences per month. The <strong>average_value_Jobs</strong> columns measures the average number of jobs added per month.</p><p>Now we’ll be adding some filters to the data.</p><h3>Filtering By Homeowners Insurance</h3><p>There are certain parts of the country where homeowners insurance has risen dramatically over the past 10 years, and will likely continue to rise due to various climate risks. I want to remove all states with the highest insurance.</p><p>I used a metric called the third quartile to remove the top 25% of states with the highest insurance.</p><p><em>Note: The third quartile is similar to the median (also known as the “2nd quartile”), but instead of being the “middle” or “50th percentile” number, the third quartile is the “number at the 75th percentile”. If we filter for numbers below the third quartile, we are left with the bottom 75% of our data, effectively removing the top 25%.</em></p><p>Here are the top MSAs we are left with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*HaTE-iBe7RlecwkO" /></figure><h3>Filtering By Property Tax Rate</h3><p>When I was crunching numbers for an investment in Texas, I personally felt the sting of their high property tax. This, in addition to high interest rates, virtually killed every deal I was looking at. So I’ll also be filtering out the top 25% of states with the highest property tax.</p><p>Here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*T20KFMrLt3-BDtqD" /></figure><p>There was no change.</p><h3>Filtering By Number of Jobs</h3><p>I also want to exclude small MSAs from this analysis, so I’ll remove all metros with less than 250,000 jobs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*ZhWIDKHO3xb63so8" /></figure><p>Now let’s rank by price growth only.</p><h3>Ranking By Price Growth Only</h3><p>After applying the same filters as above (insurance, property tax, and minimum job count), here are the top ten MSAs ranked by Average Monthly Price Growth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*oQ3l2bs7TRWDCb5C" /></figure><p>You’ll notice the first MSA on our list, Boise, starts at index #21. That means there were 21 other MSAs with a higher price appreciation that were filtered out due to insurance, taxes, or it being a relatively small metro (unsurprisingly to me, many of these metros were in Florida).</p><p>But what happens if we rank for job growth and price growth together?</p><h3>Ranking By Job &amp; Price Growth</h3><p>In order to rank by both metrics, I will be assigning a weight to both of them. To make things most simple, I am assigning both “jobs” and “price” a weight of 1 so they are weighted equally.</p><p>Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*vc0R4bOhnVcG3w3R" /></figure><p>Now let’s add the same filters as above (insurance, tax, minimum number of jobs):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*WPgtnb7zNXs2HIbA" /></figure><h3>Ranking By Job, Rent, &amp; Price Growth</h3><p>Now let’s rank by Job Growth, Price Growth, and Rent Growth. I adjusted the weights, giving Jobs a weight of 2, Price a weight of 1, and Rent a weight of 0.5, and here’s why:</p><ol><li>Job Growth: It is relatively undisputed that job growth is one of the most important leading indicators of city growth, including price appreciation and rent growth. Therefore, job growth gets the highest weight.</li><li>Price Growth: I also care about my investment appreciating faster relative to other metros. Hence, a weight of 1.</li><li>Rent Growth: There are certain big metros that have declining rents at the moment due to oversupply. As a renter in Los Angeles, I wish this were true of my MSA. But as a real estate investor, I don’t want the income of my property declining, so adding a weight to rent growth somewhat accounts for this. It is, in the long run, not as important to me, hence the 0.5 weight.</li></ol><p>Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*wu7lvnjCevnpRgfQ" /></figure><p>Seeing a pattern here? Let’s filter the results down (again, using insurance, tax rate, and minimum number of jobs):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*ZfVT84byDioYKPq4" /></figure><p>If we filter this list for the top 10 metros with respect to just Average Monthly Job Growth, and then run another filter for the top 10 metros for Average Monthly Price Growth, the only MSAs that are on both top 10 lists are:</p><ol><li>Boise, ID</li><li>Nashville, TN</li><li>Phoenix, AZ</li></ol><p>Again, remember that Texas and Florida have been filtered out due to high insurance and property taxes. If I leave them in, there are only 2 metros on both top 10 lists:</p><ol><li>Boise, ID</li><li>Lakeland, FL</li></ol><p>And if I remove the last filter (MSAs must have more than 250,000 jobs), the metros on both top 10 lists are:</p><ol><li>Boise, ID</li><li>Idaho Falls, ID</li><li>Lakeland, FL</li></ol><p>Interesting, right?</p><h3>Filtering For First-Time Investors</h3><p>Many first-time investors may not have the cash on hand to invest in the booming, primary metros.</p><p>Let’s rank for job growth only. I’m also only going to filter by one metric: the MSAs must have a median price of less than $400,000. Let’s see the top 10 results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*eU3gGTf-OymtlA4w" /></figure><p>Now let’s rank for job and price growth, while still keeping our maximum price filter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/0*vIckw8KJWij0M_sF" /></figure><p>Now let’s rank for job, price, and rent growth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*KLcpRu7u2hxWcWnK" /></figure><p>And for anyone curious what the rankings look like if we filter out the high tax and high insurance states again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/0*mGRoB_A2hm8VNxKa" /></figure><h3>Conclusion</h3><p>As part of my personal investing thesis, I’d rather not have to deal with climate risk and high insurance affecting my properties, which rules out a lot of the highest ranking metros (most in Florida). I’ve also had high property taxes affect my ability to cash flow in Texas. However, there are many investors making great returns in these areas. If you’d like to filter the data yourself, please let me know in the comments. I may build a public dashboard for anyone to filter these results.</p><p>It may be a good idea to also analyze the number of new units being added into the MSA over time as well. It’s possible there’s a metro whose growth rate far exceeds the number of new units being brought online, even if it’s a secondary MSA that doesn’t rank high in our current analysis. In this case, it’s possible that a mid-tier MSA may be a better place to invest or build simply due to extreme lack of inventory. I will need to examine this in the future.</p><p>In the meantime, next I will be looking at the best zip codes to invest in for each of the top MSAs. Follow me to get updated when I release the next real estate investment analysis by zip code.</p><h3>Do You Want To Filter The Results Yourself?</h3><p>I’m considering building a public dashboard where anyone can adjust the ranking and filtering mechanisms to their own taste. If this sounds like something you’d like, please let me know in the comments. If enough people comment on this, I’ll make a public, adjustable dashboard!</p><h3>Are You A Recruiter?</h3><p>If you’re a recruiter looking to hire a Real Estate Data Scientist or Data Engineer, feel free to reach out. The code I used is in a private Github repo, but can be made available upon request.</p><h3>Sources</h3><p>[1] <a href="https://www.bls.gov/bls/api_features.htm">U.S. Bureau of Labor Statistics</a></p><p>[2] <a href="https://www.zillow.com/research/data/">Zillow Housing Data</a></p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/ranking-best-msas-2024-real-estate-investment-austin-wolff-bniuc"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50d085fbcdaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real Estate Data Science: Ranking MSAs by Job Growth Only]]></title>
            <link>https://medium.com/@austinwolff/real-estate-data-science-ranking-msas-by-job-growth-only-1f7045c3f7b5?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f7045c3f7b5</guid>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[real-estate-investments]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 19:26:28 GMT</pubDate>
            <atom:updated>2024-04-30T19:47:33.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HA4l24vq8W_C2pxo" /></figure><p>There are many variables to help you analyze the top MSAs you should be investing in. However, one of the largest contributors to city growth is job opportunities. The more jobs a city adds, the more the population seems to grow, and home prices and rents seem to grow in tandem.</p><p>I will be using data from the U.S. Bureau of Labor Statistics (BLS) to help rank which MSAs are growing the fastest relative to their size. A small MSA may grow extremely fast relative to its small population, but for a multitude of reasons outside of the scope of this article, I am staying away from investing in small MSAs (less than 250,000 jobs).</p><h3>Extracting The Dataset</h3><p>I’ve created a special function to download the jobs dataset from the BLS API that also creates a column called “interpolated” where the impact of the COVID anomaly is smoothed out.</p><pre># Read in the smoothed job dataset<br>jobs_smooth = pd.read_csv(<br>    &#39;datasets/bls/smoothed/most_recent_bls_covid_smoothed.csv&#39;)<br><br>jobs_smooth[&#39;date&#39;] = pd.to_datetime(jobs_smooth[&#39;date&#39;])<br><br># Keep only necessary columns<br>jobs_smooth = jobs_smooth[[&#39;msa_name&#39;,&#39;date&#39;,&#39;year&#39;,&#39;value&#39;,&#39;interpolated&#39;]]<br><br>jobs_smooth</pre><pre>OUTPUT:<br><br>  msa_name    date       year value        interpolated<br>0 Abilene, TX 2024-03-01 2024 77400.000000 77400.000000<br>1 Abilene, TX 2024-02-01 2024 77300.000000 77300.000000<br>2 Abilene, TX 2024-01-01 2024 77200.000000 77200.000000<br>3 Abilene, TX 2023-12-01 2023 77100.000000 77100.000000<br>4 Abilene, TX 2023-11-01 2023 77400.000000 77400.000000<br>... ... ... ... ... ...<br>43285 Yuma, AZ 2015-05-01 2015 53100.000000 53100.000000<br>43286 Yuma, AZ 2015-04-01 2015 53000.000000 53000.000000<br>43287 Yuma, AZ 2015-03-01 2015 52800.000000 52800.000000<br>43288 Yuma, AZ 2015-02-01 2015 53000.000000 53000.000000<br>43289 Yuma, AZ 2015-01-01 2015 53000.000000 53000.000000<br><br>43290 rows × 5 columns</pre><p>The dataset has 5 columns:</p><ol><li>msa_name: The MSA name,</li><li>date: The date,</li><li>year: The year (this will be useful later),</li><li>value: The number of jobs estimated by the U.S. BLS, and</li><li>interpolated: The same as the value column, except values between April 2020 and April 2022 have been linearly interpolated to smooth over the COVID anomaly.</li></ol><h3>Preparing The Dataset</h3><p>I only want to analyze MSAs that had more than 250,000 jobs at their peak (simply including smaller MSAs skews the data towards them if we rank for speed of growth without also ranking for size).</p><pre>### Now we will remove MSAs with less than 250,000 jobs<br><br># Create a dictionary that matches each MSA <br># to its maximum job number<br>msa_names = jobs_smooth[&#39;msa_name&#39;].unique()<br>msa_max_dict = {}<br>for msa in msa_names:<br>    max_jobs = jobs_smooth[jobs_smooth[&#39;msa_name&#39;]==msa][&#39;value&#39;].max()<br>    msa_max_dict[msa] = max_jobs<br>    <br># Get this dictionary into a dataframe<br>max_jobs = pd.DataFrame.from_dict(<br>    msa_max_dict, orient=&#39;index&#39;, columns=[&#39;max&#39;]<br>).reset_index().rename(columns={&#39;index&#39;:&#39;msa_name&#39;})<br><br># Filter for only bigger towns, where number of jobs is over 250,000<br>job_limit = max_jobs[max_jobs[&#39;max&#39;]&gt;=250_000].copy()<br><br># Get the msa names<br>job_limit_msa_names = job_limit[&#39;msa_name&#39;].unique()<br><br># Filter to only keep the MSAs with more than 250,000 jobs<br>mask = jobs_smooth[&#39;msa_name&#39;].isin(job_limit_msa_names)<br>jobs_250 = jobs_smooth[mask].reset_index(drop=True).copy()<br><br>jobs_250</pre><pre>OUTPUT:<br><br>  msa_name  date       year value       interpolated<br>0 Akron, OH 2024-03-01 2024 341000.0000 341000.0000<br>1 Akron, OH 2024-02-01 2024 339600.0000 339600.0000<br>2 Akron, OH 2024-01-01 2024 339800.0000 339800.0000<br>3 Akron, OH 2023-12-01 2023 339800.0000 339800.0000<br>4 Akron, OH 2023-11-01 2023 338600.0000 338600.0000<br>... ... ... ... ... ...<br>11650 Worcester, MA 2015-05-01 2015 278000.0000 278000.0000<br>11651 Worcester, MA 2015-04-01 2015 276600.0000 276600.0000<br>11652 Worcester, MA 2015-03-01 2015 276200.0000 276200.0000<br>11653 Worcester, MA 2015-02-01 2015 275300.0000 275300.0000<br>11654 Worcester, MA 2015-01-01 2015 275800.0000 275800.0000<br><br>11655 rows × 5 columns</pre><h3>Ranking by the Linear Regression Coefficient</h3><p>The next step is to make a ranking algorithm that ranks each MSA according to the weights we specify.</p><p>Using the BLS dataset, which lists estimates for the number of jobs on a monthly level, from January 2015 to March 2024, for MSAs whose maximum number of jobs at a given time is above 250,000, we use linear regression to find the slope of growth for each MSA.</p><p>Then we can rank each MSA by its linear regression coefficient.</p><p><strong>But first, what is linear regression?</strong></p><p>Linear regression is used in statistics and machine learning to predict a dependent variable (such as job growth) based on an independent variable (such as time). In our case, the higher the “coefficient” used in our “line of best fit” (found using linear regression), the faster an MSA grows over time.</p><p>Now I’m going to show you the results of our ranking — this might be information overload at first, so I will explain each column and why it’s there below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*jYY8vZbdEGp49hIU" /><figcaption>The top 10 MSAs, ranked by the rate of job growth.</figcaption></figure><p>There are two columns in particular that aren’t immediately recognizable:</p><ol><li>trend_coef_Jobs, and</li><li>average_value_Jobs</li></ol><p>Let’s talk about <strong>average_value_Jobs</strong> first. This is the average amount of new jobs an MSA adds per month. We could’ve ranked the MSAs by this number. But the rankings would skew towards bigger MSAs, even if they aren’t growing as fast.</p><p>The <strong>trend_coef_Jobs</strong> column is the linear regression coefficient, and I’ve ranked the MSAs by this column. Let’s graph the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HpRbmLAel3KtaUAJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*czQhph576hTBvKki" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l5pHEtwsEamuKR-E" /></figure><p>The graph on the right is the percent of growth per month. Due to the COVID anomaly, which resulted in an enormous percentage drop in employment (coupled with an enormous percentage growth), the graph is somewhat hard to read.</p><p>I mentioned an article above where I smoothed the COVID anomaly out of our time series data, with the downside of losing any meaningful data from April 2020 to April 2022 with respect to percent growth. This is a tradeoff I’m willing to make for readability. Let’s graph these MSAs again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xqNPEmKY0dsp-Tti" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OTgCbp0Q1bwdNPIY" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZPmHCjTOcgqjCPC" /></figure><p>Because linear interpolation was used to predict the job numbers between April 2020 and April 2022 using linear regression, I’ve artificially created a dataset where there is constant growth between these dates. Because the growth is constant, you’ll notice in the rightmost graph that the growth percentage is also constant between these dates. I personally don’t mind this cleaning and smoothing of our time-series dataset, and will use this technique for all graphs in the article moving forward.</p><p>We’ve ranked the MSAs by their linear regression coefficient, but it still indexes a bit based on pre-existing size. Let’s now rank the MSAs with a more commonly used metric: Average Annual Growth Rate.</p><h3>Ranking MSAs based on Average Monthly Growth Rate</h3><p>Using the average percentage of monthly growth between the years 2015–2024, we arrive at this ranking for each MSA:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*EZxWrB1RwkFSgMku" /></figure><p>Because this is calculated based on months, the <strong>average_pct_Jobs</strong> column tells us there is an average 0.34% growth in jobs for the Austin, TX MSA each month. The <strong>average_value_Jobs</strong> tells us there is an average of 3,710 new jobs added to the Austin, TX metro each month.</p><p>Let’s graph the top 5 (smoothed) results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pUnbvvs085AiYSdD" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S5M2fwbZYw7tuYgb" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UCMO7YTIDL06r7I4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CWNQSwzojxa6CXo1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PrS4s3VOrdbsrG5c" /></figure><p>This ranking is fine, but one thing I notice is Austin, TX has considerably more jobs than the next top 4. Let’s filter the results and only keep the MSAs with more than 500,000 jobs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/0*d2eQ-Ci3V5EoK3QO" /></figure><p>Now let’s graph the new top 5 (smoothed) results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l6VKbTGU1MS2yvJv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mKTUjrnb6SQLbSxa" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IftwOwgmF_oi0Ji3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w8_EagZfwNCYO5Gf" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VKr3Pd82FRbqFKDP" /></figure><h3>Conclusion</h3><p>Future studies on the type of jobs (and education-level required) may be warranted. An MSA that has more additional jobs in technology may see greater price appreciation than an MSA where the job growth is primarily in other industries.</p><p>In addition, more variables may need to be included to further evaluate which MSAs may offer the best real estate investment returns, such as: price appreciation, rent growth, property tax rates, and insurance premiums. Follow me to get notified when I incorporate these variables into the MSA rankings.</p><h3>Additional Code Used</h3><p>My Github repo is private, but if you’re a recruiter looking for a Data Scientist or Data Engineer, don’t hesitate to reach out and ask to see it.</p><p>I’ll be including some functions used for this article below.</p><h4>The Linear Regression Function</h4><pre># Define helper function that runs linear regression<br>def run_lr(df, column):<br>    &quot;&quot;&quot;<br>    Run linear regression on time-series data <br>    and return the coefficient and intercept.<br>    <br>    Arguments<br>    -----------<br>        df (DataFrame): A dataframe that contains the<br>            target column and an &#39;ordinal_date&#39; column<br>            that was created by a time-series column in <br>            the format of &quot;%Y-%m-%d&quot; and making it ordinal,<br>            such as running the code below in some other <br>            step. <br>            <br>            EXAMPLE...<br>            # Create ordinal column<br>            df[&#39;ordinal_date&#39;] = df[&#39;date&#39;].map(<br>                datetime.toordinal)<br>                <br>        column (str): The name of the target column.<br>            <br>    Returns<br>    -----------<br>        coef (float): The coefficient of the linear<br>            equation calculated.<br>        <br>        intercept (float): The y-intercept of the linear<br>            equation calculated.<br>    <br>    &quot;&quot;&quot;<br>    # Run linear regression<br>    normal_lr = LinearRegression()<br>    X = df[[&#39;ordinal_date&#39;]]<br>    y = df[column]<br>    normal_lr.fit(X, y)<br>    coef = normal_lr.coef_[0]<br>    intercept = normal_lr.intercept_<br><br>    # Return lr coefficient<br>    return coef, intercept</pre><h4>The Ranking Function</h4><pre>### MAKE FUNCTION THAT MAKES A TOTAL RANK <br>### BASED ON MULTIPLE DEMOGRAPHICS FROM <br>### THE Zillow AND BLS DATASETS<br><br>def make_zillow_ranking(<br>    df_dict,<br>    all_df_dict={<br>        &quot;Jobs&quot;:[jobs_250],<br>        &quot;Median Rent&quot;:[zillow_rent],<br>        &quot;Median Price&quot;:[zillow_price],<br>    },<br>    max_price=False,<br>    min_rent_to_price=False,<br>    use_total_trend=True,<br>    use_average_percent=True,<br>    use_pct_trend=False,<br>    total_trend_weight_dict={},<br>    average_percent_weight_dict={},<br>    plot_graphs=False<br>):<br>    &quot;&quot;&quot;<br>    This function ranks the invest-ability of every<br>    city based on the demographics passed. It<br>    analyzes the total average growth per year, as <br>    well as the relative average growth per year<br>    (measured as the average percent growth per year).<br>    <br>    Arguments<br>    -----------<br>        df_dict (dict): A dictionary to be used if you<br>            want to combine multiple dataframes for analysis<br>            and plotting. If using this, the key should be<br>            a string with the demographic name, and the value<br>            should be a list containing the dataframe in position<br>            0, and the beginning year in position 1. See below<br>            for two examples...<br>            <br>            Example 1, One Extra Dataframe<br>            {&quot;Median Rent&quot;: [median_rent_df, 2013]}<br>            <br>            Example 2, Multiple Extra Dataframes<br>            {&quot;Median Rent&quot;: [median_rent_df, 2013],<br>            &quot;Population&quot; : [population_df, 2013]}<br>            <br>        max_price (int): If you only want to measure and<br>            compare MSAs up to a certain median price,<br>            enter the max median price as an integer.<br>            <br>        min_rent_to_price (float): If you only want to measure and<br>            compare MSAs up to a certain rent-to-price ratio<br>            (based on median rent and median price values),<br>            enter the minimum rent-to-price ratio as a float.<br>            <br>        use_total_trend (True/False): Set to True if you&#39;d like<br>            to include the total trend weights in the ranking<br>            of MSAs. Use False if not.<br>        <br>        use_average_percent (True/False): Set to True if you&#39;d like<br>            to include the average percent weights in the ranking<br>            of MSAs. Use False if not.<br>        <br>        total_trend_weight_dict (dict): A dictionary to set the<br>            weights of each demo. For example, if you&#39;d like to<br>            multiply the &quot;Median Rent&quot; weights by 2, giving a bigger<br>            weight to the &quot;Median Rent&quot; demographic, all you need<br>            is to make the key &quot;Median Rent&quot; set to a value of 2.<br>            This dictionary is specifically for total trend weights.<br>            See the example below.<br>            <br>            EXAMPLE...<br>            total_trend_weight_dict={<br>                &quot;Jobs&quot;:1,<br>                &quot;Median Rent&quot;:1}<br>        <br>        average_percent_weight_dict (dict): A dictionary to set the<br>            weights of each demo. For example, if you&#39;d like to<br>            multiply the &quot;Median Rent&quot; weights by 2, giving a bigger<br>            weight to the &quot;Median Rent&quot; demographic, all you need<br>            is to make the key &quot;Median Rent&quot; set to a value of 2.<br>            This dictionary is specifically for average percent weights.<br>            See the example below.<br>            <br>            EXAMPLE...<br>            average_percent_weight_dict={<br>                &quot;Jobs&quot;:3,<br>                &quot;Median Rent&quot;:3}<br>                <br>        plot_graphs (True/False): If True, ask for user inputs<br>            and run the plot_top_10_cities() function.<br>            <br>    Returns<br>    -----------<br>        final_df (DataFrame): A dataframe with each city<br>            sorted by total rank.<br>    &quot;&quot;&quot;<br>    # Make a list to add each dataframe to<br>    df_list = []<br>    <br>    # Rename all columns by appending the demo name,<br>    # except for the MSA name and date, which we will <br>    # use as the key to merge all dataframes.<br>    for demo in df_dict:<br>        <br>        # Get dataframe<br>        df = df_dict[demo][0][[&#39;msa_name&#39;,&#39;date&#39;,&#39;value&#39;,&#39;year&#39;]].copy()<br>        <br>        # Rename every column except for msa_name<br>        for col in df.columns:<br>            if (col != &#39;msa_name&#39;) &amp; (col != &#39;date&#39;):<br>                df.rename(<br>                    columns={col:f&#39;{col}_{demo}&#39;}, <br>                    inplace=True)<br>                <br>        # Add dataframe to list<br>        df_list.append(df)<br>                <br>    # Merge all dataframes<br>    merged_df = reduce(lambda left, right: <br>                       pd.merge(left, right, <br>                                left_on=[&#39;msa_name&#39;,&#39;date&#39;], <br>                                right_on=[&#39;msa_name&#39;,&#39;date&#39;],<br>                                suffixes=(None, &quot;_y&quot;),<br>                                how=&quot;outer&quot;), df_list)<br>            <br>    # Loop through columns and clean out the rest<br>    for col in merged_df.columns:<br>        if (&#39;month_&#39; in col) | (&#39;series_id_&#39; in col):<br>            merged_df.drop(columns=[col], inplace=True)<br>    <br>    # Create new df to store coefficients<br>    coef_df = pd.DataFrame(<br>        data=None, columns=[&#39;msa_name&#39;])<br>    <br>    # Add columns for every demo<br>    for demo in df_dict:<br>        coef_df[f&#39;trend_coef_{demo}&#39;] = None<br>        coef_df[f&#39;average_value_{demo}&#39;] = None<br>        coef_df[f&#39;pct_coef_{demo}&#39;] = None<br>        coef_df[f&#39;average_pct_{demo}&#39;] = None<br>        <br>    # Make temporary coef_df to use later<br>    temp_coef_1 = coef_df.copy()<br>        <br>    # Create ordinal column<br>    merged_df[&#39;ordinal_date&#39;] = merged_df[&#39;date&#39;].map(datetime.toordinal)<br>    <br>    # Loop through all cities<br>    for city in merged_df[&#39;msa_name&#39;].dropna().unique():<br><br>        # Isolate just that city<br>        df = merged_df[merged_df[&#39;msa_name&#39;]==city].copy()<br>        <br>        # Sort by date<br>        df = df.sort_values(&#39;date&#39;)<br>        <br>        # Make duplicate<br>        temp_coef_2 = temp_coef_1.copy()<br>        <br>        # Set temp coef_df<br>        temp_coef_2.loc[len(temp_coef_2.index)] = np.nan<br>        temp_coef_2[&#39;msa_name&#39;] = city<br>        <br>        # Loop through each demo<br>        for demo in df_dict:<br>            <br>            # Test to see if there&#39;s data for the demo<br>            if df[df[f&#39;year_{demo}&#39;].notna()].shape[0] &gt; 0:<br>                <br>                # Make copy<br>                df_temp = df.copy()<br><br>                # Get beginning year<br>                begin_year = df_dict[demo][1]<br><br>                # Filter by beginning year minus 1<br>                df_temp = df[df[f&#39;year_{demo}&#39;]&gt;=begin_year-1].reset_index(drop=True)<br><br>                # Create difference column<br>                df_temp[f&#39;value_change_{demo}&#39;] = df_temp[f&#39;value_{demo}&#39;].diff()<br><br>                # Create pct_change column<br>                df_temp[f&#39;percent_change_{demo}&#39;] = df_temp[f&#39;value_{demo}&#39;].pct_change()<br><br>                # Filter by beginning year<br>                df_temp = df_temp[<br>                    df_temp[f&#39;year_{demo}&#39;]&gt;=begin_year].reset_index(drop=True)<br><br>                # If an MSA&#39;s most recent year is after the beginning<br>                # year, remove it from the graphs. For example, if we want to<br>                # view the growth of all cities since 2016, but Prescott Valley<br>                # only has data starting at 2019, this may skew the data.<br>                if df_temp[f&#39;year_{demo}&#39;].iloc[0] != begin_year:<br>                    continue<br><br>                # Remove NaN values<br>                df_temp = df_temp[df_temp[f&#39;percent_change_{demo}&#39;].notna()]<br><br>                # Run linear regression<br>                coef_value, intercept_value = run_lr(df_temp, column=f&#39;value_{demo}&#39;)<br>                coef_pct, intercept_pct = run_lr(df_temp, column=f&#39;percent_change_{demo}&#39;)<br><br>                # Create trend columns<br>                df_temp[f&#39;value_trend_{demo}&#39;] = df_temp[&#39;ordinal_date&#39;]*coef_value + intercept_value<br>                df_temp[f&#39;percent_change_trend_{demo}&#39;] = df_temp[&#39;ordinal_date&#39;]*coef_pct + intercept_pct<br><br>                # Create averages column<br>                the_average_pct = df_temp[f&#39;percent_change_{demo}&#39;].mean()<br>                df_temp[f&#39;average_pct_{demo}&#39;] = the_average_pct<br>                the_average_value = df_temp[f&#39;value_change_{demo}&#39;].mean()<br>                df_temp[f&#39;average_value_{demo}&#39;] = the_average_value<br><br>                # Update temp coef<br>                temp_coef_2[f&#39;trend_coef_{demo}&#39;] = coef_value<br>                temp_coef_2[f&#39;average_value_{demo}&#39;] = the_average_value<br>                temp_coef_2[f&#39;pct_coef_{demo}&#39;] = coef_pct<br>                temp_coef_2[f&#39;average_pct_{demo}&#39;] = the_average_pct<br><br>        # Append temp coef to dataframe<br>        coef_df = pd.concat([coef_df, temp_coef_2])<br>            <br>    # Drop duplicates<br>    coef_df = coef_df.drop_duplicates().reset_index(drop=True)<br>    <br>    # Drop MSAs that have missing values (they will have missing<br>    # values if we couldn&#39;t join Census MSAs with BLS MSAs which<br>    # only occurs for a few specific MSAs)<br>    bad_msa = set()<br>    <br>    for demo in df_dict:<br>        <br>        # Filter by nulls<br>        coef_temp = coef_df[coef_df[f&#39;trend_coef_{demo}&#39;].isnull()]<br>        <br>        # Get list of MSAs<br>        bad_msa.update(coef_temp[&#39;msa_name&#39;].unique())<br>        <br>        # Filter by nulls<br>        coef_temp = coef_df[coef_df[f&#39;pct_coef_{demo}&#39;].isnull()]<br>        <br>        # Get list of MSAs<br>        bad_msa.update(coef_temp[&#39;msa_name&#39;].unique())<br>        <br>    # Remove these cities<br>    if len(bad_msa) &gt; 0:<br>        <br>        # Remove cities in bad_msa<br>        coef_df = coef_df[~coef_df[&#39;msa_name&#39;].isin(bad_msa)].reset_index(drop=True)<br>        <br>    # Create the rankings for each demographic<br>    for demo in df_dict:<br>        <br>        # Calculate rankings for both, then sort by the total<br>        # ranking. For example, if a city has the highest average<br>        # percent change, it will get a ranking of &quot;1&quot; for average_pct,<br>        # and if it has the 8th highest trend coefficient, it will<br>        # get a ranking of &quot;8&quot; for trend_coef. When we add those two<br>        # rankings together, the city will have a total ranking<br>        # of &quot;9&quot;. In this case, the lower the ranking, the better,<br>        # and we will sort total rankings from lowest to highest.<br>        <br>        # Normalize total trend column<br>        coef_df[f&#39;normalized_trend_coef_{demo}&#39;] = normalize_column(<br>            coef_df[f&#39;trend_coef_{demo}&#39;], min_max_standardized=True)<br>        <br>        # Normalize pct trend column<br>        coef_df[f&#39;normalized_pct_coef_{demo}&#39;] = normalize_column(<br>            coef_df[f&#39;pct_coef_{demo}&#39;], min_max_standardized=True)<br>        <br>        # Normalize avg pct column<br>        coef_df[f&#39;normalized_average_pct_{demo}&#39;] = normalize_column(<br>            coef_df[f&#39;average_pct_{demo}&#39;], min_max_standardized=True)<br>        <br>        # Check to see if there are weights, and if not,<br>        # set each weight to 1<br>        if demo in total_trend_weight_dict.keys():<br>            trend_weight = total_trend_weight_dict[demo]<br>        else:<br>            trend_weight = 1<br>            <br>        # Check pct weight dict<br>        if demo in average_percent_weight_dict.keys():<br>            pct_weight = average_percent_weight_dict[demo]<br>        else:<br>            pct_weight = 1<br>            <br>        # Re-adjust weights based on whether we are using<br>        # only total trend, only percent, or both. As an example, <br>        # if we aren&#39;t using percent, we set the weight to 0, that<br>        # way the percent weight isn&#39;t used when totalling the<br>        # demographic&#39;s weight.<br>        if use_total_trend == False:<br>            trend_weight = 0<br>        if use_average_percent == False:<br>            pct_weight = 0<br>            <br>        <br>        ### Create weights<br>        <br>        # If we want to rank based on % change trend<br>        if use_pct_trend:<br>            coef_df[f&#39;{demo}_weight&#39;] = (<br>                (coef_df[f&#39;normalized_trend_coef_{demo}&#39;] * trend_weight) <br>                + (coef_df[f&#39;normalized_pct_coef_{demo}&#39;] * pct_weight)<br>            )<br>            <br>        # Otherwise rank on average % growth<br>        else:<br>            coef_df[f&#39;{demo}_weight&#39;] = (<br>                (coef_df[f&#39;normalized_trend_coef_{demo}&#39;] * trend_weight) <br>                + (coef_df[f&#39;normalized_average_pct_{demo}&#39;] * pct_weight)<br>            )<br><br>    # Make final total rank column by adding up<br>    # all demo total rankings<br>    coef_df[&#39;total_weight&#39;] = 0<br>    for demo in df_dict:<br>        coef_df[&#39;total_weight&#39;] += coef_df[f&#39;{demo}_weight&#39;]<br><br>    # Sort by total weight, highest to lowest<br>    final_df = coef_df.sort_values(<br>        &#39;total_weight&#39;, ascending=False).reset_index(drop=True)<br>    <br>    # Add the values back in<br>    for demo in all_df_dict:<br>        <br>        # Get dataframe<br>        df = all_df_dict[demo][0][[&#39;msa_name&#39;,&#39;date&#39;,&#39;value&#39;,&#39;year&#39;]].copy()<br>        <br>        # Make sure the date column is in datetime format<br>        df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;])<br>        <br>        # Get most recent date and filter for it<br>        recent_date = df[&#39;date&#39;].max()<br>        new_dataframe = df[df[&#39;date&#39;]==recent_date].copy().reset_index(drop=True)<br>        <br>        # Only keep certain columns<br>        new_dataframe = new_dataframe[[&#39;msa_name&#39;,&#39;value&#39;]]<br>        <br>        # Rename column<br>        new_dataframe.rename(columns={&#39;value&#39;:f&#39;{demo}&#39;}, inplace=True)<br>        <br>        # Merge to final_df<br>        final_df = final_df.merge(new_dataframe, how=&#39;left&#39;, on=&#39;msa_name&#39;)<br>        <br>    # Create rent-to-price ratio<br>    final_df[&#39;rent_price_ratio&#39;] = final_df[&#39;Median Rent&#39;]/final_df[&#39;Median Price&#39;]<br>    <br>    <br>    # If max price, filter it<br>    if max_price:<br>        final_df = final_df[final_df[&#39;median_price&#39;]&lt;=max_price].reset_index(drop=True)<br>        <br>    # If min rent-price ratio, filter<br>    if min_rent_to_price:<br>        final_df = final_df[final_df[&#39;rent_price_ratio&#39;]&gt;=min_rent_to_price].reset_index(drop=True)<br><br>    return final_df</pre><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/real-estate-data-science-ranking-msas-job-growth-only-austin-wolff-zle2f/?trackingId=JP%2BQdBDGQEWP2jRLLoXfSg%3D%3D"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f7045c3f7b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time-Series: Removing COVID from the BLS Jobs Dataset]]></title>
            <link>https://medium.com/@austinwolff/time-series-removing-covid-from-the-bls-jobs-dataset-8b5de97bbda2?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b5de97bbda2</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[data-science-real-estate]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 05:13:10 GMT</pubDate>
            <atom:updated>2024-04-26T05:13:10.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4IiDIPJTr0FZRAKgMahCg.png" /><figcaption>Smoothing the COVID anomaly on our time-series data via linear interpolation</figcaption></figure><p>The COVID pandemic resulted in a catastrophic dip in employment, recorded in the Bureau of Labor Statistics’ (BLS) total employment dataset as of April 1st, 2020 (a few weeks after the lockdown began).</p><p>This time-series anomaly has affected my MSA-ranking algorithm, as there is a sharp deceleration of job growth in 2020, then a sharp acceleration in 2021. This sharp acceleration in 2021 means that if I only want to analyze job growth from 2021, any MSA that recovered quickly in 2021 would then see a deceleration of job growth from 2021–2024, as no MSA could ever “grow” as quickly as they did during the 1-year post-COVID job-recovery period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwPFQ1UUi-UKz2c7rL9CrA.png" /><figcaption>The graph on the right, percent-change-in-jobs, clearly illustrates the anomaly’s impact.</figcaption></figure><p><strong>I am trying to measure and rank job growth acceleration across MSAs for purposes of real estate investment, and would therefore like to reduce (or remove) the impact COVID had on the deceleration-and-acceleration of job growth.</strong></p><p>For simplicity, I will be deleting all data between April, 2020 and April, 2021, and use a time-series smoothing technique called interpolation to replace the data, using the previous years’ information to “predict” what the employment numbers may have been if there was no pandemic.</p><p>A simple explanation of interpolation is that it calculates data in-between given values. So we will use the values pre-April 2020 and post-April 2021 to calculate the values between in a linear fashion to help “smoothen” the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*v8MJvVrL0vYCvrUuirIpKQ.png" /></figure><p>Above, you’ll see the job growth data for Austin, TX. Now, using Python, we’ll create an interpolation function:</p><pre>def interpolate_smoothen(<br>    dataframe, <br>    msa_name,<br>    end_date=&#39;2021-04-01&#39;,<br>    start_date=&#39;2020-04-01&#39;<br>):<br>    &quot;&quot;&quot;<br>    This function adds an &quot;interpolated&quot; column in which<br>    the job numbers between the start_date and end_date<br>    are linearly interpolated. The purpose of this function<br>    is to give the user a column in which the impact of<br>    COVID on job deceleration and acceleration has been<br>    smoothed.<br>    &quot;&quot;&quot;<br><br>    smooth_jobs = dataframe.copy()<br>    smooth_jobs = smooth_jobs[[&#39;msa_name&#39;,&#39;date&#39;,&#39;value&#39;]]<br>    msa = smooth_jobs[smooth_jobs[&#39;msa_name&#39;]==msa_name].copy()<br><br>    # Create dummy column<br>    msa[&#39;dummy&#39;] = msa[&#39;value&#39;]<br><br>    # Filter and replace with NaNs<br>    mask = (msa[&#39;date&#39;]&lt;=end_date) &amp; (msa[&#39;date&#39;]&gt;=start_date)<br>    msa.loc[mask, &#39;dummy&#39;] = np.nan<br><br>    # Use interpolation now<br>    msa[&#39;interpolated&#39;] = msa[&#39;dummy&#39;].interpolate(method=&#39;linear&#39;)<br><br>    # Drop dummy column<br>    msa.drop(columns=[&#39;dummy&#39;], inplace=True)<br>    <br>    return msa</pre><p>Now we’ll run the interpolation function on the Austin MSA:</p><pre># Test with Austin, TX<br>austin = interpolate_smoothen(<br>    dataframe=jobs, <br>    msa_name=&#39;Austin, TX&#39;,<br>    end_date=&#39;2021-04-01&#39;,<br>    start_date=&#39;2020-04-01&#39;<br>)<br><br># Prepare for plotting<br>austin_smooth = austin.set_index(&#39;date&#39;).copy()<br><br>### PLOT THE BEFORE SMOOTHING AND AFTER SMOOTHING<br>fig, ax = plt.subplots()<br><br>ax = austin_smooth.plot(ylim=(500_000, 1_500_000), <br>            ylabel=&#39;Jobs&#39;, <br>            xlabel=&#39;Year&#39;,<br>            title=&#39;Austin Job Growth, Smoothed by 1-Year&#39;,<br>            ax=ax)<br><br>plt.ticklabel_format(style=&#39;plain&#39;, axis=&#39;y&#39;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*nUMlnDBopfIZAsrlkm35wg.png" /></figure><p>Let’s look at Los Angeles, CA and Phoenix, AZ as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*cdfcfvVjGSrhE9aeO42vkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*ec19CADN4d2J_pYoqTcA4A.png" /></figure><p>Austin, TX might be a special case as one of the fastest growing MSAs in the country at the time, but one can see a clear acceleration of job growth for Los Angeles and Phoenix that may not have been present had their never been a pandemic.</p><p>As an exercise in Exploratory Data Analysis (EDA), I wanted like to visually see what smoothing over 2 years (April 2020 to April 2022) looks like. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w617tzdu2maIgTQbL0tDhQ.png" /><figcaption>Los Angeles, CA 1-Year vs 2-Year Smoothing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvEqvizna0TMxnYsXZ0Ojw.png" /><figcaption>Austin, TX 1-Year vs 2-Year Smoothing</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkDU0HthsnLIngueUTp8xQ.png" /><figcaption>Phoenix, AZ 1-Year vs 2-Year Smoothing</figcaption></figure><p>While this smoothing removes any explosive growth a city may have had between 2020–2022, it also tries its best to remove any impact COVID had on the data to begin with, which aligns with our original intention. We will move forward with ensuring all job numbers between April 2020 and April 2022 are replaced with a linear interpolation (a prediction) of what their numbers may have been if COVID never happened, for each MSA:</p><pre># Create main function to interpolate the dataset<br>def interpolate_all_msa_job_data():<br>    <br>    # Call in the original job dataset<br>    jobs = pd.read_csv(&#39;datasets/bls/raw/most_recent_bls_data.csv&#39;,<br>                   dtype={&#39;msa_code&#39;:str, &#39;state_code&#39;:str})<br><br>    # Make sure the date column is in datetime format<br>    jobs[&#39;date&#39;] = pd.to_datetime(jobs[&#39;date&#39;])<br><br>    # Replace NECTA Division<br>    jobs[&#39;msa_name&#39;] = jobs[&#39;msa_name&#39;].apply(lambda x: x.replace(&quot; NECTA Division&quot;,&quot;&quot;))<br>    jobs[&#39;msa_name&#39;] = jobs[&#39;msa_name&#39;].apply(lambda x: x.replace(&quot; NECTA&quot;,&quot;&quot;))<br><br>    # Standardize MSA names<br>    jobs = clean_BLS_msa_names(jobs)<br>    <br>    # Add new column<br>    jobs[&#39;interpolated&#39;] = np.nan<br>    <br>    # Loop through all MSAs<br>    for msa in jobs[&#39;msa_name&#39;].unique():<br>    <br>        # Smoothen the data at the MSA level<br>        smooth_msa = interpolate_smoothen(<br>            dataframe=jobs, <br>            msa_name=msa,<br>            end_date=&#39;2022-04-01&#39;,<br>            start_date=&#39;2020-04-01&#39;)<br>        <br>        # Create a mask<br>        mask = jobs[&#39;msa_name&#39;] == msa<br><br>        # Add the interpolated data to the original jobs dataframe<br>        jobs.loc[mask, &#39;interpolated&#39;] = smooth_msa[&#39;interpolated&#39;]<br>    <br>    # Create folder to save covid-smoothed dataset<br>    folder_name = &#39;datasets/bls/smoothed&#39;<br>    create_folder(folder_name)<br>    <br>    # Create filename<br>    filename = f&quot;{folder_name}/most_recent_bls_covid_smoothed.csv&quot;<br>    <br>    # Save file<br>    jobs.to_csv(filename, index=False)<br><br># Now run the interpolation function<br>interpolate_all_msa_job_data()</pre><p>Let’s take a look at Phoenix, AZ again. Here is the job growth data before we smoothed the COVID anomaly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwPFQ1UUi-UKz2c7rL9CrA.png" /><figcaption>Above: Phoenix, AZ pre-smoothing. Below: Phoenix, AZ post-smoothing.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2AhD0RAzqUFWFr9nMODQw.png" /></figure><p>An immediate detail you’ll notice is on the right graph. The percent-change-in-jobs between April 2020 and April 2022 remains unchanged. This is a side effect of smoothing a time-series dataset using linear interpolation: the growth (or decline) will be linear, so the percent-change-in-growth will remain constant.</p><p>Another downside of smoothing the data is losing the true information of how an MSA grew (or didn’t) on a month-to-month basis. This loss of information will need to be accounted for if we build a predictive machine learning model in the future.</p><h4>Conclusion</h4><p>I will be using this smoothed time-series data to help my new analysis of the best MSAs to invest in real estate. Follow me for updates on this project.</p><p>The Github repo containing the code is private, but if you’re a recruiter for a real estate company looking for data scientists, don’t hesitate to reach out.</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/time-series-removing-covid-from-bls-jobs-dataset-austin-wolff-sxevc"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b5de97bbda2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End AWS ETL Data Pipeline: Ranking The Best Places To Invest In Real Estate]]></title>
            <link>https://medium.com/@austinwolff/end-to-end-aws-etl-data-pipeline-ranking-the-best-places-to-invest-in-real-estate-c8d383e51104?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8d383e51104</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 16:53:54 GMT</pubDate>
            <atom:updated>2023-03-06T16:53:54.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52BFxM-nbf0dxtwP4Lw7aw.png" /></figure><p>If your real estate company wants to secure the highest IRR possible, you need to select the right market.</p><p>I built an <strong>end-to-end AWS ETL pipeline</strong> that downloads demographic information and ranks every MSA in America in order to find the best places to invest in real estate (and I’m currently looking for deals in the market the data says is <strong>#1</strong>).</p><p>My name is Austin Wolff, and <strong>I’m a Real Estate Data Scientist</strong> that analyzes the best markets and locations for real estate investment. <strong>My analyses have previously been read by multiple billion-dollar firms.</strong></p><p>As mentioned in <a href="https://www.linkedin.com/pulse/creating-etl-data-pipeline-using-airflow-austin-wolff/">my previous article</a>, I’ve already created this ETL pipeline to work locally using Airflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*eYfbZMYcjw1x14ZnPU8-FA.png" /><figcaption>Local ETL: Airflow DAG</figcaption></figure><p>However, I promised I would build a similar end-to-end pipeline using AWS, so let’s get into the cloud-data-engineering details.</p><h3>The Full ETL Pipeline: An Overview</h3><p>I’ll be explaining each part of the pipeline, step-by-step. But first, here is the full pipeline diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52BFxM-nbf0dxtwP4Lw7aw.png" /><figcaption>Full AWS ETL Overview</figcaption></figure><h3>Part 1: Launching The Pipeline</h3><p>The pipeline was orchestrated with an AWS Step Function, and can be launched directly from the Step Function console, or with the AWS CLI, or by activating EventBridge to run once per month (which is when the “jobs” dataset is updated on the Bureau of Labor Statistics’ API).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*tlvnTIxfkyTaUeYQmNyUFA.png" /><figcaption>My Step Function Graph</figcaption></figure><p>Every single node in my step function invokes an AWS Lambda function. You’ll also notice the leftmost column directly relates to the top three Lambda functions in my diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*MvYzvCv58fVAj8GIHJsm9w.png" /><figcaption>Download BLS Data → Download City MSA Data → Rank MSAs</figcaption></figure><p>The bottom Lambda function in my diagram is representative of the 4 Lambda functions it takes to download my city data (more data to download means more time accessing the API, which would timeout if put into one Lambda function). I simply used 1 Lambda icon in my diagram to save space and reduce clutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*a9i-ichSiGodwd6klRCt6g.png" /><figcaption>This part of the ETL pipeline downloads city data from the Census.</figcaption></figure><p>I also could’ve used AWS ECS and ran my “Download Census City Data” container stored on ECR. But in this case I would need to either: A) Pay for a NAT Gateway, which isn’t cheap, or B) Set up and manage a NAT Instance, which creates more infrastructural overhead that isn’t necessary since 4 serverless Lambda functions can do the job.</p><p>Let’s discuss the details of the Lambda functions before talking about the container images they run.</p><h3>Part 2: The Lambda Functions</h3><p>Each Lambda function runs container images I’ve built due to the extra packages I need installed like Pandas and AWS SDK for Pandas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*xlzfvIzLBkOEsoY42UNC1w.png" /><figcaption>The AWS Lambda Console</figcaption></figure><p>The only configuration I need are increasing the timeout to 5 minutes, and setting up the API key as an environment variable in order to access the census data.</p><p>Now let’s discuss what’s actually inside the containers.</p><h3>Part 3: The Docker Containers</h3><p>Each container was made roughly the same. I will show my code for the “Download BLS Data” as an example.</p><p>I develop locally using VSCode as my IDE, so I created my virtual environment and downloaded the necessary packages.</p><pre>$ python3 -m virtualenv venv <br>$ source venv/bin/activate <br>(venv) $ pip install pandas==1.4.1 awswrangler==2.19.0</pre><p>The I created my download_bls_data.py script:</p><pre>&quot;&quot;&quot;<br>This module downloads the most recent job data from the<br>BLS at the metropolitan level for the past 10 years.<br>&quot;&quot;&quot;<br><br># Import libraries<br>import requests<br>import json<br>import os<br>from datetime import datetime<br>import pandas as pd<br>import awswrangler as wr<br><br>def download_bls(event, context):<br><br>    # Get BLS key<br>    bls_key = os.environ.get(&quot;BLS_KEY&quot;)<br><br>    ...</pre><p>Once tested, I created my Dockerfile. You’ll notice it’s configured to work with AWS Lambda:</p><pre>FROM public.ecr.aws/lambda/python:3.9 <br><br>COPY requirements.txt requirements.txt <br>RUN pip3 install -r requirements.txt --target &quot;${LAMBDA_TASK_ROOT}&quot; <br><br>COPY download_bls_data.py ${LAMBDA_TASK_ROOT} <br><br>CMD [ &quot;download_bls_data.download_bls&quot; ]</pre><p>Then I built and pushed my container to AWS ECR, where it can be executed by Lambda.</p><pre>$ docker build -t download_bls_data . <br>$ docker tag download_bls_data:latest XXXXXXXXX.dkr.ecr.us-west-1.amazonaws.com/download_bls_data:latest <br>$ docker push XXXXXXXXX.dkr.ecr.us-west-1.amazonaws.com/download_bls_data:latest</pre><p>All I needed to do was rinse-and-repeat this process for every script I had. Now the Lambda functions could access the images from ECR.</p><p>After that, I tested my Lambda functions individually in the console. Once they worked, I orchestrated my Step Functions and tested my ETL pipeline.</p><h3>Part 4: The Ranking Algorithm</h3><p>I’ve already touched on the ranking algorithm in my previous Airflow article, so I will simply repeat what I wrote there:</p><p>The MSA data is passed through my ranking algorithm, which essentially applies this equation to each MSA:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*QdfkXMo5c1DoB6cUykfW6Q.png" /><figcaption>Demographic weight summation algorithm</figcaption></figure><p>Where “weight” is the weight you want to apply to a particular demographic (so, for example, you can give “job growth” more importance than “price growth” if that fit your personal investment thesis), and “z” is the normalized trend coefficient for a given dataset. <em>(I could further explain the explicit details behind this variable, but this is not the article for that. For now, think of “z” as a measure of the trend line of a given demographic: An MSA with a higher trend of job growth will have a higher z-number.)</em></p><p>Then the MSAs are sorted by their total weight from highest to lowest, giving me an ordered list of MSAs by “invest-ability.”</p><p>The rankings are saved to S3, which can then be accessed for your visualization method of choice.</p><h3>Part 5: The Visualizations</h3><p>After the MSAs are ranked, you can drill-down and analyze the cities within the top MSAs in your visualization software.</p><p>I use GeoPandas locally (personally, I find it much more useful than Tableau or QGIS since I have more control over the data due the Pandas package being at my fingertips).</p><p>Here’s an example of a Median Income map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*IR00Tc6-UIy8RvfwasPauQ.png" /><figcaption>Median income for all towns in the Austin, TX MSA with a population of greater than 10,000</figcaption></figure><p>I personally like to rank the cities by rent-to-price ratio first, which is the ratio of the median rent to the median price, and can be a helpful rule-of-thumb for your ROI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*UqGB0X8TlO1U87gZQGbHrQ.png" /><figcaption>The higher the rent-to-price ratio, the better</figcaption></figure><p>As you can see here, the top three contenders for best rent-to-price ratio are San Marcos, Kyle, and Hutto.</p><p>But I also care about rent growth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*Ipq5Ze822C-1jMnljrn7FQ.png" /><figcaption>Rent Growth</figcaption></figure><p>San Marcos and Kyle appear to have the lowest rent growth, while Hutto’s growth may be acceptable. But let’s see if Hutto is within my price range:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*ip-cAVdBW-3JD5bg0ZY9fQ.png" /><figcaption>Median Price</figcaption></figure><p>Hutto is more expensive than San Marcos, but it’s had higher rent growth over time, which may make it a better place to invest overall.</p><h3>Conclusion</h3><p>There are more demographics that I take into account before selecting a place to invest, but the process I just showed you is coded as a city-ranking algorithm I can run on any MSA.</p><p>Maybe in the future I will write an article discussing the city-ranking algorithm. But the purpose of this article was to discuss my AWS ETL pipeline for ranking MSAs (groups of cities), and we are done.</p><p>As a recap, the AWS ETL pipeline first <strong>Extracts</strong> data from the BLS and Census API, <strong>Transforms</strong> it with the ranking algorithm, then <strong>Loads</strong> it into S3 for further analysis and visualization.</p><p>The Github repo containing the code used in the containers is private, but if you’re a recruiter for a real estate company looking for data scientists and data engineers, don’t hesitate to reach out.</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/end-to-end-aws-etl-data-pipeline-ranking-best-places-invest-wolff/?published=t"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8d383e51104" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using AWS EMR (Spark) To Solve An Infamous Real Estate Problem]]></title>
            <link>https://medium.com/@austinwolff/using-aws-emr-spark-to-solve-an-infamous-real-estate-problem-240de3dbca7b?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/240de3dbca7b</guid>
            <category><![CDATA[aws-emr]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Sun, 05 Mar 2023 21:45:15 GMT</pubDate>
            <atom:updated>2023-03-05T21:45:15.700Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHy2jdoRg8ft4ouiTMZYsQ.jpeg" /></figure><p>If your real estate company uses demographics at the Census Tract and Block Group level to make investment decisions, I hope you know about this infamous problem…</p><p>But if not, I solved it for you using PySpark and AWS EMR (which uses Hadoop under-the-hood).</p><p>So if you’re looking for a skilled real estate-focused data scientist or data engineer to join your team, read this article because I’m your guy.</p><h3>Background of The Infamous Problem</h3><p>Demographic information is very important when selecting a market to invest in real estate. At my previous company, billion dollar firms used the information I gathered (through an ETL pipeline) to aid in their multi-million dollar investment decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gCv4PtuDK1Xh7hCukc07Q.png" /><figcaption>YoY Income Growth and YoY Percent Change in the Austin, TX MSA. Created by me.</figcaption></figure><p>The U.S. Census conducts the yearly American Community Survey (ACS) and releases demographic information (population, median income, median rent, etc.) for geographies as big as the country or state, down to geographies as small as cities, census tracts, or block groups (think of block groups as neighborhoods or small sections of a big neighborhood).</p><h3>The Infamous Problem: Geo-Standardization of Census Tracts Across Time</h3><p>As helpful as this yearly dataset is, the U.S. Census changed the key identifiers of over 30,000 block groups (and over 3,000 census tracts) in 2020. This meant you couldn’t compare 2010–2019 data with any data after 2020.</p><p>What’s even worse is some key identifiers remained the same, <strong>but their geographies changed</strong>. So if a census tract represented the Sunnyvale neighborhood in 2019, it could now represent the Burbank sub-neighborhood in 2020, <strong>and there would be no way to know without looking at the data’s geometry.</strong></p><p>See my drawing below for an example of the problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QB8xEc2DJl9oyWyiEBejPA.png" /><figcaption>Simple example of the census tract geo-standardization problem</figcaption></figure><p>You’ll notice that blocks <strong>101 and 102</strong> move to a completely different geographic area in 2020, making any comparison between 2019 and 2020’s data incorrect. You can probably begin to understand why this would be a problem when trying to standardize a time-series dataset. And <strong>this made-up example is far simpler than the actual datasets provided by the U.S. Census.</strong></p><p>When I discovered the extent of this problem through rigorous EDA (exploratory data analysis), I searched the U.S. Census website for any clue on how to reconcile the data. The only data the U.S. provided was a crosswalk file, which explained which key identifiers in 2019 were associated with key identifiers in 2020. <strong>Unfortunately, it lacks a very important feature needed for reconciliation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1KWLWBcLKVYLKYI0r1sYg.jpeg" /></figure><p><strong>This is why the problem is infamous: no one on the internet has published a findable, step-by-step solution on how to geo-standardize census tract (or block group) data across time</strong>, yet it remains a very important problem to solve if you’d like to track the demographic trend of a neighborhood over time.</p><h3>The Solution</h3><p>Lucky for me, I found an organization that published half of the answer. <strong>IPUMS NHGIS</strong> had already done the heavy lifting and <strong>provided a crosswalk file with interpolation weights</strong>, the missing feature. (Why this column is needed is outside the scope of this article, so <a href="https://www.nhgis.org/geographic-crosswalks">here’s a link to their crosswalk page</a> if you want to learn more.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*AXVJBSZD9ZkLwqSqNX0-2A.png" /><figcaption>IPUMS NHGIS Website</figcaption></figure><p><strong>All that remained was to create an algorithm that used linear algebra to apply the interpolation weight to the years 2010–2019 of a given block group and merge that with the new 2020–2021 values.</strong></p><p>Because there are over 240,000 block groups, and standardizing just one can take up to half of a second, this meant <strong>running the algorithm on just one core could take anywhere from 12–60 hours</strong> (or more if we needed to calculate a median value after-the-fact). The algorithm had to be processed across multiple cores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*yDTrNC0zaqRl7jHGnYXZpQ.png" /><figcaption>Parallel processing</figcaption></figure><p>I decided to use AWS EMR (Elastic MapReduce) to speed up the processing time.</p><h3>Using AWS EMR To Standardize Census Data</h3><p>AWS EMR uses Apache Hadoop MapReduce under-the-hood, and offers a runtime for Apache Spark, giving us the perfect tool to parallelize the algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*8KsC13cyVGZHXzsJjSB_Sw.png" /><figcaption>Using PySpark with AWS EMR</figcaption></figure><h3>Creating The EMR Cluster</h3><p>Next, I had to create a cluster in EMR. I selected Spark as my framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*XXHxBfCNao9gMPO_WG25mA.png" /></figure><p>Then, just to get going, I selected the m5.xlarge EC2 type for my primary and core nodes. (I will save EC2 optimization for another article.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*QoLMW6QMqJEdCs9iKi2www.png" /></figure><p>I also created a bootstrap script to install the appropriate libraries:</p><pre>#!/bin/bash <br><br># Install needed libraries <br>sudo pip3 install pandas==1.3.5 awswrangler==2.19.0 boto3==1.26.72</pre><h3>Adding A Step</h3><p>Once I started my cluster, I added a step to run my Spark Application (my algorithm rewritten with PySpark).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*bDMgjs0Y3w1vtwbsuyJDQA.png" /></figure><h3>Main Script (standardize_blocks.py)</h3><p>Below is the main script (which then imports the proprietary algorithm embedded in the “run_standardize_script” function):</p><pre>import os<br>import pandas as pd<br>from pyspark.sql import SparkSession<br>from pyspark import SparkContext<br>from pyspark.sql.types import *<br>from pyspark.sql.functions import col as spark_col<br><br># Import other functions from module<br>from util import get_spark_session<br>from read import read_df<br>from transform import run_standardize_script<br>from write import write_file<br><br># AWS library<br>import awswrangler as wr<br><br>def main():<br>    # Get environment variables<br>    env = os.environ.get(<br>        &quot;ENVIRON&quot;)<br>    start_year = int(os.environ.get(<br>        &quot;START_YEAR&quot;))<br>    end_year = int(os.environ.get(<br>        &quot;END_YEAR&quot;))<br>    src_file = os.environ.get(<br>        &quot;SRC_FILE&quot;)<br>    tgt_file = os.environ.get(<br>        &quot;TGT_FILE&quot;)<br>    use_weight = os.environ.get(<br>        &quot;WEIGHT&quot;)<br><br>    # Start the spark session<br>    spark = get_spark_session(<br>        env, &#39;Standardize Block Groups&#39;)<br><br>    # Read in the Spark Dataframe    <br>    spark_df = read_df(<br>        spark, start_year, end_year, src_file)<br><br>    # Standardize the data<br>    standardized_df = run_standardize_script(<br>        spark_df, env, start_year, end_year, use_weight, src_file)<br><br>    # Print the dataframe just to double-check<br>    standardized_df.show(5)<br><br>    # Write to S3 bucket<br>    write_file(standardized_df, tgt_file)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Then, I added these spark-submit options:</p><pre>--conf &quot;spark.yarn.appMasterEnv.ENVIRON=PROD&quot; <br>--conf &quot;spark.yarn.appMasterEnv.START_YEAR=2013&quot; <br>--conf &quot;spark.yarn.appMasterEnv.END_YEAR=2021&quot; <br>--conf &quot;spark.yarn.appMasterEnv.WEIGHT=wt_pop&quot; <br>--conf &quot;spark.yarn.appMasterEnv.SRC_FILE=real-estate-wolff/census-data/block-groups/raw/population_blocks_raw.csv&quot; <br>--conf &quot;spark.yarn.appMasterEnv.TGT_FILE=s3://real-estate-wolff/census-data/block-groups/standardized/population_blocks_standardized.csv&quot; <br>-cacheFile s3://real-estate-wolff/census-data/block-groups/raw/population_blocks_raw.csv#population_blocks_raw.csv <br>--py-files s3://real-estate-wolff/scripts/emr_standardize_blocks/standardize_functions.zip</pre><p>The “ — conf” arguments define environment variables needed for the main script.</p><p>The “-cacheFile” argument caches a dataset needed for the algorithm.</p><p>The “ — py-files” argument defines the .zip file with the individual modules I’ve written for the main script, including the standardization function.</p><h3>The PySpark Helper Functions</h3><p>Below I’ll be showing all the python files within the “ <strong>standardize_functions.zip</strong>” file, which contain all of the helper functions used in the main script.</p><h3>util.py → for function “get_spark_session()”</h3><pre>from pyspark.sql import SparkSession<br><br>def get_spark_session(env, app_name):<br><br>    print(f&quot;env: {env}&quot;)<br><br>    if env == &quot;LOCAL&quot;:<br><br>        # Using findspark ensures the spark path is<br>        # found and set, allowing us to use the<br>        # appropriate JAR files to connect to AWS.<br>        # Only use locally.<br>        import findspark<br>        location = findspark.find()<br>        findspark.init(location, edit_rc=True)<br><br>        # Create Spark Session<br>        spark = SparkSession. \<br>            builder. \<br>            master(&#39;local&#39;). \<br>            config(&quot;spark.driver.bindAddress&quot;,&quot;127.0.0.1&quot;). \<br>            config(&quot;spark.driver.host&quot;,&quot;127.0.0.1&quot;). \<br>            config(&quot;spark.jars.packages&quot;, <br>                &quot;org.apache.hadoop:hadoop-aws:2.10.2,org.apache.hadoop:hadoop-client:2.10.2&quot;). \<br>            config(&quot;spark.jars.excludes&quot;, <br>                &quot;com.google.guava:guava&quot;). \<br>            appName(app_name). \<br>            getOrCreate()<br><br>        # Use the system&#39;s default AWS credentials<br>        spark.sparkContext._jsc.hadoopConfiguration().set(<br>            &quot;fs.s3a.aws.credentials.provider&quot;,<br>            &quot;com.amazonaws.auth.DefaultAWSCredentialsProviderChain&quot;<br>        )<br><br>    elif env == &quot;PROD&quot;:<br><br>        # Create Spark Session<br>        spark = SparkSession. \<br>            builder. \<br>            master(&#39;yarn&#39;). \<br>            appName(app_name). \<br>            getOrCreate()<br><br>    return spark</pre><p>We will be using this script in Production, so the LOCAL code does not apply here. I’ve left it here only for the purposes of being able to use this script locally if I ever get access to a computer with more cores and I don’t want to pay for AWS EMR.</p><h3>read.py → function for “read_df()”</h3><pre>import os<br>from pyspark.sql.functions import col as spark_col<br><br>def read_df(spark, start_year, end_year, src_file):<br><br>    # Get file path for spark readings<br>    src_filepath = &quot;s3://&quot; + src_file<br><br>    # READ IN DATAFRAME<br>    spark_s3_df = spark.read.load(src_filepath, format=&quot;csv&quot;, header=True)<br><br>    # CHANGE TYPE FOR THE YEAR COLUMNS<br>    for i in range(start_year, end_year + 1):<br>        spark_s3_df = spark_s3_df.withColumn(<br>            str(i), spark_col(str(i)).cast(&quot;float&quot;)<br>        )<br>        <br>    # CHNAGE TYPE FOR THE CROSSWALK MULTIPLIER COLUMNS<br>    spark_s3_df = spark_s3_df.withColumn(&#39;wt_pop&#39;, spark_col(&#39;wt_pop&#39;).cast(&quot;float&quot;)). \<br>        withColumn(&#39;wt_hu&#39;, spark_col(&#39;wt_hu&#39;).cast(&quot;float&quot;)). \<br>        withColumn(&#39;wt_adult&#39;, spark_col(&#39;wt_adult&#39;).cast(&quot;float&quot;)). \<br>        withColumn(&#39;wt_fam&#39;, spark_col(&#39;wt_fam&#39;).cast(&quot;float&quot;)). \<br>        withColumn(&#39;wt_hh&#39;, spark_col(&#39;wt_hh&#39;).cast(&quot;float&quot;)). \<br>        withColumn(&#39;parea&#39;, spark_col(&#39;parea&#39;).cast(&quot;float&quot;))<br><br>    # Drop unnecessary columns<br>    spark_s3_df = spark_s3_df.drop(&quot;name&quot;,&quot;block group&quot;)<br><br>    return spark_s3_df</pre><p>All this script does is read in the raw block group dataset into a PySpark DataFrame and ensure the columns are the correct dtypes.</p><h3>transform.py → for function “run_standardize_script()”</h3><pre>OMITTED</pre><p>I’ve decided to make the standardization algorithm proprietary due to the insane complexity it solves and the enormous business value it provides.</p><p>After the function runs, it returns a standardized PySpark DataFrame.</p><h3>write.py → for function “write_file()”</h3><pre>import awswrangler as wr<br><br>def write_file(standardized_df, tgt_file):<br><br>    # Have spark save to s3<br>    standardized_df \<br>        .write.format(&quot;csv&quot;) \<br>        .option(&#39;header&#39;,&#39;true&#39;) \<br>        .option(&#39;encoding&#39;,&#39;utf-8&#39;) \<br>        .mode(&quot;overwrite&quot;) \<br>        .save(tgt_file)</pre><p>This simple script saves our standardized PySpark DataFrame to a CSV in AWS S3.</p><h3>Conclusion</h3><p>The framework for running this was rather simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRPgurkRSJuPemXxsg6AeA.png" /></figure><p>This framework is actually part of a bigger ETL pipeline which includes downloading the raw block group data from the U.S. Census API. But I’ll save that for another article.</p><p>Now I can standardize more block group demographic information, giving me access to hyper-local real estate insights for long-term investment decisions.</p><p>If you’re a recruiter for a real estate company looking for data scientists and data engineers, don’t hesitate to reach out.</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/using-aws-emr-spark-hadoop-solve-infamous-real-estate-austin-wolff/"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240de3dbca7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an ETL Data Pipeline Using Airflow With DockerOperator]]></title>
            <link>https://medium.com/@austinwolff/creating-an-etl-data-pipeline-using-airflow-with-dockeroperator-402f452634ca?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/402f452634ca</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 20:14:37 GMT</pubDate>
            <atom:updated>2023-01-24T20:14:37.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*DObBhKRkCQIEPv-sSkS21A.png" /><figcaption>My ETL data pipeline that ranks MSAs by “invest-ability”​</figcaption></figure><p>What are the best MSAs (Metropolitan Statistical Areas) to invest in real estate right now? Is it Austin, TX? Tampa, FL? Detroit, MI? <strong>The ETL pipeline described in this article is the data engineering needed to answer this question.</strong></p><p>My name is Austin Wolff, and I’m a Real Estate Data Scientist that analyzes the best markets and locations for real estate investment. My analyses have previously been read by multiple billion-dollar firms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*f9PQNBpOV5V5Y8pxHlm8wA.png" /><figcaption>New York, NY</figcaption></figure><p>In this article I’m going to share the technical <strong>data engineering behind the ETL pipeline</strong> that makes this possible.</p><p>First, I will explain the extraction (E) and transformation (T) of the data before I dive into using Airflow and Docker to orchestrate the pipeline.</p><h3>Part 1: Extraction</h3><p>The data used for analysis comes from two different sources/APIs: The Bureau of Labor Statics (BLS) and the ACS Survey from the US Census. The BLS provides the job data I need as recent as 2 prior months (for example, in March, the most recent data will be that of January, and in April, the most recent data will be February).</p><p>The BLS data is accessed and downloaded using my <strong>download_bls_data.py </strong>script (a snippet of the Python code is featured below).</p><pre>... <br># Get the data from the API <br>headers = {&#39;Content-type&#39;: &#39;application/json&#39;} <br>data ​= json.dumps({&quot;seriesid&quot;: series_ids, <br>                    &quot;startyear&quot;: str(start_year), <br>                    &quot;endyear&quot;: str(end_year), <br>                    &quot;registrationkey&quot; : bls_key, <br>                    &quot;calculations&quot;: True}) <br>p = requests.post(&#39;https://api.bls.gov/publicAPI/v2/timeseries/data/&#39;, <br>                  data​=data, headers=headers) <br>json_data = json.loads(p.text)<br>...</pre><p>The Census provides the demographic data I need (rent/income/price) once a year near the end of the year. Unfortunately, this data will always be a year behind or more. The Census data is accessed through their API and downloaded through a similar script of mine.</p><h3>Part 2: Transformation</h3><p>Finally, the data is passed through my ranking algorithm, which essentially applies this equation to each MSA:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*pQDxFiFKR_nwmA1Pu4lzHw.png" /><figcaption>Demographic weight summation algorithm</figcaption></figure><p>Where “weight” is the weight you want to apply to a particular demographic (so, for example, you can give “job growth” more importance than “price growth” if that fit your personal investment thesis), and “z” is the normalized trend coefficient for a given dataset. <em>(I could further explain the explicit details behind this variable, but this is not the article for that. For now, think of “z” as a measure of the trend line of a given demographic: An MSA with a higher trend of job growth will have a higher z-number.)</em></p><p>Now I can simply sort all MSAs by their total weight from highest to lowest, giving me an ordered list of MSAs by “invest-ability.”</p><h3>Running Airflow Using Docker (With Docker Operators)</h3><p>Now that I had my Extract and Transformation scripts (more on the Load script in a minute), it was time to build the first DAG (Directed Acyclic Graph) using Airflow.</p><p>I used a modified, light-weight version of the docker-compose.yaml provided by Apache that works with my resource-limited MacOS (running Docker on MacOS can be very resource-intensive if you have 8GB of memory or less, since Docker needs at least 4GB to run the full Airflow Docker Image).</p><p>I needed to add this volume to the docker-compose.yaml file in order to run Docker Operators inside of a Docker container:</p><pre>version: &#39;3&#39; <br>x-airflow-common: <br>  ... <br>  volumes: <br>  ... <br>  - /var/run/docker.sock:/var/run/docker.sock</pre><p>And then to get this to work on MacOS, I further needed to add the following TCP wrapper under “services” or else I would get a Permission Denied Error:</p><pre>services: <br>  docker-proxy: <br>    image: bobrik/socat <br>    command: &quot;TCP4-LISTEN:2375,fork,reuseaddr UNIX-CONNECT:/var/run/docker.sock&quot; <br>    ports: <br>      - &quot;2376:2375&quot; <br>    volumes: <br>      - /var/run/docker.sock:/var/run/docker.sock</pre><p>Now with the docker-compose.yaml file ready, I also created separate Docker Images for the download and ranking scripts, since they used different dependencies:</p><pre>docker build -t download_msa_image .</pre><p>With the Airflow Image and individual task Images built, it was time to code the DAG.</p><h3>Coding The ETL Pipeline With An Airflow DAG</h3><p>Like all great DAGs, mine was simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*NvS57y5i7u8omGWS2GwbzQ.png" /><figcaption>Download BLS Data &gt;&gt; Download Census Data &gt;&gt; Rank MSAs</figcaption></figure><p>The DAG should be self-explanatory: download the BLS job data, then download the Census demographic data, then rank the MSAs based on the weighting algorithm I described above. The actual code in the Docker Images is private, but I can share the code for the DAG below:</p><pre>&quot;&quot;&quot;<br>This dag downloads and ranks the MSAs by<br>the data provided by the BLS (job growth)<br>and the Census (median rent, income, and <br>unit value).<br>&quot;&quot;&quot;<br># Import necessary libraries<br>import os<br>from airflow import DAG, Dataset<br>from airflow.decorators import task, dag<br>from airflow.providers.docker.operators.docker import DockerOperator<br>from docker.types import Mount<br>from datetime import datetime<br><br># Define docker images to use<br>download_image = &quot;download_msa_image:latest&quot;<br>rank_image = &quot;rank_msa_image:latest&quot;<br><br># Create the Dataset object<br>rank_all_demos = Dataset(&quot;datasets/ranked_msa_datasets/rank_all_demos.csv&quot;)<br><br># Define keyword arguments to use for all<br># DockerOperator tasks<br>dockerops_kwargs = {<br>    &#39;docker_url&#39;:&quot;tcp://docker-proxy:2375&quot;,<br>    &#39;network_mode&#39;:&quot;bridge&quot;,<br>    &#39;auto_remove&#39;:True,<br>    &#39;xcom_all&#39;:True,<br>    &#39;retrieve_output&#39;:True,<br>    &#39;mount_tmp_dir&#39;:False,<br>    &#39;mounts&#39;:[Mount(<br>                source=f&quot;{os.environ[&#39;YOUR_LOCAL_REPO&#39;]}/includes/datasets/&quot;,<br>                target=&quot;/datasets/&quot;,<br>                type=&quot;bind&quot;<br>                )],<br>    &#39;retries&#39;:1<br>}<br><br># Create DAG<br>@dag(start_date=datetime(2023, 1, 1), schedule=&quot;@monthly&quot;, catchup=False)<br>def download_and_rank_msa():<br><br>    ### CREATE TASKS<br><br>    # Task 1: Download BLS data<br>    download_bls = DockerOperator(<br>        task_id=&quot;download_bls&quot;,<br>        container_name=&quot;task__download_bls&quot;,<br>        image=download_image,<br>        environment={<br>            &#39;BLS_KEY&#39;: os.environ[&#39;BLS_KEY&#39;],<br>        },<br>        command=&quot;python3 download_bls_data.py&quot;,<br>        **dockerops_kwargs<br>    )<br><br>    # Task 2: Download census data<br>    download_census_msa = DockerOperator(<br>        task_id=&quot;download_census_msa&quot;,<br>        container_name=&quot;task__download_census_msa&quot;,<br>        image=download_image,<br>        environment={<br>            &#39;CENSUS_KEY&#39;: os.environ[&#39;CENSUS_KEY&#39;],<br>        },<br>        command=&quot;python3 download_census_msa_data.py&quot;,<br>        **dockerops_kwargs<br>    )<br><br>    # Task 3: Rank joined_data and save outputs to datasets/ranked_msa_datasets<br>    rank_msa = DockerOperator(<br>        task_id=&quot;rank_msa&quot;,<br>        container_name=&quot;task__rank_msa&quot;,<br>        image=rank_image,<br>        command=&quot;python3 rank_msa.py&quot;,<br>        outlets=[rank_all_demos],<br>        **dockerops_kwargs<br>    )<br><br>    download_bls &gt;&gt; download_census_msa &gt;&gt; rank_msa<br>    <br>dag = download_and_rank_msa()</pre><p>As you can see on Task 3 (with task_id=”rank_msa”), I’ve made the outlet equal to the Dataset “rank_all_demos” (defined before the DAG). Once this file is updated, the second DAG will begin, which can be seen as the “L” (Load) part of the ETL pipeline.</p><h3>Part 3: Load</h3><p>Now that the dataset is ranked, you can load any part of this data wherever you’d like (Snowflake, AWS RDS, S3, etc). For now, I simply wanted to create graph visualizations of market trends and save them to my local repo (the cheapest option, but by no means the only option).</p><p><em>Note: I chose to load this data into a second one-task DAG that creates and saves the graphs. This task could’ve been added to the first DAG, but I separated them to make them more functional. Plus, if in the future I wanted to output the graphs to S3 or any other data lake, I could simply make a separate DAG that would also be connected to the first DAG via the Dataset trigger.</em></p><p>Here is the code for my one-task graph-creation DAG:</p><pre>&quot;&quot;&quot;<br>This dag will graph the top 10 MSAs and save the output<br>locally. It will be triggered when the <br>&quot;ranked_msa_datasets&quot; are updated.<br>&quot;&quot;&quot;<br># Import necessary libraries<br>import os<br>from airflow import DAG, Dataset<br>from airflow.decorators import task, dag<br>from airflow.providers.docker.operators.docker import DockerOperator<br>from docker.types import Mount<br>from datetime import datetime<br><br># Define docker images to use<br>graph_image = &quot;graph_data_image:latest&quot;<br><br># Define keyword arguments to use for all<br># DockerOperator tasks<br>dockerops_kwargs = {<br>    &#39;docker_url&#39;:&quot;tcp://docker-proxy:2375&quot;,<br>    &#39;network_mode&#39;:&quot;bridge&quot;,<br>    &#39;auto_remove&#39;:True,<br>    &#39;xcom_all&#39;:True,<br>    &#39;retrieve_output&#39;:True,<br>    &#39;mount_tmp_dir&#39;:False,<br>    &#39;mounts&#39;:[Mount(<br>                source=f&quot;{os.environ[&#39;YOUR_LOCAL_REPO&#39;]}/includes/datasets/&quot;,<br>                target=&quot;/datasets/&quot;,<br>                type=&quot;bind&quot;<br>                ), <br>             Mount(<br>                source=f&quot;{os.environ[&#39;YOUR_LOCAL_REPO&#39;]}/graphs/&quot;,<br>                target=&quot;/graphs/&quot;,<br>                type=&quot;bind&quot;<br>                )],<br>    &#39;retries&#39;:0<br>}<br><br># Create the Dataset object<br>rank_all_demos = Dataset(&quot;datasets/ranked_msa_datasets/rank_all_demos.csv&quot;)<br><br># Create DAG -- Triggered when the Dataset is updated<br>@dag(start_date=datetime(2023, 1, 1), <br>    schedule=[rank_all_demos], <br>    catchup=False)<br>def graph_msa():<br><br>    # Graph top 10 MSAs, all demographics, and<br>    # save locally<br>    graph_each_demo = DockerOperator(<br>        task_id=&quot;graph_each_demo&quot;,<br>        container_name=&quot;task__graph_each_demo&quot;,<br>        image=graph_image,<br>        command=&quot;python3 graph_data.py&quot;,<br>        **dockerops_kwargs<br>    )<br><br>    graph_each_demo<br>    <br>dag = graph_msa()</pre><h3>“Airflow Using Docker” Conclusion</h3><p>The first “download_and_rank_msa” DAG is scheduled to run monthly, as this is when we can expect to receive job growth updates from the BLS. Seeing as one wouldn’t want their Docker container running permanently for a once-a-month DAG run, future iterations of this project may include porting this project to an AWS EC2 instance and using AWS Instance Scheduler.</p><h3>MSA Ranking Conclusion</h3><p>As of January 2023, the <strong>Dallas-Fort Worth, TX MSA</strong> was <strong>#1</strong> across multiple weight variations. Other top 5 MSAs included:</p><p>Charlotte, NC</p><p>Atlanta, GA</p><p>Nashville, TN</p><p>Charleston, SC</p><p>If you’d like to see the full MSA analysis, <a href="https://www.biggerpockets.com/users/austinw187">check out my real estate articles on BiggerPockets</a>.</p><h3>Final Conclusion</h3><p>Thank you for reading. If you’re a recruiter and would like to see the private repo which includes all code for this ETL pipeline, don’t hesitate to reach out.</p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/creating-etl-data-pipeline-using-airflow-austin-wolff/"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=402f452634ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My AWS Cloud Practitioner Notes]]></title>
            <link>https://medium.com/@austinwolff/my-aws-cloud-practitioner-notes-d3131f4c68a?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3131f4c68a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-certified-cloud]]></category>
            <category><![CDATA[aws-certification]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 20:07:38 GMT</pubDate>
            <atom:updated>2022-12-22T03:22:42.208Z</atom:updated>
            <content:encoded><![CDATA[<p>As I prepare for the AWS Cloud Practitioner exam, I’ll be taking notes. Selfishly this article is mainly for my benefit, but hopefully anyone looking to take the AWS Cloud Practitioner exam will find this equally as valuable.</p><h3>AWS Basics</h3><p><strong>Why use AWS?</strong></p><p>With AWS, you have the ability to only pay for what you use. For example, you could use Amazon EC2 to launch as many or as few virtual servers as you need.</p><p><strong>What is Cloud Computing?</strong></p><p>Cloud computing is the on-demand delivery of IT resources over the internet with pay-as-you-go pricing.</p><p><strong>How is AWS able to offer pay-as-you-go?</strong></p><p>AWS separates different virtual machines from each other on the same hardware. So for example, my company and John’s company could be sharing the exact same physical server owned by AWS, but our virtual machines would still be completely separated. This ensures that servers are put to their highest and best use, allowing cheaper server costs to us as users than what we’d typically have to pay for to manage our own data server (unless my company becomes as big as Amazon).</p><h3>AWS EC2 Introduction</h3><p><strong>What OS can you use with EC2?</strong></p><p>You can use Windows or Linux OS.</p><p><strong>What software can you run on the EC2 instance?</strong></p><p>Almost anything. Software, databases, web apps, scripts, and more.</p><p><strong>What are the EC2 instance types?</strong></p><p>There are a variety of tasks that can be done, so different EC2 instances should be used for specific jobs.</p><p>Each instance type is grouped under an instance family, similar to how employees of a big company are run under teams (marketing, sales, engineering, HR, etc).</p><p><strong>What are the EC2 instance families?</strong></p><ol><li>General Purpose</li><li>Compute Optimized</li><li>Memory Optimized</li><li>Accelerated Computing</li><li>Storage Optimized</li></ol><p><strong>What is the General Purpose EC2 family used for?</strong></p><p>It’s can be used for diverse workloads, web servers, or code repositories.</p><p><strong>What is the Compute Optimized EC2 family used for?</strong></p><p>It is used for compute-intensive tasks like gaming servers or scientific modeling.</p><p><strong>What is the Memory Optimized EC2 family used for?</strong></p><p>Memory intensive tasks.</p><p><strong>What is the Accelerated Computing EC2 family used for?</strong></p><p>Floating point number calculation, graphics processing, streaming data, or data pattern matching.</p><p><strong>What is the Storage Optimized EC2 family used for?</strong></p><p>High performance for locally stored data.</p><p><strong>What are the EC2 purchase options?</strong></p><p>You can pay for it on demand (per hour or per second, depending on instance type and OS).</p><p>You can buy a savings plan (lower prices in exchange for a commitment of dollars per hour for 1 or 3 year term). This can save up to 72% of AWS cost.</p><p>You can also have reserved instances. These are good when you know you will need a steady amount of resources that is unlikely to change.</p><p>You can also pay for spot instances. These can offer up to 90% off the on demand cost, but AWS can stop your instance at any time (with a 2 minute warning to save your work). This is best used when your workflow can be interrupted such as batch workloads.</p><p>The final payment option is to pay for a dedicated host. No one else will share the host, and these are usually for compliance requirements.</p><p><strong>What is Elastic Load Balancing (ELB)?</strong></p><p>If you have multiple EC2 instances all running the same task, a load balancer makes sure that each EC2 instance has an even distribution of workload between them.</p><p>Elastic Load Balancing is the AWS service that automatically distributes incoming application traffic across multiple resources, like EC2 instances.</p><p><strong>Why would a tightly coupled architecture be bad and a loosely coupled architecture be good?</strong></p><p>If the architecture is tightly coupled, any errors with one application can cause cascading problems with any other applications it’s tightly coupled with. However, if it’s loosely coupled, errors in one app may not necessarily affect the other app.</p><p><strong>How can you create a loosely coupled architecture?</strong></p><p>You cna introduce a message queue between applications as a sort of buffer. The message queue takes in messages from App A and delivers them to App B when App B is ready. If App B fails, App A does not experience any disruption and the messages will remain in the message queue until App B is back and ready to handle them again.</p><p><strong>What are the 2 AWS services that act as message queues?</strong></p><p>AWS SQS (Simple Queue Service) and SNS (Simple Notification Service)</p><p><strong>What can AWS SQS do?</strong></p><p>SQS can send, store, and receive messages at any volume.</p><p><strong>What is a payload?</strong></p><p>A payload is the data contained within a message.</p><p><strong>What can AWS SNS do?</strong></p><p>It can send notifications and messages to “subscribers”, which can be phone numbers, email addresses, web servers, AWS Lambda Functions, and more.</p><p><strong>What does AWS Lambda do?</strong></p><p>Lambda is a serverless computing platform that can run your script after an event is triggered. It is also meant to run code for under 15 minutes, and is more suited for quick processing. You also won’t have to worry about scaling the environment either.</p><p>If you need access to the underlying environment, you need a container orchestration tool, such as AWS Elastic Container Service (ECS) or Elastic Kubernetes Service (EKS).</p><p><strong>What is a container?</strong></p><p>A container is package for your code. When you use a Docker container, it will be running on the EC2 instance.</p><p>If you want to host a traditional application and want access to the underlying OS, you’ll want to use AWS EC2.</p><p>If you are going to host short-running functions and don’t need access to the underlying environment at all, you’ll want to use AWS Lambda.</p><p>If you’d like to run Docker container-based workloads on AWS, you’ll need to choose AWS ECS or EKS, then you can run them on EC2 instances that you manage, or in a serverless environment like AWS Fargate that is managed for you.</p><h3>AWS Global Infrastructure</h3><p><strong>What is an availability zone and why would you want to run your application across multiple availability zones?</strong></p><p>An availability zone is a group of locations where AWS data centers are. They are spread out far enough so as not to have all of them fail at once in a disaster, but close enough to still have low-latency.</p><p>You’ll want to run your application/instance on at least 2 availability zones. In case something happens to one, you’ll have another zone up and running.</p><p><strong>What’s an edge location?</strong></p><p>An edge location is a site somewhere in the world that Amazon CloudFront uses to store cached copies of your content closer to your customers. So if your data is in the Ohio Region but you have customers in China, you can cache a copy of your data somewhere close to China so your customers in China will receive your data faster.</p><p><strong>How do you work with AWS?</strong></p><p>You can work with AWS resources using the Management Console, or the Command Line Interface (CLI), or Software Development Kits (SDK), or other tools.</p><p>The Management Console is on your browser.</p><p>You can create instances manually through the Management Console, but if you have to create multiple instances, you open yourself up to manual errors. The CLI can help automate these tasks.</p><p>The SDKs allow you to access AWS using a programming language.</p><p><strong>What is AWS Elastic Beanstalk?</strong></p><p>AWS Elastic Beanstalk helps you provision AWS EC2-based environments. You can assign your code and resource provision requirements to the Elastic Beanstalk service and it will create your environment for you.</p><p>It can also save your environment configurations to use again at a later time.</p><p><strong>What is AWS CloudFormation?</strong></p><p>AWS CloudFormation is an “infrastructure as code” tool that allows you to control and define many AWS resources using “CloudFormation Templates” in the form of JSON or YAML.</p><h3>AWS Networking</h3><p><strong>What is Amazon Virtual Private Cloud?</strong></p><p>Amazon VPC lets you create an isolated, virtual network that can either be public or private. It’s your own private network in AWS. You can deploy things like EC2 instances and your ELB in your VPC.</p><p><strong>What are Subnets?</strong></p><p>Subnets are chunks of IP addresses in your VPC that allow you to group resources together.</p><p><strong>What is an internet gateway?</strong></p><p>An internet gateway is like a door that lets public traffic into your VPC.</p><p><strong>What is a virtual private gateway?</strong></p><p>A VPG is a private gateway into your VPC that only lets traffic in from specific sources you choose (an approved network), such as from your on-premise data center.</p><p><strong>What is AWS Direct Connect?</strong></p><p>The problem with a virtual private gateway is you could still be subject to slowdowns when moving data across the internet. But with AWS Direct Connect, you can create the lowest latency and highest security dedicated fiber connection from your data center to AWS. This connects a physical line from your data center to your AWS VPC.</p><p><strong>What is a Network ACL?</strong></p><p>A Network Access Control List (ACL) controls what traffic is let into the subnet. The ACLs check traffic going in and out of the subnet. Only traffic that is approved beforehand is let in.</p><p><strong>What is a Security Group?</strong></p><p>A security group in an instance-level ACL, and only a specific-traffic-type that is approved beforehand is let in (like HTTPS or OS traffic).</p><p>The Network ACL is like a Passport Control Traffic officer checking traffic in and out of the country, while a Security Group checks traffic going into a building (but doesn’t care about traffic going out).</p><p>The Security Group is also <strong>statefull</strong> (while the Network ACL is <strong>stateless</strong>), which means the Security Group can remember which packets are already cleared for entry and therefore does not need to check a packet’s validity if it’s already been accepted through the instance before. Meanwhile, the Network ACL checks a packet’s validity every single time it passes through a subnet, regardless if it’s already been accepted before.</p><p><strong>What is Amazon Route 53?</strong></p><p>Route 53 is Amazon’s DNS.</p><p><strong>What is DNS?</strong></p><p>The Domain Name System translates website names into IP addresses that computers can read.</p><p><strong>What’s the CDN?</strong></p><p>The Content Delivery Network helps deliver edge content to users based on their geolocation.</p><h3>AWS Databases</h3><p><strong>What is instance storage?</strong></p><p>Instance storage is storage attached to the physical hardware running your instance, and can store temporary data. However, it is deleted the moment your instance stops running. It is fine to use with temporary data you don’t actually need to keep.</p><p><strong>What is Amazon Elastic Block Store?</strong></p><p>AWS EBS can create virtual hard drives that you can attach to your EC2 instance for purposes of storing data.</p><p>EBS volumes come in different sizes and types. When you create an EBS volume, you can define the size, type, and configurations. Then you can attach to your EC2 instance.</p><p><strong>What are snapshots?</strong></p><p>Snapshots are incremental backups, which your EBS volume should be doing regularly to backup your data.</p><p>Incremental backups are different from <strong>full backups. </strong>Incremental backups only backup data that has changed since the last backup (similar to how Git only tracks changes and not the entire repo every time you commit).</p><p><strong>What is Amazon Simple Storage Service?</strong></p><p>AWS S3 allows you to store and retrieve an unlimited amount of data. You store objects (like files) in buckets (like file directories). The maximum object size is 5 TB. You can also version objects so there is always a copy of the last version (similar to how Git can revert to a previous change or restore something that was deleted in the current commit).</p><p><strong>What are the different tiers of S3?</strong></p><p>The first is <strong>Amazon S3 Standard</strong>. This is standard storage, and is meant for frequent retrieval of data.</p><p>You can also use Amazon S3 static website hosting, where you can store multiple html files and other web assets into a bucket, and then host it a static website.</p><p>The next tier is <strong>Amazon S3 Standard-Infrequent Access (S3 Standard-IA)</strong>. This is good for long-term storage, backups, and recovery files. It still allows rapid retrieval of data, but is best for data that isn’t accessed frequently. It has a lower storage price than S3 standard, but higher retrieval price. A variation of this is <strong>Amazon S3 One Zone-Infrequent Access (S3 One Zone-IA)</strong>, which only stores your data on one availability zone (for a cheaper price).</p><p>Another tier is <strong>Amazon S3 Intelligent-Tiering</strong>. For an additional monitoring and automation fee, it will automatically move data to different tiers based on retrieval. For example, if an object in S3 Standard hasn’t been accessed for 30 consecutive days, Intelligent-Tiering will move it to the Infrequent Access tier.</p><p>Another tier is Amazon S3 Glacier, which archives data. There are different retrieval tiers: <strong>S3 Glacier Instant Retrieval</strong>, <strong>S3 Glacier Flexible Retrieval</strong> (able to retrieve objects from a few minutes to a few hours), and <strong>S3 Glacier Deep Archive</strong> (12–48 hours to retrieve data).</p><p>There is also <strong>Amazon S3 Outposts</strong>, which allow you to create buckets on AWS Outputs (this is good for meeting local data residency requirements).</p><p><strong>What is S3 Lifecycle Management?</strong></p><p>Amazon s3 Lifecycle Management is where you can automatically move data to different tiers. For example, if you wanted data to be accessible in S3 Standard for 90 days, then moved to Standard-IA for another 30 days, and then moved to S3 Glacier after that, lifecycle policies can do this automatically.</p><p><strong>How does object storage work?</strong></p><p>In object storage, each object consists of: data, metadata, and a key.</p><p>The data is the data itself you are storing. The metadata is data about the data. And the key is a unique identifier for the object.</p><p>As a note, if you modify a file in block storage, only the pieces that are changed are update. But if you modify a file in object storage, the entire object is updated.</p><p><strong>What is Amazon Elastic File System?</strong></p><p>Amazon EFS allows you to have multiple instances accessing the data in EFS at the same time.</p><p>You should use “file storage” over block storage or object storage when you have a large amount and services and resources that need to access the same data at the same time.</p><p><strong>What is Amazon Relational Database Service?</strong></p><p>Amazon RDS supports all the major relational database management systems (RDBMS) like MySQL, PostgreSQL, and more. Amazon RDS also automatically handles things for you like backups, redundancy, and disaster recovery.</p><p><strong>What is Amazon Aurora?</strong></p><p>It’s Amazon’s most managed RDBMS option and offers MySQL and PostgreSQL, and is 1/10th the cost of commercial databases. It also has data replication and up to 15 read replicas (to scale performance and helps with high volume read traffic). Amazon Aurora also automatically creates continuous backups to Amazon S3. Amazon Aurora is best if your workloads require high availability.</p><p><strong>What is Amazon DynamoDB?</strong></p><p>AWS DynamoDB is a serverless, non-relational, NoSQL database. This is great for datasets that have variations from item to item. You can query this database through key-value pair relationships (think JSON or Python Dictionaries).</p><p><strong>What is a Data Warehouse good for?</strong></p><p>A Data Warehouse can be good for historical data which we will want to run Business Intelligence Analytics on. Historical data is set and will never change, making a Data Warehouse a good place to store it.</p><p><strong>What is Amazon Redshift?</strong></p><p>Redshift is Amazon’s Data Warehouse.</p><p><strong>What is Amazon Database Migration Service?</strong></p><p>Amazon DMS can migrate data from one source database to another target database (which can be the same type or different type).</p><p>If the database types are the same, this is known as a homogenous migration, and is a one-step (one-click) process.</p><p>If the source and target database types are different, this is known as a heterogeneous migration. You’ll need to use the AWS Schema Conversion Tool first to convert the source schema and code to match that of the target database. Then you can use DMS to migrate into the target database.</p><p><strong>What are other use cases for Amazon DMS?</strong></p><ol><li>You can create a test database migration, so you can test applications against production data without affecting production users.</li><li>You can consolidate several databases into one database.</li><li>You can do continuous replication to send ongoing copies of your data to target sources (instead of a one-time migration).</li></ol><p><strong>What is Amazon DocumentDB?</strong></p><p>DocumentDB (which has MongoDB compatibility) is great for content management, user profiles, and catalogs.</p><p><strong>What is Amazon Neptune?</strong></p><p>Amazon Neptune is a graph database.</p><p><strong>What is Amazon Managed Blockchain?</strong></p><p>It is an immutable, blockchain-based database.</p><p><strong>What is Amazon Quantum Ledger Database?</strong></p><p>Amazon QLDB is an immutable ledger database, where any entry can never be removed.</p><p><strong>What are some ways to accelerate your database performance?</strong></p><p>You can add caching layers onto your database to improve read times from milliseconds to microseconds. Amazon ElastiCache can provide these caching layers.</p><p>If you’re using DynamoDB, you can use DynamoDB Accelerator (DAX) which can dramatically improve read times for your data.</p><h3>AWS Security</h3><p>AWS has a shared responsibility model. AWS is responsible for the security <strong>of</strong> the cloud, and the user is responsible for the security <strong>in</strong> the cloud.</p><p><strong>What exactly are AWS and the user responsible for?</strong></p><p>AWS is responsible for the security of the hardware, network, and hypervisor (the software that creates virtual machines).</p><p>The user is responsible for the security of the operating system, your application, and your data.</p><p><strong>What is the AWS account root user?</strong></p><p>The root user has access and control of any resource in the account. It is important to also implement MFA (multi-factor authentication).</p><p><strong>What is AWS IAM?</strong></p><p>AWS Identity and Access Management (IAM) is a way to manage and control access to resources. You can create IAM users, and by default, will have no permissions.</p><p>You should follow the principle of least privilege: A user should be granted access only to what they need.</p><p><strong>What are IAM groups?</strong></p><p>IAM groups are groups of users with the same permissions (which are implemented via policies).</p><p><strong>What are roles in IAM?</strong></p><p>Roles have associated permissions that allow or deny specific actions (and can be assumed for temporary amounts of time). They are basically temporary permissions for users.</p><p><strong>What are AWS Organizations?</strong></p><p>AWS Organizations is a central location to manage multiple AWS accounts. It can also consolidate billing (using the primary account to pay for all accounts). You can also create hierarchical groupings of accounts. You will also have control over the AWS services and APIs that each account can access.</p><p>You can use Service Control Policies (SCPs) to specify the maximum permissions for accounts in the organization. SCPs can applied to Organizations Units (OUs) or individual member accounts.</p><p>IAM policies can be applied to IAM users, IAM groups, and IAM roles.</p><p><strong>What is AWS Artifact?</strong></p><p>AWS Artifact is a place where you can request documents proving that AWS is compliant with compliance.</p><p>You can also sign an <strong>AWS Artifact Agreement</strong> for certain compliance laws, such as HIPAA.</p><p>You can also access evidence of AWS security controls through <strong>AWS Artifact Reports</strong>.</p><p><strong>What is the Customer Compliance Center?</strong></p><p>The Customer Compliance Center is a place that contains resources to help you learn more about compliance.</p><p><strong>What is DDoS?</strong></p><p>DDoS stands for distributed denial of service, and is an attack on your infrastructure. It tries to overwhelm your system to the point it can no longer operate.</p><p><strong>What is a Slowloris attack?</strong></p><p>A Slowloris attack is a type of DDoS attack where the bad-acting client takes a very long time sending packets to the server. This is similar to how someone ordering a coffee shop and taking a very long time to order can create a long line of people waiting to give their order (essentially “clogging” the server). Because the Slowloris never finishes its request, the server will remain open, fill up their maximum concurrent connection pool, and eventually deny service from any other clients.</p><p><strong>How does AWS architecture help prevent DDoS attacks?</strong></p><p>Security groups only allow traffic which you specify. Security groups operate at the AWS network level (not at the EC2 instance level). If the traffic isn’t what you approved, it isn’t let in to clog the server.</p><p><strong>What is AWS Shield and what is AWS WAF?</strong></p><p>AWS WAF uses a web application firewall to filter incoming traffic with the signatures of bad actors (it uses a web access control list, or web ACL). It has ML abilities and can detect threats as they evolve.</p><p>AWS Shield provides DDoS protection. It is free if you don’t use the Advanced version.</p><p><strong>What is Encryption?</strong></p><p>Encryption secures your data in a way that only authorized parties can access it.</p><p><strong>What is AWS KMS?</strong></p><p>AWS Key Management Service manages your encryption keys.</p><p><strong>What is Amazon Inspector?</strong></p><p>Amazon Inspector helps improve security and compliance of your applications by running an automated security assessment against your infrastructure. It exposes your vulnerabilities.</p><p>It consists of 3 parts:</p><ol><li>A network configuration reachability piece,</li><li>An Amazon agent, and</li><li>A security assessment service</li></ol><p><strong>What is Amazon GuardDuty?</strong></p><p>Amazon GuardDuty analyzes your metadata to identify threats. It runs independently and does not affect performance of your workloads.</p><h3>AWS Monitoring and Analytics</h3><p><strong>What is monitoring?</strong></p><p>Monitoring means observing systems, collecting metrics, and then using that data to make decisions.</p><p><strong>What is Amazon CloudWatch?</strong></p><p>CloudWatch allows you to monitor your AWS infrastructure and your applications in real-time.</p><p>You can create a CloudWatch alarm to alert you once an event or metric is triggered. You can connect it to AWS SNS to send a message to a user to alert them as well.</p><p>You can create a CloudWatch dashboard to show us everything we want in one place.</p><p><strong>What is AWS CloudTrail?</strong></p><p>CloudTrail is an API auditing tool. Every request made to AWS gets logged in the CloudTrail engine (who made it, when, what was the IP address, and what was the response, was the request denied, etc).</p><p>You can also enable <strong>CloudTrail Insights</strong>, which can detect unusual API activities in your account.</p><p><strong>What is AWS Trusted Advisor?</strong></p><p>AWS Trusted Advisor is an automated advisor that evaluates your resources against 5 pillars:</p><ol><li>Cost optimization</li><li>Performance</li><li>Security</li><li>Fault tolerance</li><li>Service limits</li></ol><h3>AWS Pricing and Support</h3><p><strong>AWS Free Tier</strong></p><p>AWS Free Tier offers 3 ways to try out AWS:</p><ol><li>Always free (only some services)</li><li>12-months free</li><li>Trials (short-term free trials)</li></ol><p>Here are some examples:</p><p>AWS Lambda allows 1 million free requests per month (and up to 3.2 million seconds of compute time… that’s 888 hours).</p><p>AWS S3 is free for 12 months for up to 5 GBs of storage.</p><p>AWS Lightsail offers a 1 month trial of up to 750 hours of usage.</p><p>A few more examples are AWS SageMaker, DynamoDB (25 GB of free storage per month), SNS, and more.</p><p><strong>AWS Support Plans</strong></p><p>There are 4 different types of support plans: Basic, Developer (email access to support), Business (phone access to support), and Enterprise (15-minute response time for mission-critical workloads, and dedicated Technical Account Manager (TAM)).</p><p><strong>What are the 5 pillars of the Well-Architected Framework?</strong></p><ol><li>Operational excellence</li><li>Security</li><li>Reliability</li><li>Performance efficiency</li><li>Cost optimization</li></ol><p>A TAM can also review your account and suggest changes based on the 5 pillars of the well-architected framework.</p><p><strong>What is AWS Marketplace?</strong></p><p>AWS Marketplace is a catalog that includes software from thousands of independent vendors that can run on AWS.</p><h3>AWS Migration and Innovation</h3><p><strong>What is AWS CAF?</strong></p><p>The AWS Cloud Adoption Framework is a framework to help users migrate on-premise data (or cloud data) into AWS.</p><p>The CAF has 6 perspectives:</p><ol><li>Business</li><li>People</li><li>Governance</li><li>Platform</li><li>Security</li><li>Operations</li></ol><p><strong>What are the 6 R’s of migration?</strong></p><p>Once you know exactly what you have in your existing environment, you decide which of the 6 R’s are best for your migration:</p><ol><li>Rehosting (lift and shift) — Simply lifting your app/infrastructure and shifting it to AWS</li><li>Replatforming (lift, tinker, and shift) — You may make a few cloud optimizations first before lifting and shifting to the cloud</li><li>Retire — Some parts of your infrastructure may no longer be needed</li><li>Retain — Some parts of your infrastructure may need to be retained on-premise but not necessarily migrated to AWS (and can be retired eventually)</li><li>Repurchase — Abandon legacy software and move to something new on the cloud</li><li>Refactoring — You’ll need to write new code, you’ll need to add new features, and likely change the architecture of the code to make sure everything works once moved to AWS</li></ol><p><strong>What is the AWS Snow Family?</strong></p><p>The AWS Snow Family is a collection of physical devices that help physically transport data into and out of AWS. For example, Amazon can ship you AWS Snowcone, you plug it into your data server or computer, copy all the data you’d like onto it, then ship it back to Amazon. Then, you will find all of your data copied into an S3 bucket, as an example.</p><p><strong>AWS Snowcone</strong> is the smallest, holding up to 8 TB of storage.</p><p><strong>AWS Snowball</strong> is the next biggest and comes in 2 versions: Storage-optimized (80 TB) and Compute-optimized (42 TB).</p><p><strong>AWS Snowmobile</strong> is the biggest and is delivered via truck, holding up to 100 Petabytes (100,000 TB).</p><h3>AWS Cloud Wrap-Up</h3><p>What is the AWS Well-Architected Framework?</p><ol><li>Operational excellence — Ensuring your architect delivers business value and continual improvement</li><li>Security — Protecting your data and systems with encryption</li><li>Reliability — Focuses on recovery planning from failure or disruption of infrastructure or AWS, as well as being able to scale horizontally</li><li>Performance efficiency — Choosing the right services (and the right types of a chosen service) for efficiency</li><li>Cost optimization — Optimizing for cost</li><li>Sustainability — Reducing energy consumption by minimizing the total resources needed an maximizing the benefits from the resources you are using</li></ol><p><strong>What is the AWS Well-Architected Tool?</strong></p><p>The Well-Architected Tool is a tool you can run against your framework which can help check if your architecture meets the Well-Architected Framework standards (and can note areas of improvement).</p><p><strong>What are the 6 main benefits of using AWS?</strong></p><ol><li>Trade fixed expense for variable expense (pay-as-you-go)</li><li>Benefit from massive economies of scale</li><li>Stop guessing capacity</li><li>Increase speed and agility</li><li>Stop spending money running data centers</li><li>Go global in minutes</li></ol><h3>Additional Notes</h3><p><strong>What are shared controls?</strong></p><p>Shared controls are controls where both AWS and the user share responsibility, such as:</p><ol><li>Patch management</li><li>Configuration management</li><li>Awareness and training</li></ol><p><strong>Note about S3</strong></p><p>S3 cannot be scaled manually, it is instead scaled automatically. It can also provide unlimited storage for any type of data, but each individual object does have a maximum size of 5 TB. It is “infinitely scalable.”</p><p><strong>Why use Amazon ElastiCache?</strong></p><p>ElastiCache is a web service that makes it easy to deploy and manage an in-memory data store or cache in the cloud. It’s great for applications that need fast retrieval of data (querying a database is always slower than getting a copy of that data in the cache).</p><p><strong>What are the 3 AWS Cloud Computing Models?</strong></p><p>The 3 AWS Cloud Computing Models are:</p><ol><li>Infrastructure as a Service (IaaS)</li><li>Platform as a Service (PaaS)</li><li>Software as a Service (SaaS)</li></ol><p>Note: Networking is a part of Infrastructure as a Service.</p><p><strong>What is an AWS-Managed Service?</strong></p><p>An AWS-managed service is a service where AWS is responsible for the operational and maintenance burdens of running them.</p><p>Examples are services like DynamoDB, Lambda, Elastic MapReduce, S3, and more.</p><p>IAM , VPC, and EC2 are NOT examples, since you are the one responsible for managing them.</p><p><strong>What is Infrastructure Event Management?</strong></p><p>Infrastructure Event Management is a short-term service you can get from AWS Support (which is included in the Enterprise Support plan and available for purchase in the Business Support plan) that helps provide architectural guidance for big traffic events (like product launches and advertising launches).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3131f4c68a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Predictive Models (Random Forest, XGBoost, and Grid Search) To Predict A Movie’s Box…]]></title>
            <link>https://medium.com/@austinwolff/building-predictive-models-random-forest-xgboost-and-grid-search-to-predict-a-movies-box-7d7b7c8f4732?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d7b7c8f4732</guid>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[gridsearchcv]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 05:22:11 GMT</pubDate>
            <atom:updated>2021-11-15T05:22:11.591Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Predictive Models (Random Forest, XGBoost, and Grid Search) To Predict A Movie’s Box Office</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arqbKoq520aQkcAnHE5Y7A.jpeg" /><figcaption>Photo by Michael Krahn on Unsplash</figcaption></figure><p>This is a follow-up to <a href="https://www.linkedin.com/pulse/using-multiple-linear-regression-examine-what-variables-austin-wolff/">my previous article</a>, where I found the variables most correlated with a movie’s box office success. Recently, I tested numerous machine learning models to learn which model performed the best when predicting our target (a movie’s box office). I will detail which models I used and their associated results below.</p><p><strong>And if you’d like to see this deployed model in action and predict your own movie’s box office, </strong><a href="https://box-office-predictions-usa.herokuapp.com/"><strong>click here</strong></a><strong>.</strong></p><h3>Cleaning The Data</h3><p>But first, I had to clean and organize my data. I pulled data from IMDb’s open database, which they update once per day. The dataset was millions of rows long, so I had to use Dask to help my poor MacBook Air process the data.</p><p>I narrowed the dataset down to only movies released in the US between 1980–2020, then merged it with another dataset from TMDB, which contained details regarding budget and box office that IMDb’s dataset didn’t have.</p><p>Like most machine learning projects, getting, cleaning, and preparing the data took about 80% of the total project time.</p><h3>Feature Engineering</h3><p>Based on my previous article, I knew there was a correlation between a movie’s box office and the previous box office success of the actors and director associated with said movie. Here is the simple equation I used to quantify that number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*cVsU75CRxiAzk7pNM-Pj3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*d2c_4iijk0zJCN3mD5lr6A.png" /></figure><p>I simply calculated the average box office associated with every actor and director for their top 4 movies then added those numbers together (the avg. gross for the star actor and the avg. gross for the director) of each movie to get the “Total Gross Bankability.”</p><h3>Data Leakage</h3><p>The “Total Gross Bankability” is the only feature that has possible data leakage, as it takes the box office of an actor’s previous top movies. However, this can incorporate target data into our feature.</p><p>To remove data leakage, it would be good to only calculate the avg. gross for an actor for all movies released before the target movie (after all, if we were to use this in the real world, we wouldn’t have access to the box office of future movies an actor would be in).</p><h3>Finding Our Baseline With Dummy Regression</h3><p>After splitting the training and testing data, I started with our baseline.</p><pre>model_baseline = make_pipeline( <br>OneHotEncoder(use_cat_names=True), <br>DummyRegressor() <br>)</pre><p>Then I used cross validation to help evaluate the metrics.</p><pre>scoring = [&#39;neg_mean_absolute_error&#39;,&#39;neg_mean_absolute_percentage_error&#39;,&#39;r2&#39;] </pre><pre>cv_baseline = cross_validate( model_baseline, X_train, y_train, scoring=scoring, cv=5 ) </pre><pre>cv_mae_baseline = -cv_baseline[&#39;test_neg_mean_absolute_error&#39;].mean() </pre><pre>cv_mape_baseline = -cv_baseline[&#39;test_neg_mean_absolute_percentage_error&#39;].mean() </pre><pre>cv_r2_baseline = cv_baseline[&#39;test_r2&#39;].mean() </pre><pre>print(&#39;Baseline MAE:&#39;, &#39;{:,}&#39;.format(cv_mae_baseline.round(2))) print(&#39;Baseline MAPE:&#39;, &#39;{:,}&#39;.format(cv_mape_baseline.round(6))) print(&#39;Baseline R2 score:&#39;, &#39;{:,}&#39;.format(cv_r2_baseline.round(6)))</pre><p>Below were the printed results:</p><pre>Baseline MAE: 93,947,168.94 <br>Baseline MAPE: 282.409473 <br>Baseline R2 score: -0.000994</pre><p>Due to the high variance of the target column, I decided my key metric was going to be the R2 score and not MAE. However, I kept printing the mean absolute error and mean absolute percentage error for reference. Now that I had my baseline, it was time to use other well-known machine learning models.</p><h3>Using Linear Regression</h3><p>I made my linear model and reused most of the code above with some slight variations.</p><pre>model_lr_1 = make_pipeline( <br>OneHotEncoder(use_cat_names=True), <br>SimpleImputer(strategy=&#39;mean&#39;), <br>LinearRegression() <br>)</pre><p>After cross-validating and scoring, below were the printed results:</p><pre>Linear Regression (1) MAE: 455,712,698.77 <br>Linear Regression (1) MAPE: 178.76018 <br>Linear Regression (1) R2 score: -14,205.471755</pre><p>Linear Regression performed <strong>worse</strong> than the baseline! I tried again, this time scaling my data, to see if that made a difference.</p><pre>model_lr_2 = make_pipeline( <br>OneHotEncoder(use_cat_names=True), <br>SimpleImputer(strategy=&#39;mean&#39;), <br>StandardScaler(), <br>LinearRegression() <br>)</pre><p>Printed results:</p><pre>Linear Regression (2) MAE: 4.039487079675694e+17 <br>Linear Regression (2) MAPE: 3,207,677,317,315.1016 <br>Linear Regression (2) R2 score: -3.033014419394398e+22</pre><p>Scaling the data made it much worse. This is likely because there is a lot of variance in the data, as most movies make little money, while some make over 1,000 times that of others.</p><p>Next, I tried Ridge Regression.</p><h3>Using Ridge Regression</h3><p>Unfortunately with Ridge, we had to scale the data.</p><pre>model_ridge_1 = make_pipeline( <br>OneHotEncoder(use_cat_names=True), <br>SimpleImputer(strategy=&#39;mean&#39;), <br>StandardScaler(), <br>Ridge() <br>)</pre><p>But fortunately, it made quite a positive difference. Here are the printed results:</p><pre>Ridge Regression (1) MAE: 64,164,252.9 <br>Ridge Regression (1) MAPE: 130.469053 <br>Ridge Regression (1) R2 score: 0.5957777</pre><p>I tried a few different alpha values for Ridge, but it didn’t make too much of a difference.</p><pre>model_ridge_2 = make_pipeline( <br>OneHotEncoder(use_cat_names=True), <br>SimpleImputer(strategy=&#39;mean&#39;), <br>StandardScaler(), <br>Ridge(alpha=100) <br>)</pre><p>Here were the new scores:</p><pre>Ridge Regression (2) MAE: 63,796,418.02 <br>Ridge Regression (2) MAPE: 128.287068 <br>Ridge Regression (2) R2 score: 0.595994</pre><p>It barely made a difference. I could’ve used Grid Search to find the optimal hyperparameters, but I wanted to try a tree-based model first.</p><p>I had a hunch tree-based models would outperform linear regression models because scoring a big box office is not necessarily linear, and there are other interactions at play like story, the star power of the movie, and word-of-mouth advertising. Below proves my hunch right.</p><h3>Using Random Forest</h3><p>I built the first model using an Ordinal Encoder for my categorical variables.</p><pre>model_forest_1 = make_pipeline( <br>OrdinalEncoder(), <br>SimpleImputer(strategy=&#39;mean&#39;), <br>RandomForestRegressor() <br>)</pre><p>Here were the scores:</p><pre>Random Forest (1) MAE: 45,806,089.2 <br>Random Forest (1) MAPE: 63.284248 <br>Random Forest (1) R2 score: 0.6850748</pre><p>The scores were already much better, and I didn’t even tune any hyperparameters yet! Next I tried One Hot Encoding to see if that made a difference.</p><pre>model_forest_2 = make_pipeline( <br>OneHotEncoder(use_cat_names=True), <br>SimpleImputer(strategy=&#39;mean&#39;), <br>RandomForestRegressor() <br>)</pre><p>The scores:</p><pre>Random Forest (2) MAE: 44,759,313.8 <br>Random Forest (2) MAPE: 48.350349 <br>Random Forest (2) R2 score: 0.6904746</pre><p>One Hot Encoding gave better metrics than Ordinal, so I stuck with that.</p><h3>Using Grid Search</h3><p>To find the optimal hyperparameters, I used GridSearchCV() on “model_forest_2.” Instead of testing all parameters in an iterative range, instead I used parameter extremes to lower computation time but without leaving things to chance using Random Search.</p><pre>params = { &quot;simpleimputer__strategy&quot;: [&#39;mean&#39;,&#39;median&#39;], &quot;randomforestregressor__n_estimators&quot;: [75, 100, 200], &quot;randomforestregressor__max_depth&quot;: [None, 100], &quot;randomforestregressor__min_samples_leaf&quot;: [1, 0.1], <br>} </pre><pre>model_grid_rf = GridSearchCV( <br>model_forest_2, <br>param_grid = params, <br>n_jobs=-1, <br>cv=5, <br># verbose=3 <br>) </pre><pre>model_grid_rf.fit(X_train, y_train) </pre><pre>print(model_grid_rf.best_params_)</pre><p>Here were the printed hyperparameters:</p><pre>{&#39;randomforestregressor__max_depth&#39;: None, &#39;randomforestregressor__min_samples_leaf&#39;: 1, &#39;randomforestregressor__n_estimators&#39;: 100, &#39;simpleimputer__strategy&#39;: &#39;mean&#39;}</pre><p>The hyperparameters ended up just being the default values. For clarification, I built a third model and explicitly stated the hyperparameters:</p><pre>model_forest_3 = make_pipeline( <br>OneHotEncoder(use_cat_names=True), <br>SimpleImputer(strategy=&#39;mean&#39;), RandomForestRegressor(max_depth=None, <br>min_samples_leaf=1, <br>n_estimators=100 ) <br>)</pre><p>Here were the printed results:</p><pre>Random Forest (3) MAE: 44,809,586.4 <br>Random Forest (3) MAPE: 53.607505 <br>Random Forest (3) R2 score: 0.6880779</pre><p>All 3 scores were a little worse. This is most likely due to the randomness of the regression, as we would most likely get a different result every time anyway. Regardless, to be conservative, we will stick with these values for reporting.</p><h3>XGBoost</h3><p>Then I tried XGBoost. I tuned the hyperparameters using GridSearchCV:</p><pre>xgb_params = { &quot;xgbregressor__max_depth&quot;: [3,6,10], &quot;xgbregressor__learning_rate&quot;: [0.01,0.1,0.3], &quot;xgbregressor__n_estimators&quot;: [100, 500, 1000], &quot;xgbregressor__colsample_bytree&quot;: [0.1, 0.5, 1] <br>} </pre><pre>xgb_grid_1 = GridSearchCV(<br>model_xgb_1, <br>param_grid=xgb_params, <br>n_jobs=-1, <br>scoring=&#39;r2&#39;, <br>cv=2, <br>verbose=3) </pre><pre>xgb_grid_1.fit(X_train, y_train)</pre><p>Then I printed the results:</p><pre>XGBoost (2) MAE: 45,012,162.4 <br>XGBoost (2) MAPE: 56.752657 <br>XGBoost (2) R2 score: 0.700572</pre><p>The MAE and MAPE scores were a little worse, but the R2 Score was better. So I used this model on the testing data, and compared it to the Random Forest Model:</p><pre>Random Forest R2 (Test) = 0.68125 <br>XGBoost R2 (Test) = 0.7136502</pre><p><strong>The XGBoost performed the best!</strong> This is not surprising as it’s the most common model used to win Kaggle Competitions.</p><h3>Results</h3><p>While Random Forest beat the Linear Regression models, XGBoost still outperformed them all. This will be yet another example of the “out-of-the-box” adaptability of the XGBoost model.</p><p>For those curious what the top features were, here is a “feature importances” graph, pulled from the Random Forest model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*k04gWKBkpWI0Xd8cF-rJew.png" /></figure><p>As you can see, “budget” was by far the most important feature, with “Total_Gross_Bankability” coming in second.</p><h3>Further Research</h3><p>Limitations of my analysis include missing data in all rows, which either had to be dropped or ignored. The dataset also only included movies released in the USA between 1980–2020, and excluded any movies released by streaming companies ( <em>like Netflix-originals, since their business model is not built around “box office”</em>).</p><p>Area for further research include calculating the Total Gross Bankability based on the movies released previous to one we are trying to predict, log-transforming the box office to test if that impacts the R2 score, and removing movies classified as outliers in a box-plot model (those with box offices more than 1.5 times the interquartile ranges).</p><p><strong>If you’d like to predict what your own movie’s box office could be,</strong> <a href="https://box-office-predictions-usa.herokuapp.com/"><strong>check out the app I made</strong></a><strong> based on this very model!</strong></p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/building-predictive-models-random-forest-xgboost-grid-austin-wolff/?published=t"><em>https://www.linkedin.com</em></a><em>.</em></p><p><em>You can check out </em><a href="https://github.com/AustinJamesWolff"><em>my GitHub</em></a><em>. For convenience, you can see the entire notebook referenced above </em><a href="https://github.com/AustinJamesWolff/Data-Science-Portfolio/tree/main/Box_Office_XGBoost_Regression"><em>right here</em></a><em>. To see more Data Science projects, follow me on GitHub or connect with me on </em><a href="https://www.linkedin.com/in/austin-james-wolff/"><em>LinkedIn</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d7b7c8f4732" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Multiple Regression To Examine What Variables Are Most Correlated With A Movie’s Box Office…]]></title>
            <link>https://medium.com/@austinwolff/using-multiple-linear-regression-to-examine-what-variables-drive-a-movies-box-office-success-the-93f5c8174078?source=rss-db21aa43a93e------2</link>
            <guid isPermaLink="false">https://medium.com/p/93f5c8174078</guid>
            <category><![CDATA[dask]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Austin Wolff]]></dc:creator>
            <pubDate>Thu, 14 Oct 2021 23:08:53 GMT</pubDate>
            <atom:updated>2021-10-20T02:20:26.421Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Multiple Regression To Examine What Variables Are Most Correlated With A Movie’s Box Office Success</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*4YnE9t2G30jZE-D_HeeA1A.jpeg" /><figcaption>Photo by <a href="https://www.mctv.com.au/mctv-shines-in-half-yearly-box-office/">MCTV</a></figcaption></figure><p>When asked how movie executives know if their film would make money or not, Hollywood-legend William Goldman once said,</p><blockquote>“Nobody knows anything.”</blockquote><p>But surely there are independent variables that are more correlated with box office than others. I was personally motivated to find this out: I’m a filmmaker too, and I’d much rather make money than lose money with my movie.</p><p>So my goal was to analyze the Pearson Correlation Coefficients to determine just how correlated each independent variable is with a movie’s gross revenue, in hopes of one day replicating the box office success of movies I love.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*35QRuTV1pn6t7YEgdyVhJg.jpeg" /><figcaption>Photo by AZQuotes.com</figcaption></figure><h3>Getting The Data</h3><p>The most comprehensive movie database on the internet is probably the aptly name Internet Movie Database, or IMDb.com. They have a relational database accessible by downloadable zip files on their website, which is updated every day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*LeZx0iZbcgWshKdKutjyEw.png" /><figcaption>Example RDBMS from the <a href="https://relational.fit.cvut.cz/dataset/IMDb">Relational Dataset Repository</a></figcaption></figure><p>The files were millions of rows long, so in order to wrangle the data in Jupyter, I imported Dask to use parallel processing. I merged the “relational dataframes” based on their primary keys, then I double-checked a few rows.</p><pre># Testing to see if the DataFrame also holds my own IMDb credits!</pre><pre>imdb_all_data.loc[imdb_all_data[&quot;primaryName&quot;] == &quot;Austin James Wolff&quot;].compute()</pre><p>After I merged the tables, I converted the Dask DataFrame back into Pandas to continue the analysis.</p><h4>Limitations To The Dataset</h4><p>IMDb’s dataset, while massive, was still missing many variables I needed, such as Rating, Score, and Budget. So I pulled a public dataset from Kaggle which contained the variables I needed, but only for movies from the years 1980–2020.</p><h4>Data Wrangling and Feature Engineering</h4><p>First, I removed all non-US movies. Then I converted the release date column to a datetime with Pandas and some help from regular expressions (this column was quite dirty). I also created a column for “profit” (gross revenue - budget).</p><p>Now came the interesting part. It is common knowledge in the industry that your movie is more likely to make more money if you have “<strong>star power</strong>,” an esoteric measure of the popularity of your top actors. This can also apply, to some extent, to the popularity of the director (think Christopher Nolan or Quentin Tarantino).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGa4gT00L2Jmpr8iMQvL2g.jpeg" /><figcaption>Photo by <a href="https://www.complex.com/pop-culture/quentin-tarantino-movies-ranked/">Complex</a></figcaption></figure><p>I wanted to quantify this “bankability.” So I adapted an algorithm from my colleague Ravi Gupta and made some slight modifications[1]. (You can find his algorithm <a href="https://towardsdatascience.com/predicting-movie-profitability-and-risk-at-the-pre-production-phase-2288505b4aec">here</a>. His entire post is quite brilliant and I highly recommend it!)</p><p>So I created a new DataFrame with just actors and directors, and mapped their top 4 movies they were known for, along with each movies’ gross revenue and profit. Then I took the average of the gross and profit for each actor and director.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*3yFjezvxKvc7DRckXQR8Sg.png" /></figure><p>For each movie, I added the Average Gross the top billed actor was known for with the Average Gross of the director to get “Total Gross Bankability.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*LhZt8AEfqaeRcI-nE3dK2A.png" /></figure><p>I decided we should add the the mean bankability of the actor with the director to account for people wanting to see a movie because of a particular actor and not necessarily the director, and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*A_wC13b8T9wvn7oCMfrgqQ.png" /></figure><p>I repeated the same process for profit. Now we have two new “bankability” coefficients for each movie we can use in our data analysis to test for correlation.</p><p>This is a very simple equation, and quantifying “bankability” for an actor, director, and “total star power” for a movie is certainly worth exploring in the future.</p><blockquote>At this point, we had all the features necessary for our analysis.</blockquote><h3>Statistical Methods Used</h3><p>There were quite a few statistical models used. First, I thought it necessary to remove outliers, as there are a handful of movies with box offices of over $1 Billion, that already affect our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*CrrYrmFVSRGofG689AsEqg.png" /><figcaption>Outliers are already affecting our models</figcaption></figure><p>A few James Cameron movies (Titanic, Avatar) and Marvel “Tentpole Movies” (The Avengers, Avengers: Infinity War, Avengers: Endgame) would be considered outliers.</p><pre># Current gross mean, including outliers</pre><pre>gross_mean = df_movies[&#39;gross&#39;].mean().round(2)<br>print(&#39;Gross Mean:&#39;, &quot;{:,}&quot;.format(gross_mean))</pre><pre># Current gross standard deviation</pre><pre>gross_std = df_movies[&#39;gross&#39;].std().round(2)<br>print(&#39;Gross Standard Deviation:&#39;, &quot;{:,}&quot;.format(gross_std))</pre><p><strong>Gross Mean:</strong> 82,468,351.51</p><p><strong>Gross Standard Deviation:</strong> 168,082,426.51</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Lq8rfO_M3KiQfNfkcssRuw.jpeg" /><figcaption>Box Office: $2.789 Billion</figcaption></figure><h4>Removing Outliers</h4><p>I classified outliers as movies with box offices more than 3 standard deviations away from the mean.</p><pre># Calculate Z-Score</pre><pre>df_movies[&#39;Z_Score&#39;] = np.abs(stats.zscore(df_movies[&quot;gross&quot;]))</pre><pre># Filter out outliers and make a deepcopy</pre><pre>df_less_outliers = copy.deepcopy(df_movies[df_movies[&#39;Z_Score&#39;] &lt; 3])</pre><p>Now let’s calculate the new mean and standard deviation.</p><pre>gross_mean_less_3sigma = df_less_outliers[&#39;gross&#39;].mean().round(2)<br>print(&#39;Gross Mean:&#39;, &quot;{:,}&quot;.format(gross_mean_less_3sigma))</pre><pre>gross_std_less_3sigma = df_less_outliers[&#39;gross&#39;].std().round(2)<br>print(&#39;Gross Standard Deviation:&#39;, &quot;{:,}&quot;.format(gross_std_less_3sigma))</pre><p><strong>Gross Mean:</strong> 63,085,873.0</p><p><strong>Gross Standard Deviation:</strong> 98,445,947.42</p><p>The gross mean decreased by about 20 Million, and the Gross Standard Deviation decreased by about 70 Million. Let’s look at our histogram again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*471Kd0rz_90VZ7Mo8LiU9g.png" /><figcaption>Box office of movies released, less outliers greater than 3-sigma from the mean</figcaption></figure><p>This looks a little better. Common domain knowledge states that most movies make little to no money, so at first glance this graph appears to accurately represent the filmmaking industry.</p><p>Now let’s return to the question of the article: What variables drive box office the most?</p><h4>My Hypotheses</h4><p>Because this was an EDA, there are multiple hypotheses. First, I must test the statistical significance of the linear relationship between each variable and the gross.</p><p>We’ll start by defining a null and alternative hypothesis for “budget,” the variable I think most correlates to box office. The null hypothesis is that the movie’s budget and box office have a linear relationship of 0 and <strong>are not</strong> statistically significantly associated with one another, with an alpha = 0.05.</p><blockquote>H₀: β₁ = 0</blockquote><blockquote>H₁: β₁ ≠ 0</blockquote><p>The alternative hypothesis is the linear relationship of the budget and box office is <strong>not</strong> <strong>0</strong> and are statistically significantly associated with one another.</p><p>We’ll use linear regression:</p><pre>from statsmodels.formula.api import ols<br>model = ols(&quot;gross ~ budget&quot;, data=df_clean_movies).fit()<br>print(model.summary())</pre><p><strong>R-squared:</strong> 0.466</p><p><strong>Adj. R-squared:</strong> 0.466</p><p><strong>Slope:</strong> 2.11</p><p><strong>P-value:</strong> 0.000</p><p>Because the P-Value is less than the alpha (p &lt; 0.05) we reject the null hypothesis and <strong>can conclude there is a statistically significant association between a movie’s budget and box office.</strong></p><p>But all we did was conclude something that is common knowledge. What I’m looking for is the measure of correlation for each variable (we can test for statistically significant association afterwards).</p><pre># This will show us correlation of our variables</pre><pre>df_clean_movies.corr().sort_values(by=&quot;gross&quot;, ascending=False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*F0UZt32IHpSWHGnz1ytQZw.png" /></figure><p>From this table, we can see that “<strong>profit</strong>” has the highest correlation to “gross” (unsurprisingly) with a coefficient of <strong>0.96</strong>.</p><p>The next highest is “<strong>budget</strong>” with a correlation coefficient of <strong>0.68</strong>.</p><p>The third highest is “<strong>Total_Gross_Bankability</strong>”, our engineered feature to represent the “total star power” of the actor and director, with a correlation coefficient of <strong>0.45</strong>.</p><p>Let’s test the statistical significance of the relationship of “gross” and “Total_Gross_Bankability” while keeping budget in account, with an alpha = 0.05.</p><blockquote>H₀: β₁ = 0</blockquote><blockquote>H₁: β₁ ≠ 0</blockquote><pre>model2 = ols(&quot;gross ~ budget + Total_Gross_Bankability&quot;, data=df_clean_movies).fit()<br>print(model2.summary())</pre><p><strong>R-squared:</strong> 0.501 (an increase)</p><p><strong>Adj. R-squared:</strong> 0.500 (an increase)</p><p><strong>Slope:</strong> .09</p><p><strong>P-value:</strong> 0.000</p><p>Because the P-Value is less than the alpha (p &lt; 0.05) we reject the null hypothesis and <strong>can conclude there is a statistically significant association between a movie’s “Total Gross Bankability” and box office, while keeping budget into account.</strong></p><h3>Results</h3><p>This analysis concludes the variable with highest correlation and statistically significant association to a movie’s box office is its budget. This is not that surprising to me.</p><p>What is surprising, however, is this analysis also concludes that there is a statistically significant association between box office and “star power” bankability (titled “Total_Gross_Bankability” in the DataFrame).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*ZnoKDzWMugkACsNCPdQRJw.png" /><figcaption>Regardless, most movies still make little money</figcaption></figure><p>Remember, “Total Gross Bankability” was a feature engineered by taking the average box office of the 4 most popular movies an actor/director was known for on their IMDb page. Because the correlation coefficient was 0.45, it might be worth exploring in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*kISwQvVyQxFxiEBMRgLOqQ.png" /></figure><h3>Conclusion</h3><p>Budget and “Total Gross Bankability” (a quantification of a movie’s “star power”) were statistically significantly associated with a movie’s box office. Budget had a relatively strong correlation (0.68), and “Total Gross Bankability” had a moderate correlation (0.45).</p><p>The year, runtime, and score had relatively weak correlation with box office.</p><p>Limitations of my analysis include missing data in all rows, which either had to be dropped or ignored. I also did not measure the correlation of categorical variables, only quantitative. The dataset also only included movies released in the USA between 1980–2020, and excluded any movies released by streaming companies (like Netflix-originals, since their business model is not built around “box office”).</p><p>Further research could use logistic regression to analyze the thousands of production companies and tens of thousands of actors in films to analyze their correlation with box office success, as well as potentially find a better algorithm to analyze the “star power” of a movie (the ability to get an audience to see a movie because they want to see a movie with a particular actor or because it’s made by a particular director).</p><p>If we had access to the marketing data, I would be particularly interested in examining the correlation between box office and spend on different marketing mediums, such as OOH billboards, digital display ads, YouTube Ad commercials, social media posts, getting actors on talk shows, and more. This is certainly an area for further research.</p><p><em>You can check out </em><a href="https://github.com/AustinJamesWolff"><em>my GitHub here</em></a><em>. For convenience, you can see the entire notebook referenced above </em><a href="https://github.com/AustinJamesWolff/Data-Science-Portfolio/blob/main/Data%20Cleaning%20and%20Analysis/CRM_Data.ipynb"><em>here</em></a><em>. To see more Data Science projects, follow me on GitHub or connect with me on </em><a href="https://www.linkedin.com/in/austin-james-wolff/"><em>LinkedIn</em></a><em>!</em></p><p><em>[1] Gupta, Ravi. Predicting Movie Profitability and Risk at the Pre-production Phase. Medium. Retrieved from </em><a href="https://towardsdatascience.com/predicting-movie-profitability-and-risk-at-the-pre-production-phase-2288505b4aec"><em>https://towardsdatascience.com/predicting-movie-profitability-and-risk-at-the-pre-production-phase-2288505b4aec</em></a></p><p><em>Originally published at </em><a href="https://www.linkedin.com/pulse/using-multiple-linear-regression-examine-what-variables-austin-wolff"><em>https://www.linkedin.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93f5c8174078" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>