<?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 Daniel Kim  on Medium]]></title>
        <description><![CDATA[Stories by Daniel Kim  on Medium]]></description>
        <link>https://medium.com/@danielkimwas?source=rss-8cf473938a8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bRjK2oEJSQyvtdC-uW8jFA.jpeg</url>
            <title>Stories by Daniel Kim  on Medium</title>
            <link>https://medium.com/@danielkimwas?source=rss-8cf473938a8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:12:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielkimwas/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[Analyzing Google Store Merchandise Data (GStore) with Tableau & Python]]></title>
            <link>https://medium.com/@danielkimwas/analyzing-google-store-merchandise-data-gstore-with-tableau-python-ae839347a2b9?source=rss-8cf473938a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae839347a2b9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[google-data-analytics]]></category>
            <dc:creator><![CDATA[Daniel Kim ]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 02:49:17 GMT</pubDate>
            <atom:updated>2024-10-27T04:59:44.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lu_os1VqF_VhTZOmOs2oXg.png" /></figure><p>In 2018 Google launched a customer revenue prediction competition based on their customer dataset for google merchandising stores. The actual competition on Kaggle while completed still contains the merchandising dataset. You can go to the link to read about it yourself here: <a href="https://www.kaggle.com/competitions/ga-customer-revenue-prediction/overview">Google Analytics Customer Revenue Prediction | Kaggle</a>. And if you are having trouble reformatting the json dataset, someone kindly reformatted it into a nice csv file and that can be downloaded here: <a href="https://www.kaggle.com/code/julian3833/1-quick-start-read-csv-and-flatten-json-fields/output">1 — Quick start: read csv and flatten json fields (kaggle.com)</a>.</p><p>In this article, rather than trying to predict customer revenue for the future dates, I decided to do a deep dive analysis of the dataset using Tableau and Python. For the tableau parts, I will give a step-by-step explanation on how I created a custom churn rate field and also define some other key metrics such as average order size that will help us understand our data better. Let’s get going now! If you want to interact with the dashboard as you go along with the article click <a href="https://public.tableau.com/app/profile/daniel.kim2801/viz/google_store/GstoreAnalytics">here</a>!</p><h4>Intro to the dataset</h4><p>I won’t explicitly list out all the columns in the dataset since the link I provided above in the Kaggle website does a better job in listing and describing all of them. The data starts at 08–01–2016 and ends at 08–01–2017. In general, several segment columns are provided such as channel grouping, device category, country, and device browser. Below I have provided some quick summary charts in tableau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*kCu502nbwyAVBsJoDvMyYg.png" /></figure><p>Above I show a quick summary table of number of visitors who actually purchased and the total unique number of visitors on the site. To do this I first created a new calculated field called purchases and added the following to it:</p><pre>if [totals.transactionRevenue] &gt; 0 then 1 <br>else 0 end</pre><p>This allows me to count transactions greater 0 as a transaction (1) and those that are 0 as not a transaction (0). Using the sum function, I can then tally all the ones all together and get a total amount of purchases. Going back to stats, as you can see from the table above, the percentage of people actually buying something is a fraction of the amount of site visitors (column on the right). It is around 2% for desktop users, 0.5% for mobile users, and 0.6% for tablet. The majority of the purchases (10,945) come from desktop users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFGnEcReD5CeUiY1hp59BQ.png" /><figcaption>bar chart of transaction revenue by channel grouping</figcaption></figure><p>From the above chart, one can see that the channel grouping Referral makes up the majority of revenue from the Gstore. Direct &amp; Organic Search are second and third highest revenue channels. Let’s add another field to columns, distinct count of fullVisitorId. This will tell me how many unique visistors there were for each channel grouping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxNivA_E2EVtZFMSRfMiEA.png" /><figcaption>revenue vs # of unique visitors. Tableau table is <a href="https://public.tableau.com/app/profile/daniel.kim2801/viz/google_store/GstoreAnalytics">here</a></figcaption></figure><p>Notice how the total revenue does not necessarily correlate with how many users visit the Google Merchandising Store. As you can see above on the left chart, in purple we have our highest revenue channel, Referral but you can clearly see that it has far less unique visitors (chart on left) than say Direct and Organic Search channels. Organic Search in green has a lot of unique visitors but it still has less total revenue than referrals. This kind of makes sense since users coming from organic search contains a wider variety of people. Some visitors probably just stumble upon the site through google search and just want to check the site and its products out of curiosity. On the other hand, it appears the direct channel (red bar above) has more visitors converting and buying something. They perhaps saw the site before, and this time went directly cause they are interest in buying something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*130iiJ_abCS7VFE2XK8tMQ.png" /></figure><p>If we add a third column, page views, we can also see that in general referrals have the highest average pageviews and social media is actually quite ineffective in terms of converting users to buyers and having them engaged with the google store (avg of 2 page views for users who come from social media). We can also zoom out and see in general what the total count of distinct users vs total revenue looks like in a dual axis bar and line chart. Basically, in tableau, you can overlay one field over the other using the dual axis feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKdXeT3U1Gnh30wOe47GHw.png" /></figure><p>As you can see above, I combined two fields together using dual axis. This can be done if you place two fields on the rows section and then right click on one of them and click on dual axis. The orange line represents unique # of users over the months. The y-axis on the right represents the amount for distinct user count while the left y-axis shows the total revenue. This overlay allows me to see more easily that the amount of unique users is slightly correlated with total revenue. Because we only have one year’s worth of data it is a little difficult to tell if revenue is cyclical. However, it appears that revenue seems to increase and fall in a cycle of 3–4 months.</p><p>Before we go into a deeper dive into referrals and other KPI’s let’s look at some basic stats a bit longer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*oUTlLIXjc_-QlkBlvXHRgA.png" /><figcaption>device operating system</figcaption></figure><p>Macintosh is the clear winner ironically (Apple is google’s rival) in terms of total transaction revenue with a total of 856 B over the years 08–2016 to 08–2017. With 6,426 purchases in that year span, the transaction revenue per purchase equals $133,267,318! It appears most of google store buyers are either large corporate companies or just really rich people (I am assuming since the purchases are in huge scale) ! Video games like xbox and nintendo are basically non-existent in terms of revenue channels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*zirJ86rnNcUjP_7NclzKRQ.png" /></figure><p>I have further segmented the table by device browser. I highlighted in yellow, the macintosh to show the browsers from descending order of transaction revenue. For Macintosh users, the browser with the highest revenue is Chrome ($818 Billion) and Safari a distance second ( $34 billion). Except for iOS operating system, most of the highest revenue come from Chrome browsers.</p><h4>Deeper Dive &amp; Defining Churn Rate Metric</h4><p>Let’s now move onto a deeper look into referrals our highest revenue channel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jW9MaNJ0M9sYuRZye1GKyQ.png" /></figure><p>Above I decided to create a total transaction over time chart and colored different lines by the traffic source to determine where the referrals were coming from. I also added certain filters to only get the top referrals as there were a lot of them. I also filtered for only the channel group referral. As one can see above, the majority of revenue came from one traffic source, mall.googleplex.com. While I don’t have further information on this traffic source, in a real-world scenario I would further explore this traffic source and further segment the data to understand who the main customers are for this traffic source. But just from looking at it, it seems the main customer of the google store might actually be google since I am assuming mall.googleplex.com is an google employee url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpq9xoDm5MWnSVgKcJkRhw.png" /><figcaption>chart without mall.googleplex.com url</figcaption></figure><p>Taking out the mall.googleplex.com url, I can see the trends of the other smaller traffic sources. The second highest revenue source is mail.google.com. This makes sense since mail.google.com is Google’s email URL and perhaps google sends google promotional emails to specific users. While total transaction revenue on the y-axis does give me some useful insight into the highest traffic sources, average revenue per purchasing customer may give me a better view of the situation. I will define average order size as the following: total revenue/ # of orders.</p><p>In tableau this would be the same as below:</p><pre>sum([totals.transactionRevenue])/countd([Order ID])</pre><p>Countd stands for distinct count. Replacing total transaction revenue with avg. order size allows me to see all the traffic sources a bit better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_Bu_Z3SM_lD940-faG8CA.png" /><figcaption>avg order size over time vs total transaction revenue over time</figcaption></figure><p>On the left of the above pic, you can see the avg order size over time chart. A bit surprising is that the highest revenue traffic source, mall.googleplex.com actually has quite a low avg order size in comparison to other traffic sources such as mail.google.com and dealspotr.com. I’ve put a comparison on the right of the avg order size chart. Having both these views, helps one understand the data better. If we just focused on avg order size we would not realize that mall.googleplex.com which is in the middle of the pack is quite important as it has a majority of the total revenue.</p><h4>Defining and Creating Churn Rate Calculated Field</h4><p>Now we are going to going to define churn rate which is define as the following:</p><p><em># of users who churn / total # of unique visitors</em></p><p>So to solve for this formula, I first need to figure out how to find # of users who churn. I need to first set a threshold or the number of days that goes by without buying that defines a customer as no longer one. To do this, I needed to first identify all the users who were current customers. I defined any customer as someone in the dataset who bought something in the Google store at least one time. However, to get the average amount of days customers in this dataset took to buy again, I need to filter for only customers who bought 2 or more times in the dataset.</p><p>I then need to find the average days between all transactions for each user who purchased more than once. While I will not go over the details how I calculated this average in code, I used handy dandy python to get this average and that came out to be about 40 days (I have put the code and process at the end of this article in the appendix).</p><p>In tableau, before calculating churn rate I had to first create a few calculated fields to make it work. The first one was purchase date:</p><pre>if [totals.transactionRevenue] &gt;0 then [Date] else null end</pre><p>Basically, all revenues greater than 0 would output the date and if not then no date would be outputted. Using this purchase date field I then got the latest purchase date for each user by making use of the max() function and fixed LOD function as follows:</p><pre>{fixed [Full Visitor Id]: max([purchase date])}</pre><p>I called this calculated field “last purchase date”. Then using this new field, I calculated another field “Days since last purchase”:</p><pre>datediff(&#39;day&#39;, [Last Purchase Date], dateparse(&quot;MM-DD-YYYY&quot;, &#39;01-01-2018&#39;))</pre><p>This field uses the datediff() function to get the number of days between the last purchase date field and Jan 1st 2018. I used 01/01/2018 instead of the last date in the dataset 08–01–2017 because tableau was malfunctioning and datediff() was not using 8/1/2017 as the date to compare but defaulting to 01/01/2016. To adjust for this error, I then created another field and subtracted 153 days or the days between 08/01/2017 and 01/01/2019 to set the comparison date to 08/01/2017.</p><pre>[Days Since Last Purchase] - 153</pre><p>Finally I created a field called “churn flag” and put the formula as follows:</p><pre>if [Days Since Last Purchase 2 ] &gt; 40 then 1 else 0 end</pre><p>This checks if the days since last purchase is greater than 40 and assign 1 if it is and 0 if it is not. Summing this churn flag field will give me the total users who have churned and have not. The final churn rate field is as follows:</p><pre>sum([Churn Flag ])/countd([Full Visitor Id])</pre><p>The only caveat to this field “churn rate” is that the # of unique visitors needs to be the total # of people who actually purchased not the total # of people who purchased or did not purchase. To do this, I use the following filter settings on the field Full Visitor Id. I set a condition that only gets users with a total transaction revenue &gt; 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*t6UnU1WzsP15nBprnCIiDA.png" /></figure><p>Finally I can visualize the churn rate!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iecfjoZ2Ol4mAKjIack5gQ.png" /></figure><p>I split churn and not churned into two for the visualization. The labels show the number of churned or not churned users and the y-axis shows the total revenue. As you can see, the number of churned users slowly decreases as we get closer to the latest date which is August 1, 2017. The early dates are actually more interesting for the “did not churn” category as it shows there are at least 10 users since August 2016 who have not churned. even up to April 2017, there are around 52 users who have not churned. While it may not seem much, a next step would be to understand how much revenue these loyal users generate and also to reward them gifts or awards to retain them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eoSqO4wlaJWMjGMt5gsm9g.png" /></figure><p>I now create a more complete table for the channel group adding in the Churn Rate as well another column “more than one purchase” that counts the # of customers who purchased more than once. I also added a Year over Year % difference in transaction revenue. Referral churn rate was about 98.95% in 2016 but decreased to 76.97% and had increases in revenue. Interestingly, one of the highest YoY % changes is Display. It had a revenue growth from 8 billion to 69 billion USD. We should further check this segment and try to figure out the underlying increase and see whether or not it is just a one-time thing or a growth segment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VaQKhBGlRJpKpz7qjgkZw.png" /><figcaption>Display timeline chart</figcaption></figure><p>Above I have looked more in depth at the unique count of users and total revenue for each month for the channel grouping display. I have created a filter for channel grouping that allows one to filter for each channel grouping. Examining the total revenue of display over time, we see that instead of a trend we seem to have one extremely large transaction in April 2017. Even though the revenue went up in 2017, it appears total unique visitors that made one or more transactions declined from the January 2017 to June 2017. On further examination (chart below), we see that display channel grouping in April actually comes solely from the traffic source CPM. And the main revenue source of $32 billion comes from Firefox browser in April 2, 2017, and $9 billion again in April 16, 2017.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQVtvlR5eP9qnFQ-TOjoIA.png" /></figure><p>If we zoom out the date and look at prior months (chart below) , we also see that in March they purchased a decent amount (around $8 billion) and then purchased a similar amount in June 2017 ($7 Billion). While we don’t have enough granular data in this sample dataset to look into why such a large quantity was bought in April 2017, in a real-life scenario we should look further into this and understand who this customer is and how to best accommodate them for future orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjUlrDnrw6lfW6vDxh1rBA.png" /></figure><p>Another interesting observation is that the distribution of the channel grouping Display is quite lopsided with one customer contributing to a majority of the total transaction revenue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O9w3jq13xxHPPbMA_kXnYA.png" /><figcaption>total revenue per visitor id for displays</figcaption></figure><p>Compared to the other channel groups, display is quite disproportionate. Below you can view other channel groups with much more equitable distributions in comparison to the Display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QiNLOY4manIcnCr8Xj1Nyg.png" /><figcaption>Organic Search distribution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACeyW9KCqkvy9IDnRLGpTw.png" /><figcaption>referral channel group distribution</figcaption></figure><p>Referring to an earlier piece of data, the table with the unique count of users, avg total transaction revenue, and sum total of transaction revenue, we can see that Display has very few total unique users which may be contributing to the disproportion in revenue distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*rZWw7JCHAT8lHGTMYnHybA.png" /></figure><p>Overall our investigation of whether or not display has truly been trending up has concluded. Based on the data, it seems the upward trend in channel group display year over year was more of an outlier/anomaly then an actual trend. Because a majority of the total transaction revenue came from a single customer and happened only during certain months in 2017 rather than gradually increasing for a majority of the users in display channel group, I am ruling out that this is a genuine upward trend that the company should be alerted to and focus more on. They should try to find out about this single customer providing a majority of the revenue in display channel group, but we should not identify the entire display channel as an exploding group that needs attention as a whole.</p><p>tableau here: <a href="https://public.tableau.com/app/profile/daniel.kim2801/viz/google_store/GstoreAnalytics">google_store | Tableau Public</a></p><h3>Appendix</h3><p><em>Python approach to getting the 40 day threshold for churn rate is below:</em></p><pre>import pandas as pd <br><br>df = pd.read_csv(&#39;C://path_to_dir//My Tableau Repository//google_analytics.csv&#39;)<br><br># first I needed to get only the rows where transaction actually <br># occured or where revenue is greater than 0<br>df1 = df[df[&#39;totals.transactionRevenue&#39;] &gt; 0]<br><br># sort values by the visitor id and date <br>df1 = df1.sort_values([&#39;fullVisitorId&#39;, &#39;date&#39;])<br><br># reformat date to one that I can get the differences <br>df1[&#39;date&#39;] = pd.to_datetime(df1[&#39;date&#39;], format=&#39;%Y%m%d&#39;)<br># get the difference between the purchase dates for each full visitor id<br>df1[&#39;days&#39;]= df1.groupby(&#39;fullVisitorId&#39;)[&#39;date&#39;].diff()<br><br># I convert the day to the right format <br>df1[&#39;day_integer&#39;]= pd.to_timedelta(df1[&#39;days&#39;]).dt.days<br><br># I get only three columns <br>df1 = df1[[&#39;date&#39;, &#39;fullVisitorId&#39;, &#39;days&#39;]]<br><br># finally I calculate the average amount of days between purchase dates by <br># adding all the days and dividing by the length <br>(df1[&#39;day_integer&#39;].sum())/len(pd.unique(df1[&#39;fullVisitorId&#39;]))<br><br># this gets me around 41 days but I went down to 40 days. </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae839347a2b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Forecasting Sales Data with ARIMA model]]></title>
            <link>https://medium.com/@danielkimwas/time-series-forecasting-sales-data-with-arima-model-f38d383be134?source=rss-8cf473938a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f38d383be134</guid>
            <dc:creator><![CDATA[Daniel Kim ]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 09:11:18 GMT</pubDate>
            <atom:updated>2024-09-15T02:54:06.842Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I am going to be looking at a hypothetical (not real) international company and attempt to forecast its sales using its past sales numbers. For this sales company, I have actual data from January 1,2018 — December 31,2019. This company sells in multiple countries so for each country, I am going to predict the number of sales for 1 business day in the future (T +1). The model I will use to predict the time series sales data is ARIMA. Before I go about explaining my process, I want to add an outline of the topics I will cover in this article:</p><ol><li>Visualize sales data for each country to identify any patterns in time series</li><li>Interpolate (fill in) any missing data for each country time series</li><li>Explanation of what ARIMA model is &amp; using it to model sales data</li><li>Use custom auto ARIMA functions to get best order combination for (p, d, q)</li><li>Forecast Jan1, 2019 total sales for each country</li></ol><h3>Explore the Data &amp; Visualize Time Series</h3><p>The very first thing I did before anything else was explore my dataset and try to see how many missing data points each country had. Realistically, I assumed that some countries had no sales on certain days from Jan 1, 2018 -Dec 31,2018. Because ARIMA time series forecasting is affected by missing data, I need to identify these points and do some sort of interpolation.</p><pre>country_missing_dates = []<br>countries = []<br><br>for country in df[&#39;country&#39;].unique():<br>  #filter by country<br>  test = df[df[&#39;country&#39;]==country]<br><br>  test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>  test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>  test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>  # get the start and end date to see which missing values we have to impute<br>  date_range = pd.date_range(start=&#39;2018-01-01&#39;, end=&#39;2018-12-31&#39;, freq=&quot;D&quot;)<br><br>  test = test.set_index(&#39;date&#39;)<br>  test.index = pd.to_datetime(test.index)<br>  missing_dates = date_range[~date_range.isin(test.index)]<br>  # print(&#39;checking missing dates for %s&#39; % (country), len(missing_dates))<br>  if len(missing_dates):<br>    country_missing_dates.append(len(missing_dates))<br>  else:<br>    country_missing_dates.append(0)<br>  countries.append(country)<br><br>data = {&#39;Country&#39;: countries,<br>        &#39;missing_dates&#39;: country_missing_dates}<br><br># Create DataFrame<br>country_missing_dates_df = pd.DataFrame(data)<br>country_missing_dates_df = country_missing_dates_df.sort_values(by=&#39;missing_dates&#39;, ascending=False)<br>country_missing_dates_df = country_missing_dates_df.reset_index()<br>country_missing_dates_df[[&#39;Country&#39;, &#39;missing_dates&#39;]]</pre><p>As you can see in the python code above, the first I thing I did was create the lists country_missing_dates and countries to save the country code into countries list and the amount of missing dates in the country_missing_dates list. This way after collecting all the info into these lists, I could easily convert it into a pandas dataframe.</p><p>The variable df saved the sales file csv and using a for loop, I went through each country in df[‘country’] and created a new variable test to save each country filtered df. I then had to do some date reformatting in order to be able to check for missing dates. My strategy was quite simple. I created a date_range variable that held all dates from Jan 1-Dec 31 2018 and then checked which country dates were missing in the date_range list to identify missing data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*6my6mA7KumdphAonbhY1YQ.png" /><figcaption># of missing dates per country</figcaption></figure><p>As seen above, the resulting dataframe of missing data points per country showed that some countries like Luxembourg (LU) contained lots of missing data and others showed having very few missing data points such as Denmark (DK).</p><p>Using the snippet of python code below, I visualized missing data points in a time series for each country.</p><pre>import matplotlib.pyplot as plt<br><br>for country in country_missing_dates[&#39;Country&#39;].unique():<br>  #filter by country<br>  test = df[df[&#39;country&#39;]==country]<br>  test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>  test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>  test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>  # get the start and end date to see which missing values we have to impute<br>  date_range = pd.date_range(start=&#39;2018-01-01&#39;, end=&#39;2018-12-31&#39;, freq=&quot;D&quot;)<br><br>  test = test.set_index(&#39;date&#39;)<br>  test.index = pd.to_datetime(test.index)<br>  missing_dates = date_range[~date_range.isin(test.index)]<br><br>  plt.figure(figsize=(8, 6))<br>  plt.bar(missing_dates, [1] * len(missing_dates))<br>  plt.title(&quot;%s Missing Dates&quot; % (country))<br>  plt.xlabel(&quot;Date&quot;)<br>  plt.ylabel(&quot;Count&quot;)<br>  plt.xticks(rotation=45)<br>  plt.show()<br><br></pre><p>The resulting chart below clearly showed how dispersed missing data was in each country’s time series. The country PT has more missing dates in the beginning of 2018 than at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*kpVatDN_h7MZt0h9lvAWNw.png" /></figure><p>Using the below script, I also was easily able to chart for each country, the actual time series.</p><pre>import matplotlib.pyplot as plt<br><br>for country in country_missing_dates[&#39;Country&#39;].unique():<br><br>  #filter by country<br>  test = df[df[&#39;country&#39;]==country]<br>  test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>  test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>  test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>  # get the start and end date to see which missing values we have to impute<br>  date_range = pd.date_range(start=&#39;2018-01-01&#39;, end=&#39;2018-12-31&#39;, freq=&quot;D&quot;)<br><br>  test = test.set_index(&#39;date&#39;)<br>  test.index = pd.to_datetime(test.index)<br>  missing_dates = date_range[~date_range.isin(test.index)]<br><br>  plt.figure(figsize=(8, 6))<br><br>  merged_data = test.reindex(date_range)<br>  closing_prices = merged_data[&quot;dollar_amount&quot;]<br>  missing_dates_mask = closing_prices.isna()<br>  # Plotting the closing prices with breaks for missing dates<br>  plt.plot(closing_prices.index, closing_prices)<br>  plt.title(&quot;%s Country amount&quot; % (country))<br>  plt.xlabel(&quot;Date&quot;)<br>  plt.ylabel(&quot;Country Amount&quot;)<br>  plt.grid(True)<br><br>  plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*tedcKDEXR4Im43Ad_rbmGg.png" /><figcaption>a time series chart of country PT</figcaption></figure><p>After charting both the data points and missing data points separately, I subdivided the countries by their amount of missing data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*dIukWyciM_SmwbhiPkDcPw.png" /><figcaption>left side shows data points &amp; right side shows missing data points</figcaption></figure><p>I subdivided by:</p><ol><li>Country Missing Dates &gt; 50</li><li>Country Missing Dates ≤50</li><li>Country Missing Dates = 0</li></ol><p>Subdividing in this way was actually important as I used different approaches based on the number of missing data. Examining the top left chart on the pic above, one can see for the MX country time series, that there is literally no data until the later part of the year. Since there is no data for almost half of the year, it would be pointless to try interpolating. for that reason, I decided for those time series containing &gt; 50 missing data points, I would specify the starting points to interpolate.</p><h4>Interpolating Missing Data Points</h4><p>So as follows, my next task was in estimating the missing data points using interpolation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*WebGS3lWjL6rwR6w" /><figcaption>a random image of interpolation</figcaption></figure><ul><li>I tested multiple different methods for interpolation:</li><li>Mean, median, spline, polynomial, quadratic, cubic, etc.</li><li>R squared value was used to get the best method. The highest r squared method was chosen</li><li>Most cases used polynomial interpolation order=7</li><li>One case used spline interpolation order =4</li></ul><p>The python code used to find the best method is below:</p><pre># Import a scoring metric to compare methods<br>from sklearn.metrics import r2_score<br>import numpy as np<br><br><br>country_list = []<br>best_method_list = []<br><br><br><br># iterate through countries with at least one missing data point<br># I choose 8:16 since I have ordered my dataframe by the amount of missing data desc<br>for country in country_missing_dates[&#39;Country&#39;][8:16].unique():<br><br>  #filter by country<br>  test = df[df[&#39;country&#39;]==country]<br>  test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>  test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>  test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>  test = test.set_index(&#39;date&#39;)<br>  test.index = pd.to_datetime(test.index)<br><br>  # adding the missing rows<br>  df = test<br>  df = df.reset_index()<br>  df1 = df.reindex(pd.date_range(start=min(df[&#39;date&#39;]), end=max(df[&#39;date&#39;]), freq=&quot;D&quot;))<br>  df1 = df1.reset_index()<br>  df1 = df1[[&#39;index&#39;]]<br>  df1.rename(columns={&#39;index&#39;: &#39;date&#39;}, inplace=True)<br>  final_df = pd.merge(df1, df, how=&quot;left&quot;, on=[&quot;date&quot;])<br><br>  df2 = final_df<br>  # impute mean for missing data<br>  df2 = final_df.assign(FillMean=final_df.dollar_amount.fillna(final_df.dollar_amount.mean()))<br>  # impute median<br>  df2 = df2.assign(FillMedian=final_df.dollar_amount.fillna(final_df.dollar_amount.median()))<br><br>  # imputing using the rolling average<br>  df2 = df2.assign(RollingMean=final_df.dollar_amount.fillna(final_df.dollar_amount.rolling(10,min_periods=1,).mean()))<br><br>  # test other methods for imputing data <br><br>  df = df2<br>  df.set_index(&quot;date&quot;, inplace = True)<br>  df = df.assign(InterpolateLinear=df.dollar_amount.interpolate(method=&#39;linear&#39;))<br>  df = df.assign(InterpolateTime=df.dollar_amount.interpolate(method=&#39;time&#39;))<br>  df = df.assign(InterpolateQuadratic=df.dollar_amount.interpolate(method=&#39;quadratic&#39;))<br>  df = df.assign(InterpolateCubic=df.dollar_amount.interpolate(method=&#39;cubic&#39;))<br>  df = df.assign(InterpolateSLinear=df.dollar_amount.interpolate(method=&#39;slinear&#39;))<br>  df = df.assign(InterpolateAkima=df.dollar_amount.interpolate(method=&#39;akima&#39;))<br>  df = df.assign(InterpolatePoly5=df.dollar_amount.interpolate(method=&#39;polynomial&#39;, order=5))<br>  df = df.assign(InterpolatePoly7=df.dollar_amount.interpolate(method=&#39;polynomial&#39;, order=7))<br>  df = df.assign(InterpolateSpline3=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=3))<br>  df = df.assign(InterpolateSpline4=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=4))<br>  df = df.assign(InterpolateSpline5=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=5))<br><br>  df.reset_index(inplace=True)<br><br>  df[&#39;dollar_amount&#39;].fillna(0, inplace=True)<br><br>  # get the r squared values and find the one with the highest score<br>  results = [(method, r2_score(df.dollar_amount, df[method])) for method in list(df)[4:]]<br>  results_df = pd.DataFrame(np.array(results), columns=[&#39;Method&#39;, &#39;R_squared&#39;])<br>  results_df.sort_values(by=&#39;R_squared&#39;, ascending=False)<br><br>  best_method = results_df[results_df.R_squared == max(results_df.R_squared)].iloc[0,0]<br>  print(country, best_method)<br>  country_list.append(country)<br>  best_method_list.append(best_method)<br><br>  # Create Best Method DataFrame<br>  data = {&#39;country&#39;: country_list,<br>        &#39;best_method&#39;: best_method_list}<br><br>  best_method_df = pd.DataFrame(data)<br>  best_method_df = best_method_df.sort_values(by=&#39;country&#39;, ascending=False)<br>  best_method_df = best_method_df.reset_index()</pre><p>While I will not go through in detail the above code, one can see below the comment section #adding the missing rows, that I have to do a bit of work actually adding rows for the missing dates in each country’s time series. This required some table merges and reindexing. Afterwards, I was finally able to use the interpolate method to create different types of interpolations. The below snippet highlights the various methods I tried.</p><pre>df = df.assign(InterpolateLinear=df.dollar_amount.interpolate(method=&#39;linear&#39;))<br>df = df.assign(InterpolateTime=df.dollar_amount.interpolate(method=&#39;time&#39;))<br>df = df.assign(InterpolateQuadratic=df.dollar_amount.interpolate(method=&#39;quadratic&#39;))<br>df = df.assign(InterpolateCubic=df.dollar_amount.interpolate(method=&#39;cubic&#39;))<br>df = df.assign(InterpolateSLinear=df.dollar_amount.interpolate(method=&#39;slinear&#39;))<br>df = df.assign(InterpolateAkima=df.dollar_amount.interpolate(method=&#39;akima&#39;))<br>df = df.assign(InterpolatePoly5=df.dollar_amount.interpolate(method=&#39;polynomial&#39;, order=5))<br>df = df.assign(InterpolatePoly7=df.dollar_amount.interpolate(method=&#39;polynomial&#39;, order=7))<br>df = df.assign(InterpolateSpline3=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=3))<br>df = df.assign(InterpolateSpline4=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=4))<br>df = df.assign(InterpolateSpline5=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=5))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBPPy1UsW9J4mcN_V8qizw.png" /><figcaption>df table that shows estimates from different interpolators</figcaption></figure><p>The above table shows the 0 dollar amount row highlighted in yellow. The zero represents a missing data point. Notice each method such as FillMean, FillMedian, and InterpolatedLinear have different estimates for the 2018–01–08 price. Ultimately, I chose the method with the highest R-squared which is a good indicator.</p><pre># get the r squared values and find the one with the highest score<br><br>results = [(method, r2_score(df.dollar_amount, df[method])) for method in list(df)[4:]]<br>results_df = pd.DataFrame(np.array(results), columns=[&#39;Method&#39;, &#39;R_squared&#39;])<br>results_df.sort_values(by=&#39;R_squared&#39;, ascending=False)<br><br>best_method = results_df[results_df.R_squared == max(results_df.R_squared)].iloc[0,0]<br>print(country, best_method)<br>country_list.append(country)<br>best_method_list.append(best_method)</pre><p>For the countries with missing data points &gt;50, I decided to manually specify an exact date to start by observing the best possible points. Because these countries had a vast majority of their missing, it did not make sense to try imputing data from the beginning of the year to the end. Basically, I used the same script as above but added a dictionary country_date_map to hold the starting dates for each country with greater than 50 missing days.</p><pre># Import a scoring metric to compare methods<br>from sklearn.metrics import r2_score<br>import numpy as np<br>#---------------this is the main difference below -----------------------------#<br># Checked the graph and time series myself and chose starting points for these more erratic time series filled with missing sections<br>country_date_map = {&#39;LU&#39;: &#39;2018-10-01&#39;, &#39;MX&#39;: &#39;2018-11-05&#39;, &#39;PT&#39;:&#39;2018-02-26&#39;,<br> &#39;CH&#39;: &#39;2018-04-07&#39;, &#39;FI&#39;:&#39;2018-01-01&#39;, &#39;NZ&#39;:&#39;2018-01-01&#39;, &#39;SG&#39;:&#39;2018-01-04&#39;, <br>&#39;HK&#39;:&#39;2018-01-05&#39;}<br><br><br>country_list = []<br>best_method_list = []<br><br># iterate through countries with more than 50 missing data points<br>for country in country_missing_dates[&#39;Country&#39;][:8].unique():<br><br>  #filter by country<br>  test = df[df[&#39;country&#39;]==country]<br>  test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>  test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>  test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>  # get the start and end date to see which missing values we have to impute<br># here I make the start date reference the country_date_map dictionary<br># where I have specified the starting point<br>  date_range = pd.date_range(start=country_date_map[country], <br>end=max(test[&#39;date&#39;]), freq=&quot;D&quot;)<br><br>  test = test.set_index(&#39;date&#39;)<br>  test.index = pd.to_datetime(test.index)<br>  missing_dates = date_range[~date_range.isin(test.index)]<br><br>  # adding the missing rows ... the rest is the same as the previous code</pre><h3>ARIMA</h3><p>At last, after exploring the dataset and imputing values to missing data points, we can finally start trying to create an ARIMA model to predict the number of sales for each country on January 1, 2019! Let’s first get to know a little more about ARIMA before implementing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*HxYMlaRPFw1MysSFfAz4vA.png" /><figcaption>ARIMA the octopus of time series models</figcaption></figure><p>Meet ARIMA, the fortune-telling octopus of the data world. Its full name is Autoregressive Integrated Moving Average, but that’s a mouthful even for an octopus.</p><p>ARIMA is like that friend who always knows what’s going to happen next in your favorite TV show. It’s got three special tentacles:</p><ol><li>The “Autoregressive” tentacle: This one’s obsessed with the past. It’s like your grandpa who thinks every story relates to something that happened in 1953.</li><li>The “Moving Average” tentacle: This is the cool surfer dude of the group, always riding the latest waves of change.</li><li>The “Integrated” tentacle: This is the peacemaker, blending grandpa’s stories with surfer dude’s vibes to predict the future.</li></ol><p>Together, these tentacles juggle numbers from the past and present, trying to guess what’ll happen next.</p><p>The key points to remember about ARIMA are the following:</p><ol><li>Model uses lagged moving averages to smooth time series data.</li><li>It has 3 components (p, d, q):</li></ol><ul><li>Autoregression (AR aka p) — ARIMA regresses on its own lagged values</li><li>Integrated (I aka d) — the amount of differencing to make model stationary. The purpose of differencing is to remove any trends or seasonal structures</li><li>Moving Average (MA aka q) — uses a regression-like model on past forecast errors</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yh9O0geBzab19Tfs" /></figure><p>On the left side of the image above, one can see the original time series being differenced to the 1st &amp; 2nd order. This essentially reduces trend and seasonality and makes the time series stationary which is a requirement for ARIMA models to work. On the right are PACF charts that help one find the order for p or the auto regressive part of <strong>AR</strong>IMA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VM_fikph1r6ctbHFN7oxRw.png" /></figure><p>The custom auto arima function I used can be seen in the code block below:</p><pre># grid search ARIMA parameters for time series<br>import warnings<br>from math import sqrt<br>from pandas import read_csv<br>from statsmodels.tsa.arima.model import ARIMA<br>from sklearn.metrics import mean_squared_error<br><br><br># evaluate an ARIMA model for a given order (p,d,q)<br>def evaluate_arima_model(X, arima_order):<br> # prepare training dataset<br> train_size = int(len(X) * 0.66)<br> train, test = X[0:train_size], X[train_size:]<br> history = [x for x in train]<br> # make predictions<br> predictions = list()<br> for t in range(test.index.start, test.index.stop):<br>  model = ARIMA(history, order=arima_order)<br>  model_fit = model.fit()<br>  yhat = model_fit.forecast()[0]<br>  predictions.append(yhat)<br>  history.append(test[t])<br> # calculate out of sample error<br> rmse = sqrt(mean_squared_error(test, predictions))<br> return rmse<br><br># evaluate combinations of p, d and q values for an ARIMA model<br>def evaluate_models(dataset, p_values, d_values, q_values):<br> dataset = dataset.astype(&#39;float32&#39;)<br> best_score, best_cfg = float(&quot;inf&quot;), None<br> for p in p_values:<br>  for d in d_values:<br>   for q in q_values:<br>    order = (p,d,q)<br>    try:<br>     rmse = evaluate_arima_model(dataset, order)<br>     if rmse &lt; best_score:<br>      best_score, best_cfg = rmse, order<br>     # print(&#39;ARIMA%s RMSE=%.3f&#39; % (order,rmse))<br>    except:<br>     continue<br> print(&#39;Best ARIMA%s RMSE=%.3f&#39; % (best_cfg, best_score))</pre><p>While the above looks a bit complex, it is actually quite simple. First, the ARIMA model is taken from the statsmodel package and the mean squared error is from sklearn package. First we define the function evaluate_arima_model which takes two arguments: X (the dateset) &amp; arima_order which is (p, d, q) or (AR order, difference order, moving average order). We make the training size 66% of the data and the test set 34%. Then we create the model instantiating from ARIMA() and train on the past dataset (here it is the variable history) and then predict for each date in the future one at a time. Finally we calculate the RMSE and return that. We place the function evaluate_arima_model inside the evaluate_models function which iterates through all combinations of p, d, and q and gets the lowest RMSE. This function is then placed inside the previous script that finds the best interpolation method. We put the following at the very bottom of that script.</p><pre>  # Create Best Method DataFrame<br>  data = {&#39;country&#39;: country_list,<br>        &#39;best_method&#39;: best_method_list}<br><br>  best_method_df = pd.DataFrame(data)<br>  best_method_df = best_method_df.sort_values(by=&#39;country&#39;, ascending=False)<br>  best_method_df = best_method_df.reset_index()<br><br>  # find the best p, d, q ------------------we place it right here inside the <br>  # for loop<br>  time_series = getattr(df, best_method_df[best_method_df[&#39;country&#39;]==country].iloc[0,2])<br>  evaluate_models(time_series, p_values, d_values, q_values)</pre><p>Unfortunately, this process of checking one by one all combinations to get the optimal one is quite slow at the present moment. Further research needs to be done on how to increase the speed and efficiency.</p><h4>Building the Model and Predicting for Jan 1, 2019</h4><p>When the auto ARIMA function eventually finds the most optimal p, d, &amp; q combinations and we have also pinpointed the best interpolation method, we can then build the ARIMA model and forecast the sales amount for each country at time T+1.</p><pre># Import a scoring metric to compare methods<br>from sklearn.metrics import r2_score<br>import numpy as np<br><br><br>p_values = [0, 1, 2, 4, 6, 8, 10]<br>d_values = range(0, 3)<br>q_values = range(0, 3)<br><br>country_list = []<br>best_method_list = []<br><br>model_parameters = {&#39;NL&#39;: [10, 1, 2], &#39;AT&#39;: [6, 2, 1], &#39;IE&#39;: [10,0,2], &#39;IT&#39;:[10,1,2], &#39;DK&#39;: [1,1,2], &#39;SE&#39;:[8,0,0], &#39;DE&#39;:[6,1,0], &#39;NO&#39;:[1,2,2]}<br><br>forecast_list = []<br><br># iterate through countries with at least one missing data point<br>for country in country_missing_dates[&#39;Country&#39;][8:16].unique():<br>  # I pull data from the model_parameters dictionary I created after seeing<br>  # the best combos for (p, d, q). This part is not so good since it still manual<br>  # but this can definitely be automated in the future. <br>  country_parameters = model_parameters[country]<br><br>  time_series = getattr(df, best_method_df[best_method_df[&#39;country&#39;]==country].iloc[0,2])<br><br># I have left out all the other stuff in the script such as finding<br># best interpolation method or<br># what is the best p, d, &amp; q combination as it would make this code too long<br><br># model building and forecasting<br><br>  model = ARIMA(time_series, order=(country_parameters[0],country_parameters[1],country_parameters[2]))<br>  model_fit = model.fit()<br>  forecast = model_fit.forecast()<br>  forecast_list.append(forecast.iloc[0])<br>  print(forecast)<br><br># below script is creating visualization of how model is predicting values. <br># Make first 320 days<br># training data and plot prediction of days 321-364 and see how it compares to<br># actual data in test dataset. <br>  df = test<br>  # Create Training and Test<br>  train = time_series[:320]<br>  test = time_series[320:]<br>  model = ARIMA(train, order=(country_parameters[0],country_parameters[1],country_parameters[2]))<br>  fitted = model.fit()<br><br>  # Forecast<br>  fc = fitted.forecast(70, alpha=0.05)<br><br>  fc_series = pd.Series(fc, index=test.index)<br>  plt.figure(figsize=(12,5), dpi=100)<br>  plt.plot(train, label=&#39;training&#39;)<br>  plt.plot(test, label=&#39;actual&#39;)<br>  plt.plot(fc_series, label=&#39;forecast&#39;)<br>  plt.title(&#39;Forecast vs Actuals&#39;)<br>  plt.legend(loc=&#39;upper left&#39;, fontsize=8)<br>  plt.show()<br><br># Create Best Method DataFrame<br>data = {&#39;country&#39;: country_list,<br>      &#39;value&#39;: forecast_list}<br><br>forecast_df_less_than_50 = pd.DataFrame(data)<br>forecast_df_less_than_50 = forecast_df_less_than_50.sort_values(by=&#39;country&#39;, ascending=False)<br>forecast_df_less_than_50 = forecast_df_less_than_50.reset_index()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbcqhnA81otttV-KOLIQJg.png" /><figcaption>overall ARIMA was able to do well on certain country time series but failed in others quite spectacularly</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpSI0bjYQv62qFCuSUCSSQ.png" /></figure><h3>final code:</h3><h4>custom function</h4><pre># grid search ARIMA parameters for time series<br>import warnings<br>from math import sqrt<br>from pandas import read_csv<br>from statsmodels.tsa.arima.model import ARIMA<br>from sklearn.metrics import mean_squared_error<br><br># dataset = df<br><br># evaluate an ARIMA model for a given order (p,d,q)<br>def evaluate_arima_model(X, arima_order):<br> # prepare training dataset<br> train_size = int(len(X) * 0.66)<br> train, test = X[0:train_size], X[train_size:]<br> history = [x for x in train]<br> # make predictions<br> predictions = list()<br> for t in range(test.index.start, test.index.stop):<br>  model = ARIMA(history, order=arima_order)<br>  model_fit = model.fit()<br>  yhat = model_fit.forecast()[0]<br>  predictions.append(yhat)<br>  history.append(test[t])<br> # calculate out of sample error<br> rmse = sqrt(mean_squared_error(test, predictions))<br> return rmse<br><br># evaluate combinations of p, d and q values for an ARIMA model<br>def evaluate_models(dataset, p_values, d_values, q_values):<br> dataset = dataset.astype(&#39;float32&#39;)<br> best_score, best_cfg = float(&quot;inf&quot;), None<br> for p in p_values:<br>  for d in d_values:<br>   for q in q_values:<br>    order = (p,d,q)<br>    try:<br>     rmse = evaluate_arima_model(dataset, order)<br>     if rmse &lt; best_score:<br>      best_score, best_cfg = rmse, order<br>     # print(&#39;ARIMA%s RMSE=%.3f&#39; % (order,rmse))<br>    except:<br>     continue<br> print(&#39;Best ARIMA%s RMSE=%.3f&#39; % (best_cfg, best_score))</pre><h4>for finding optimal p,d,q &amp; interpolation method</h4><pre># Import a scoring metric to compare methods<br>from sklearn.metrics import r2_score<br>import numpy as np<br><br><br>p_values = [0, 1, 2, 4, 6, 8, 10]<br># p_values = [1]<br>d_values = range(0, 3)<br>q_values = range(0, 3)<br><br>country_list = []<br>best_method_list = []<br><br><br><br># iterate through countries with at least one missing data point<br>for country in country_missing_dates[&#39;Country&#39;][8:16].unique():<br><br>  #filter by country<br>  test = df[df[&#39;country&#39;]==country]<br>  test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>  test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>  test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>  # get the start and end date to see which missing values we have to impute<br>  date_range = pd.date_range(start=min(test[&#39;date&#39;]), end=max(test[&#39;date&#39;]), freq=&quot;D&quot;)<br><br>  test = test.set_index(&#39;date&#39;)<br>  test.index = pd.to_datetime(test.index)<br>  missing_dates = date_range[~date_range.isin(test.index)]<br><br>  # adding the missing rows<br>  df = test<br>  df = df.reset_index()<br>  df1 = df.reindex(pd.date_range(start=min(df[&#39;date&#39;]), end=max(df[&#39;date&#39;]), freq=&quot;D&quot;))<br>  df1 = df1.reset_index()<br>  df1 = df1[[&#39;index&#39;]]<br>  df1.rename(columns={&#39;index&#39;: &#39;date&#39;}, inplace=True)<br>  final_df = pd.merge(df1, df, how=&quot;left&quot;, on=[&quot;date&quot;])<br><br>  df2 = final_df<br>  # impute mean for missing data<br>  df2 = final_df.assign(FillMean=final_df.dollar_amount.fillna(final_df.dollar_amount.mean()))<br>  # impute median<br>  df2 = df2.assign(FillMedian=final_df.dollar_amount.fillna(final_df.dollar_amount.median()))<br><br>  # imputing using the rolling average<br>  df2 = df2.assign(RollingMean=final_df.dollar_amount.fillna(final_df.dollar_amount.rolling(10,min_periods=1,).mean()))<br><br>  # test other methods for imputing data - apologies for the terrible names and going back and forth between df to final_df to df2 back to df<br><br>  df = df2<br>  df.set_index(&quot;date&quot;, inplace = True)<br>  df = df.assign(InterpolateLinear=df.dollar_amount.interpolate(method=&#39;linear&#39;))<br>  df = df.assign(InterpolateTime=df.dollar_amount.interpolate(method=&#39;time&#39;))<br>  df = df.assign(InterpolateQuadratic=df.dollar_amount.interpolate(method=&#39;quadratic&#39;))<br>  df = df.assign(InterpolateCubic=df.dollar_amount.interpolate(method=&#39;cubic&#39;))<br>  df = df.assign(InterpolateSLinear=df.dollar_amount.interpolate(method=&#39;slinear&#39;))<br>  df = df.assign(InterpolateAkima=df.dollar_amount.interpolate(method=&#39;akima&#39;))<br>  df = df.assign(InterpolatePoly5=df.dollar_amount.interpolate(method=&#39;polynomial&#39;, order=5))<br>  df = df.assign(InterpolatePoly7=df.dollar_amount.interpolate(method=&#39;polynomial&#39;, order=7))<br>  df = df.assign(InterpolateSpline3=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=3))<br>  df = df.assign(InterpolateSpline4=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=4))<br>  df = df.assign(InterpolateSpline5=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=5))<br><br>  df.reset_index(inplace=True)<br><br>  df[&#39;dollar_amount&#39;].fillna(0, inplace=True)<br><br>  # get the r squared values and find the one with the highest score<br>  results = [(method, r2_score(df.dollar_amount, df[method])) for method in list(df)[4:]]<br>  results_df = pd.DataFrame(np.array(results), columns=[&#39;Method&#39;, &#39;R_squared&#39;])<br>  results_df.sort_values(by=&#39;R_squared&#39;, ascending=False)<br><br>  best_method = results_df[results_df.R_squared == max(results_df.R_squared)].iloc[0,0]<br>  print(country, best_method)<br>  country_list.append(country)<br>  best_method_list.append(best_method)<br><br>  # Create Best Method DataFrame<br>  data = {&#39;country&#39;: country_list,<br>        &#39;best_method&#39;: best_method_list}<br><br>  best_method_df = pd.DataFrame(data)<br>  best_method_df = best_method_df.sort_values(by=&#39;country&#39;, ascending=False)<br>  best_method_df = best_method_df.reset_index()<br><br>  # find the best p, d, q<br><br><br>  # warnings.filterwarnings(&quot;ignore&quot;)<br>  time_series = getattr(df, best_method_df[best_method_df[&#39;country&#39;]==country].iloc[0,2])<br>  evaluate_models(time_series, p_values, d_values, q_values)<br><br></pre><h4>Building the model &amp; forecasting after getting optimal values</h4><pre># Import a scoring metric to compare methods<br>from sklearn.metrics import r2_score<br>import numpy as np<br><br><br>p_values = [0, 1, 2, 4, 6, 8, 10]<br># p_values = [1]<br>d_values = range(0, 3)<br>q_values = range(0, 3)<br><br>country_list = []<br>best_method_list = []<br><br>model_parameters = {&#39;NL&#39;: [10, 1, 2], &#39;AT&#39;: [6, 2, 1], &#39;IE&#39;: [10,0,2], &#39;IT&#39;:[10,1,2], &#39;DK&#39;: [1,1,2], &#39;SE&#39;:[8,0,0], &#39;DE&#39;:[6,1,0], &#39;NO&#39;:[1,2,2]}<br><br>forecast_list = []<br><br># iterate through countries with at least one missing data point<br>for country in country_missing_dates[&#39;Country&#39;][8:16].unique():<br>  country_parameters = model_parameters[country]<br>  #filter by country<br>  test = df[df[&#39;country&#39;]==country]<br>  test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>  test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>  test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>  # get the start and end date to see which missing values we have to impute<br>  date_range = pd.date_range(start=min(test[&#39;date&#39;]), end=max(test[&#39;date&#39;]), freq=&quot;D&quot;)<br><br>  test = test.set_index(&#39;date&#39;)<br>  test.index = pd.to_datetime(test.index)<br>  missing_dates = date_range[~date_range.isin(test.index)]<br><br>  # adding the missing rows<br>  df = test<br>  df = df.reset_index()<br>  df1 = df.reindex(pd.date_range(start=min(df[&#39;date&#39;]), end=max(df[&#39;date&#39;]), freq=&quot;D&quot;))<br>  df1 = df1.reset_index()<br>  df1 = df1[[&#39;index&#39;]]<br>  df1.rename(columns={&#39;index&#39;: &#39;date&#39;}, inplace=True)<br>  final_df = pd.merge(df1, df, how=&quot;left&quot;, on=[&quot;date&quot;])<br><br>  df2 = final_df<br>  # impute mean for missing data<br>  df2 = final_df.assign(FillMean=final_df.dollar_amount.fillna(final_df.dollar_amount.mean()))<br>  # impute median<br>  df2 = df2.assign(FillMedian=final_df.dollar_amount.fillna(final_df.dollar_amount.median()))<br><br>  # imputing using the rolling average<br>  df2 = df2.assign(RollingMean=final_df.dollar_amount.fillna(final_df.dollar_amount.rolling(10,min_periods=1,).mean()))<br><br>  # test other methods for imputing data - apologies for the terrible names and going back and forth between df to final_df to df2 back to df<br><br>  df = df2<br>  df.set_index(&quot;date&quot;, inplace = True)<br>  df = df.assign(InterpolateLinear=df.dollar_amount.interpolate(method=&#39;linear&#39;))<br>  df = df.assign(InterpolateTime=df.dollar_amount.interpolate(method=&#39;time&#39;))<br>  df = df.assign(InterpolateQuadratic=df.dollar_amount.interpolate(method=&#39;quadratic&#39;))<br>  df = df.assign(InterpolateCubic=df.dollar_amount.interpolate(method=&#39;cubic&#39;))<br>  df = df.assign(InterpolateSLinear=df.dollar_amount.interpolate(method=&#39;slinear&#39;))<br>  df = df.assign(InterpolateAkima=df.dollar_amount.interpolate(method=&#39;akima&#39;))<br>  df = df.assign(InterpolatePoly5=df.dollar_amount.interpolate(method=&#39;polynomial&#39;, order=5))<br>  df = df.assign(InterpolatePoly7=df.dollar_amount.interpolate(method=&#39;polynomial&#39;, order=7))<br>  df = df.assign(InterpolateSpline3=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=3))<br>  df = df.assign(InterpolateSpline4=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=4))<br>  df = df.assign(InterpolateSpline5=df.dollar_amount.interpolate(method=&#39;spline&#39;, order=5))<br><br>  df.reset_index(inplace=True)<br><br>  df[&#39;dollar_amount&#39;].fillna(0, inplace=True)<br><br>  # get the r squared values and find the one with the highest score<br>  results = [(method, r2_score(df.dollar_amount, df[method])) for method in list(df)[4:]]<br>  results_df = pd.DataFrame(np.array(results), columns=[&#39;Method&#39;, &#39;R_squared&#39;])<br>  results_df.sort_values(by=&#39;R_squared&#39;, ascending=False)<br><br>  best_method = results_df[results_df.R_squared == max(results_df.R_squared)].iloc[0,0]<br>  print(country, best_method)<br>  country_list.append(country)<br>  best_method_list.append(best_method)<br><br>  # Create Best Method DataFrame<br>  data = {&#39;country&#39;: country_list,<br>        &#39;best_method&#39;: best_method_list}<br><br>  best_method_df = pd.DataFrame(data)<br>  best_method_df = best_method_df.sort_values(by=&#39;country&#39;, ascending=False)<br>  best_method_df = best_method_df.reset_index()<br><br>  # find the best p, d, q<br><br><br>  # warnings.filterwarnings(&quot;ignore&quot;)<br>  time_series = getattr(df, best_method_df[best_method_df[&#39;country&#39;]==country].iloc[0,2])<br>  # model building and forecasting<br><br>  model = ARIMA(time_series, order=(country_parameters[0],country_parameters[1],country_parameters[2]))<br>  model_fit = model.fit()<br>  forecast = model_fit.forecast()<br>  forecast_list.append(forecast.iloc[0])<br>  print(forecast)<br><br>  df = test<br>  # Create Training and Test<br>  train = time_series[:320]<br>  test = time_series[320:]<br>  model = ARIMA(train, order=(country_parameters[0],country_parameters[1],country_parameters[2]))<br>  fitted = model.fit()<br><br>  # Forecast<br>  fc = fitted.forecast(70, alpha=0.05)<br><br>  fc_series = pd.Series(fc, index=test.index)<br>  plt.figure(figsize=(12,5), dpi=100)<br>  plt.plot(train, label=&#39;training&#39;)<br>  plt.plot(test, label=&#39;actual&#39;)<br>  plt.plot(fc_series, label=&#39;forecast&#39;)<br>  plt.title(&#39;Forecast vs Actuals&#39;)<br>  plt.legend(loc=&#39;upper left&#39;, fontsize=8)<br>  plt.show()<br><br><br># Create Best Method DataFrame<br>data = {&#39;country&#39;: country_list,<br>      &#39;value&#39;: forecast_list}<br><br>forecast_df_less_than_50 = pd.DataFrame(data)<br>forecast_df_less_than_50 = forecast_df_less_than_50.sort_values(by=&#39;country&#39;, ascending=False)<br>forecast_df_less_than_50 = forecast_df_less_than_50.reset_index()</pre><h4>No Interpolation Needed</h4><pre># evaluate parameters<br>p_values = [0, 1, 2, 4, 6, 8, 10]<br>d_values = range(0, 3)<br>q_values = range(0, 3)<br><br>warnings.filterwarnings(&quot;ignore&quot;)<br><br>for country in country_missing_dates[&#39;Country&#39;][16:].unique():<br>  # I checked US individually<br>  if country == &#39;US&#39;:<br>    continue<br>  else:<br>    print(country)<br>    #filter by country<br>    test = df[df[&#39;country&#39;]==country]<br><br>    test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>    test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>    test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>    test = test.set_index(&#39;date&#39;)<br>    test.index = pd.to_datetime(test.index)<br>    test = test.reset_index()<br>    evaluate_models(test.dollar_amount, p_values, d_values, q_values)</pre><pre>from statsmodels.tsa.arima.model import ARIMA<br><br>forecast_list = []<br>country_list = []<br><br>model_parameters = {&#39;GB&#39;: [1, 1, 1], &#39;AU&#39;: [6, 2, 1], &#39;JP&#39;: [10,1,1], &#39;FR&#39;:[8,1,1], &#39;ES&#39;: [10,1,2], &#39;US&#39;:[6,1,2], &#39;CA&#39;:[8,1,1], &#39;BR&#39;:[8,1,1], &#39;BE&#39;:[0,2,2]}<br><br><br><br>for country in country_missing_dates[&#39;Country&#39;][16:].unique():<br>  # I checked US individually<br><br>  country_list.append(country)<br>  print(country)<br>  country_parameters = model_parameters[country]<br>  test = df[df[&#39;country&#39;]==country]<br><br>  test = test[[&#39;date&#39;, &#39;dollar_amount&#39;, &#39;country&#39;]]<br>  test[&#39;date&#39;] = pd.to_datetime(test.date, format=&#39;ISO8601&#39;)<br>  test[&#39;date&#39;] = test[&#39;date&#39;].dt.strftime(&#39;%Y-%m-%d&#39;)<br><br>  test = test.set_index(&#39;date&#39;)<br>  test.index = pd.to_datetime(test.index)<br>  test = test.reset_index()<br><br>  model = ARIMA(test.dollar_amount, order=(country_parameters[0],country_parameters[1],country_parameters[2]))<br>  model_fit = model.fit()<br>  forecast = model_fit.forecast()<br>  forecast_list.append(forecast.iloc[0])<br>  print(forecast)<br><br>  df = test<br>  # Create Training and Test<br>  train = df.dollar_amount[:320]<br>  test = df.dollar_amount[320:]<br>  model = ARIMA(train, order=(country_parameters[0],country_parameters[1],country_parameters[2]))<br>  fitted = model.fit()<br><br>  # Forecast<br>  fc = fitted.forecast(70, alpha=0.05)<br><br>  fc_series = pd.Series(fc, index=test.index)<br>  plt.figure(figsize=(12,5), dpi=100)<br>  plt.plot(train, label=&#39;training&#39;)<br>  plt.plot(test, label=&#39;actual&#39;)<br>  plt.plot(fc_series, label=&#39;forecast&#39;)<br>  plt.title(&#39;Forecast vs Actuals&#39;)<br>  plt.legend(loc=&#39;upper left&#39;, fontsize=8)<br>  plt.show()<br><br><br><br># Create Best Method DataFrame<br>data = {&#39;country&#39;: country_list,<br>      &#39;best_method&#39;: forecast_list}<br><br>forecast_df = pd.DataFrame(data)<br>forecast_df = forecast_df.sort_values(by=&#39;country&#39;, ascending=False)<br>forecast_df = forecast_df.reset_index()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f38d383be134" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uncovering Data Insights into Los Angeles’ Crime Using Tableau (Crime Data from 2020 to 2024)]]></title>
            <link>https://medium.com/@danielkimwas/uncovering-data-insights-into-los-angeles-crime-using-tableau-crime-data-from-2020-to-present-ce5023505d40?source=rss-8cf473938a8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce5023505d40</guid>
            <category><![CDATA[crime]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[tableau]]></category>
            <category><![CDATA[dashboard]]></category>
            <dc:creator><![CDATA[Daniel Kim ]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 06:16:08 GMT</pubDate>
            <atom:updated>2024-07-28T07:09:38.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*qJuT6WJ-1Rs5rC_Emqy_ig.png" /><figcaption>pic of law enforcement at a crime scene in Los Angeles</figcaption></figure><p>Today, I will be taking a dive into the Los Angeles Crime Data from 2020 Q1 to 2024 Q2 and create an interactive dashboard using Tableau after analyzing the data and seeing if there are any noticeable trends and patterns. Before moving on, I would like to note that this data has been provided by the Los Angeles Police Department and can be downloaded through this <a href="https://catalog.data.gov/dataset/crime-data-from-2020-to-present">link</a>.</p><h3>Exploring the Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBXuTCSNw1OKcVjbvqdfyQ.png" /><figcaption>dataset columns part 1</figcaption></figure><p>A quick look at the dataset (seen above), some key columns are Date Occ (date occurred), Area Name, Crm Cd Desc (a description of type of crime), Vict Age (victim age), and Vict Sex (victim gender).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*NNkLbm4C29K6DQsPCV5KdQ.png" /><figcaption>dataset columns part 2</figcaption></figure><p>As seen in dataset columns part 2 above, the remaining columns show other useful data points such as weapons desc, status desc, and lat &amp; lon (which can be used for charting on a visual map). Most of the main columns seem to be non-null or have data. Some less important but possibly interesting columns such as Weapon Desc seem to have many missing rows so let’s check it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6RrbH3-P5cT6wE1F0Dm7Q.png" /><figcaption>weapons count</figcaption></figure><p>A quick look at the weapons desc bar graph above shows that a majority of the rows are null (634,058). Is this because the dataset is erroneous and missing data points? No. We’ll later see this is in fact okay. Looking at the bar graph above, we can see the next 3 most frequently reported weapon descriptions are Strong Arm, Uknown weapon, and verbal threat. Going back to the question of why there are so many nulls in the weapons desc column, we see (below left chart) that it is actually because these crimes involve either a vehicle being stolen or theft. One can imagine the LAPD only being able to record the incident and not yet apprehend the perpetrator to record/identify any weapon used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baJ7MeZGZ4cg7m5RNpwquQ.png" /></figure><p>On the right chart above, one can see that reported crimes related to assault have the most weapons recorded. It may be of interest for the LAPD, to know what areas contain a high presence of weapons and shootings so I will use this information to later filter out vehicle thefts and focus on assaults when creating a weapons heat map.</p><p>Alright we kind of went on a tangent examining some of the null data. Now let’s get to the summary analysis part. One of the first things I will do is look at the overall time trends such as number of crimes per area in Los Angeles. Below I have created an interactive dashboard that shows amount of crime per area over a time period (2020 Q1 to 2024 Q3). These visuals can help me understand the upward or downwards trends in the various neighborhoods over time. In the screenshot below, I have put a filter on the amount of crime per area chart (bottom most chart) so one can click on different areas and have the other charts change visually based on which ones are included.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uBO3pMW1-1os_cBzcrVSvQ.png" /><figcaption>click this <a href="https://public.tableau.com/views/lapdcrimedata-amountofcrimeperarea/Dashboard2?:language=en-US&amp;publish=yes&amp;:sid=&amp;:redirect=auth&amp;:display_count=n&amp;:origin=viz_share_link">link</a> to see the interactive chart</figcaption></figure><p>Taking a look at the percentage heat map (middle chart) one can observe that overall, crime over time in Los Angeles has increased since 2021 Q1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DuXcuIUZQzVhf3GYG0pOPw.png" /><figcaption>Heat Map of QtoQ % change. Highlighted in yellow 2021 Q3 and 2022 Q2 had overall increase in crime in almost all districts</figcaption></figure><p>From above heat map showing quarter to quarter percent change for all neighborhoods, we can easily see that in year 2020 Q4, crime actually decreased (most rows are orange). This makes sense as covid lockdowns were at its height during 2020 Q4. However, after 2020, crimes begin to tick upwards again from 2021 Q2. 2021 Q3 in almost all areas had larger than normal increases in crime compared to the prior quarter. Another uptick occured in 2022 Q2 before starting to trend downwards. The crimes start to decrease significantly in 2024 which seems a bit suspicious. 2024 Q3 still has not completed so it makes sense it is small but 2024 Q2 is much smaller than prior Q2’s. Perhaps it takes some time for LAPD to log the data into the system? Because of this I decided to leave out 2024 data from the heatmap as a result.</p><p>A final thing we will look at for our initial data analysis is demographic info (age, gender, and race).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRGtGJLCQ8L6MXh_n-a1Zg.png" /><figcaption>crime type by gender (labels show avg age) . <a href="https://public.tableau.com/app/profile/daniel.kim2801/viz/lapdcrimedata-crimemaponeatatime/Dashboard3-gender">link</a></figcaption></figure><p>From the graphs above, one can see that in general women face a higher frequency of assault crimes. Females experienced 35, 471 cases of intimate partner — simple assault crimes whereas males experienced about 11, 096 cases from 1/1/2020–7/1/2024. For intimate partner -aggravated assault, females also faced almost 3 times as many cases as their male counterparts. Accounting for all crimes however, males had a higher frequency of crimes against them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NBSOcj6tUT4v2-VAao56zQ.png" /></figure><p>While I could not find any documentation for the Vict Descent column, I can assume H stands for Hispanic, W for White, and B for Black. If this is incorrect, please let me know. Based on these assumptions, in Los Angeles, the Hispanic population have the most crime victims among the different ethnicities in most assault categories and Whites and Blacks follow. In terms of crime types such as burglary, whites represent the highest frequency.</p><h4>Creating an Interactive Map</h4><p>Interactive maps are a powerful visual tool for analyzing datasets and often allows users to identify patterns more quickly than staring at a table full of coordinate points. Luckily, the LAPD dataset include longitude and latitude points that we can use to map out data onto a visual map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1izjUVaetalH-aqglMXVeQ.png" /><figcaption>heat map with filters such as date range &amp; type of crime</figcaption></figure><p>The map above shows the finished product and I will go step by step in explain the different parts. First off, the heat map is based on the <strong>crime count</strong> grouped by <em>area</em> (neighborhood), <em>Crm Cd Desc</em> (crime type), and the <em>date range</em>. The higher the count, the darker the blue color it is. On the right of the map there are filters for type of crime and start/end date. The start and end date are custom parameters I created that are then used by a calculated field called Date range filter that basically looks for the following:</p><p><em>([Date Occ] &gt;= [Start Date] and [Date Occ] &lt;= [End Date])</em></p><p>This basically only includes dates between the start and end date parameters. There are some limitations to this map. When one adds a bunch of different crime types, the heat map can start to become saturated and not really be useful as it doesn’t highlight clearly neighborhoods where specific types of crimes occur more frequently. Therefore, I find this interactive more useful when only using one or two Crm Cd Desc. For example, below we can add only stolen bikes and quickly identify that most bikes are stolen in the Pacific area from 1/1/2020–8/1/2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acvQy6qBAW-4kEeYWD804Q.png" /><figcaption>stolen bike heat map</figcaption></figure><p>Adding the crime types prowler and reckless driving one can see that West Valley is actually the main hotspot for such activities with 71 occurences between 2021 and 2024 (see heat map below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klALBiVqyDLfuWKDHa2tmw.png" /><figcaption>heatmap filtered on crime type prowler and reckless driving with dates 1/1/2020- 7/1/2024. Click <a href="https://public.tableau.com/app/profile/daniel.kim2801/viz/lapdcrimedata-crimemaponeatatime/crimemaponeatatime?publish=yes">link</a> to see map.</figcaption></figure><p>Moving on, let’s now create a weapons heat map that shows the frequency of certain types of weapons by area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JqKPZSyrmlFXzEjL_VrMw.png" /><figcaption><a href="https://public.tableau.com/app/profile/daniel.kim2801/viz/lapdcrimedata-crimemaponeatatime/weaponsmap">weapons heat map</a></figcaption></figure><p>Above one can see the weapons heat map with the darker orange showing higher frequencies per area for a specific weapon (in this case folding knife). Again, this map works best by looking at one weapon at a time. Notably, one can see that up north in mission neighborhood, one can see there is a high occurrence of folding knifes compared to other areas. This is a bit unexpected as the northern parts where mission is usually has much less crime occurrences than the Central and 77th street areas.</p><p>For air pistols/revolvers (seen in the map below) we see the more usual pattern of seeing high freqencies in the main crime areas of 77th Street, Southwest, Southeast, and Central.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dEji2acZw3R2WdDhOHqE9g.png" /></figure><h4>Creating a Dashboard for Crime Status</h4><p>The final thing I want to make before consolidating all the dashboards into a tableau story is a crime status dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQBVW6wZQERPtqsqC2C0aw.png" /><figcaption><a href="https://public.tableau.com/app/profile/daniel.kim2801/viz/lapdcrimedata-crimemaponeatatime/crimestatusdash">crime status dashboard</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Nrgx2Y3JVsWASLwijunEA.png" /><figcaption>QtoQ % change</figcaption></figure><p>Above is a visual of the crime status dashboard showing a time series on the left of the count of status descriptions over time from 2020–2024. Because 2024 Q3 had so little data, I decided to omit it. On the right of the time series chart, I created a bar graph of the various different types of crime and colored the bars by crime status. I also added a filter on this bar graph so one could click on any of the crime types and have the time series and the heat maps below zoom into that specific crime so we could find more specific info on them. Below the time series and bar chart, I added a count heatmap that colors in darker blue those status descriptions with higher frequencies and in ligher blue those with less occurrences. Finally, I added a QtoQ % change heatmap table to allow users to more easily identify increases and decreases from quarter to quarter. For the heatmaps I purposely excluded crime statuses of juveniles and UNK because there were so few compared to Adult Arrest, Adult Other, and Invest Cont that they would mess up the heatmap and highlight increases that were not significant.</p><p>As the dashboard is interactive, I hope whoever is reading this you can play around a bit with the filtering set on the bar chart to see different results based on the crime type chosen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yiqo4DMKGZ03tqQCj7pWbA.png" /></figure><p>From just a glance, one can see that crime descriptions such as <em>vehicle- stolen </em>and <em>burglary</em> almost have an overwhelming amount of status descriptions — <em>Invest Cont</em>. On the flipside crimes such as <em>intimate partners -simple assault</em> seem to have at least been looked into (not Investigation continued) and have half of their cases categorized as <em>Adult Arrest</em> and <em>Adult other</em>. We can also see from the first pic on the crime status dashboard that <em>intimate partners -simple assault</em> is actually seasonal and they appear to increase always near the end of Q3 in year 2021–2023. Perhaps in the future the LAPD can give officers during fall season a heads up they will more than likely see more <em>intimate partners assault</em> occurrences and have adequate experts on board.</p><p>With the crime status dashboard completed, I finally combined all the relevant dashboards into one story and have added it below. I hope you enjoyed this explanation of the tableau dashboards I have created and feel free to expound upon them as they are all available on tableau public library! Click here to see the <a href="https://public.tableau.com/views/lapdcrimedata-crimemaponeatatime/LAPDCrimeDashboard?:language=en-US&amp;:sid=&amp;:redirect=auth&amp;:display_count=n&amp;:origin=viz_share_link"><strong>final product</strong></a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPkA9qsjiHjJ0PuvtG-iXQ.png" /><figcaption>click <a href="https://public.tableau.com/app/profile/daniel.kim2801/viz/lapdcrimedata-crimemaponeatatime/LAPDCrimeDashboard">here</a> to go to the tableau story!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce5023505d40" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>