<?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 Bryant Crocker on Medium]]></title>
        <description><![CDATA[Stories by Bryant Crocker on Medium]]></description>
        <link>https://medium.com/@Psr1?source=rss-93a17102968d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*lfXME4ac71KPPGuwYRKxtg.jpeg</url>
            <title>Stories by Bryant Crocker on Medium</title>
            <link>https://medium.com/@Psr1?source=rss-93a17102968d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:05:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Psr1/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[How to Predict a Time Series Part 1]]></title>
            <link>https://medium.com/data-science/how-to-predict-a-time-series-part-1-6d7eb182b540?source=rss-93a17102968d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d7eb182b540</guid>
            <category><![CDATA[tidyverse]]></category>
            <category><![CDATA[real-world-forecasting]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Bryant Crocker]]></dc:creator>
            <pubDate>Tue, 09 Jul 2019 18:14:38 GMT</pubDate>
            <atom:updated>2019-11-10T14:01:06.862Z</atom:updated>
            <content:encoded><![CDATA[<h4>Real World Forecasting</h4><h4>Classical time series methods with the forecast package</h4><p>Time series forecasts are quite different from other supervised regression problems. My background is in business analytics, so I’ve learned quite a bit about classical forecasting methodology (arima, exponential smoothing state space models , moving average etc…). When talking to many data scientists, I have found that many of them know little about predicting time series and treat it like other supervised learning problems with little success (usually because they aren’t engineering the right features).</p><p>The R forecast library is one of the most complete and popular libraries for handling and forecasting time series. While I do recognize that python has become more popular among data scientists, this does not mean that it is the best language for everything. Time series forecasting in R is much more mature and routine.</p><p>The goal of this article is walk through forecasting workflow and evaluation. Thus, I will leave the math to a minimum in this blog post. There are many blog posts that deal with the math behind these methods and I will link to a few. In this blog post I ‘d like to share a few things I learned from forecasting a lot of time series using the forecast package. In follow up blog posts I will cover workflow with facebook prophet and workflow for one step ahead predictions using supervised machine learning algorithms.</p><p>Not all the code used to write this article will be presented in the blog post. The full code with even more examples can be found on my <a href="https://github.com/pysr1/Forecasting">github</a>.</p><h4>How are Time Series Forecasts Different from other Supervised Learning Problems:</h4><ol><li>It is unprincipled to use k fold randomized cross-validation (because maintaining temporal order is important)</li><li>We are extending a trend outside the range of observed data</li><li>Popular machine learning algorithms (xgboost, linear regression, MLP neural networks etc…) typically won’t work well without heavy feature engineering</li><li>Understanding uncertainty around point estimations can be more important than the point estimates themselves for decision making, especially in a business setting</li></ol><h4><strong>The Data — Seattle Bikes:</strong></h4><p>The time series that I will try to predict is the weekly recorded bike path volume in the city of Seattle. The script seatleBike.r creates this dataset (pulls together 13 public datasets from Seattle open data portal, aggregates to weekly frequency).</p><p>I’ll start off with a quick line plot to visualize the time series.</p><pre>df_day %&gt;% <br>  ggplot(aes(ds, y))+<br>  geom_line()+ <br>  labs(x = &quot;Date&quot;, y = &quot;Traffic&quot;, title = &quot;Seattle Bike Traffic&quot;)+<br>  theme_minimal()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ZqHqMfOFk3dy9fLUK4-B7g.png" /></figure><p><strong>Observations and important notes:</strong></p><ul><li>We can see that the time series has <strong>seasonality</strong>. <strong>Seasonality</strong> refers to a periodic pattern, within years, that is related to the calendar day, month, quarter etc…</li><li>We can see that the time series does not appear to have a <strong>trend. </strong>a <strong>trend</strong> is a long run upward or downward direction in the series.</li><li>It appears that bike traffic is much higher during summer weeks than winter weeks. We would expect this because Seattle is cold and rainy in the winter.</li></ul><p>When predicting a time series, we typically use previous values of the series to predict a future value. Because we use these previous values, it’s useful to plot the correlation of the y vector (the volume of traffic on bike paths in a given week) with previous y vector values. This plot is called an auto correlation plot (auto correlation because it correlation with itself).</p><pre>ggAcf(df_day %&gt;% convert()) + theme_light() + labs(title = &quot;ACF plot of Seattle Bikes Series&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*CC4NJDCChwmr3FFzJ8_c_Q.png" /></figure><p><strong>Notes:</strong></p><ul><li>The strongest correlation is with the most recent value. This is typical with time series</li><li>We can see there is a strong negative correlation around 26 weeks. We should expect this given the seasonality of the time series</li><li>There is a strong correlation with the observation a year (52 weeks) prior, this is expected.</li><li>We can see that the correlation drops off around 3 or 4 lags. Classical time series models will learn this structure and we can create lagged variables to incorporate this into our machine learning models.</li></ul><h4><strong>Setting a Baseline with a Seasonal Naive Model:</strong></h4><p>Our time series does not appear to have a trend, but it does have seasonality. When there is seasonality in a time series (which is typically the case in most real world time series) a good baseline model is a seasonal naive model.</p><p>A seasonal naive model predicts the last value of the same season (same week last year) when forecasting. We can fit these models with the snaive() function from the <a href="https://cran.r-project.org/web/packages/forecast/index.html">forecast </a>package. I previously stated that I would limit the math in order to zoom in on forecasting workflow. This is the only formula that I will present in the blog post. I opted to present formula to introduce notation frequently used in forecasting. I will link to more info on the formulas/math behind the rest of the models presented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*9l6BjMufWIS8CZDqsYFmkg.png" /><figcaption>source = <a href="https://otexts.com/fpp2/simple-methods.html">https://otexts.com/fpp2/simple-methods.html</a></figcaption></figure><p>I fit the model on the train set, and predict on a held out test set to see how the model performs forecasting data that it hasn’t seen.</p><pre>naiv = train %&gt;% <br>  snaive(h=length(test), bootstrap = T, level = 0.89) <br>naiv %&gt;% <br>  forecast_eval(model_name = &quot;Seaonal Naive&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*r1RHoa3rjmvJwNup8oz0lg.png" /></figure><ul><li>The snaive forecast looks pretty good. The forecast is off by about 56953.55 on average on the test set (MAE). This is pretty good for a simple model on real world data.</li><li>The prediction interval covers most of the points</li><li>The model would perform much worse if the data had a trend</li><li>The model misses the large May and April spikes which can been seen reaching far above the forecast’s predictive interval</li><li>The uncertainty around the predictions grows with time</li><li><strong>A model must perform better than this to even be viable</strong></li></ul><p>Another way that we can evaluate forecasts is by checking the models residuals on the training set with the checkresiduals() functions. The function returns the test statistic for a Ljung-Box test, which is a null hypothesis test to see whether the residuals are white noise. I don’t like null hypothesis testing so I will only do this once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*OFLAFteR-FgxilekHwo2jw.png" /><figcaption>residual analysis</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*o7W85QyWMELWnyI0mu8Fgw.png" /><figcaption>Nothing worse than null hypothesis tests</figcaption></figure><p>Another issue with residual analysis is that is stresses the accuracy of point estimates rather than the accuracy of the predictive interval. These tests also come with a laundry list of assumptions that often aren’t met with real world time series.</p><h4>auto.arima:</h4><p>auto.arima() is one of the most popular functions in the forecast package. Despite its popularity, I am not a big fan of it. In my experience, arima models work best with monthly, quarterly or yearly data, but fail to capture the seasonality of weekly or daily data without Fourier terms (which auto.arima doesn’t use). Still, <strong>auto.arima() is often the only forecasting function that data scientists use</strong>.</p><pre>aarim = train %&gt;% <br>  auto.arima() %&gt;% <br>  forecast(h = length(test), level = 0.89)<br>aarim %&gt;% <br>  forecast_eval(model_name = &quot;Arima&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Y06gLlFiYOrWREsVobaggA.png" /><figcaption>auto.arima</figcaption></figure><ul><li>The auto.arima() function performs worse than just guessing last years value (the snaive() model)</li><li>arima models <a href="https://robjhyndman.com/hyndsight/forecasting-weekly-data/">don’t tend to work well on weekly data</a> (Dr. Hyndman wrote the package, so if you don’t trust me trust him)</li></ul><p>The auto.arima function chose an SARIMA(1,0,0)(1,1,0)[52] with drift. Lets slow down and explain this notation.</p><p>SARIMA models follow the form (p,d,q)x(P,D,Q)m, arima models follow the form (p, d, q):</p><p>p = number of autoregressive terms</p><p>d = number of differences</p><p>q = number of moving average terms</p><p>P=number of seasonal autoregressive terms</p><p>D=number of seasonal differences</p><p>Q=number of seasonal moving average terms</p><p>m = frequency</p><p>drift = drift coefficient or constant (both arimas and sarimas can include drift)</p><p>So that means that our model is an SARIMA model that has 1 autoregressive term, 1 seasonal autoregressive term, and 1 seasonal difference term. The model has no moving average or seasonal moving average terms. It also has a drift coefficient. We can confirm this with the summary function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*xm-e9fZMtK83qfqmy49b_w.png" /><figcaption>Arima model summary</figcaption></figure><p>Those interested in learning more about arima models can refer to the package author’s book or this <a href="https://people.duke.edu/~rnau/411arim.htm?fbclid=IwAR0BkB6uIiFsoV1NicmHhKbGKvlgHA7Jn1VLXUhgQaoMnHk3SU8k6Jhg19Y">link</a>.</p><p>When an arima model is created with additional exogenous regressors and domain knowledge, they tend to perform quite well. when analysts opt to just use the auto.arima function, models don’t tend to perform well (especially for weekly data).</p><h4><strong>Exponential Smoothing:</strong></h4><p>Exponential smoothing methods are a family of related models, that use exponentially decreasing weights for previous values to predict the current value of a time series. These methods are extremely popular in the business analytics and supply chain domains. For the sake of brevity, I am going to use the ETS function which fits a variety of exponential smoothing methods and selects the best one. I highly recommend that you read more about the function <a href="https://otexts.com/fpp2/ets.html">here</a>. This article is getting rather long, so I will not explain further.</p><pre>ETS = train %&gt;% <br>  ets() %&gt;% <br>  forecast(h = length(test), bootstrap = T, level = 0.89, lamda = &#39;auto&#39;)<br>ETS %&gt;% <br>forecast_eval()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*lgLs6YPcp1Ucw4oKyXP4CQ.png" /><figcaption>ETS model fit</figcaption></figure><ul><li>There is a large amount of uncertainty in the forecast distribution based on the ETS model</li><li>The model totally fails to fit the seasonality because it does not handle a frequency greater than 24</li></ul><p>Exponential smoothing models tend to work well daily data (if it doesn’t have a yearly seasonality so frequency can be set to 7), monthly and yearly data, but not weekly data. In many business situations we need to forecast weekly data and understand uncertainty.</p><h4>TBATS:</h4><p><strong>TBATS is typically my go to method for forecasting time series with the forecast package</strong>. Like other methods in the forecast package, it is fully automatic. The model itself is flexible enough to fit a bunch of different time series and is still relatively fast to fit.</p><p>TBATS is an extension of exponential smoothing methods, that adds ARMA errors and trigonometric terms. One could write a whole blog post about this method, so I will opt to link to a couple of good posts on the method for those who are interested because a full explanation would simply make this article too long.</p><pre>TBATS = train %&gt;% <br>  tbats()</pre><pre>TBATS_for = TBATS %&gt;% <br>  forecast(h = length(test))<br>TBATS_for %&gt;% <br>  forecast_eval(&quot;Tbats&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*z2gLGoX3yOQpOgDG5EUJdg.png" /><figcaption>TBATS forecast</figcaption></figure><ul><li>TBATS performs the best of all methods presented thus far</li><li>TBATS does a good job of representing where it is uncertain about predictions</li><li>TBATS intervals can sometimes be too wide as the package author has <a href="https://otexts.com/fpp2/complexseasonality.html">pointed out</a></li></ul><h4>lets zoom in on the TBATS fit on the test set:</h4><p>I know the subtitle is incorrect the prediction interval is in grey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eGwyUgwIfHNcmeTAA-e8_A.png" /></figure><ul><li>Uncertainty is much higher in the summer and early fall than the rest of the year</li><li>Several successive points fall outside the prediction interval</li></ul><h4>Summary:</h4><ul><li>TBATS is a flexible, accurate, algorithm that often outperforms other classical methods</li><li>Classical time series methods fail to predict large anomalies</li><li>All of the models presented used automatic model selection procedures</li></ul><p>To find out more about forecasting I highly recommend checking out Rob Hyndman, the package author’s <a href="https://otexts.com/fpp2/">book</a>. Dr. Hyndman is also working on a new version of the book using the new <a href="https://fable.tidyverts.org/">fable </a>package which brings forecasting to the tidyverse (to check it out just change the 2 to a 3 in the URL). I have not been able to get fable to run on my machine yet. It will also likely be a while until it as mature as the forecast package, so for now I would stick to using the forecast package.</p><p><a href="https://github.com/pysr1/Forecasting">CODE</a></p><h4>Required note from <a href="https://data.seattle.gov/stories/s/Data-Policy/6ukr-wvup/">Seattle Open Data Portal:</a></h4><p>“The data made available here has been modified for use from its original source, which is the City of Seattle. Neither the City of Seattle nor the Office of the Chief Technology Officer (OCTO) makes any claims as to the completeness, timeliness, accuracy or content of any data contained in this application; makes any representation of any kind, including, but not limited to, warranty of the accuracy or fitness for a particular use; nor are any such warranties to be implied or inferred with respect to the information or data furnished herein. The data is subject to change as modifications and updates are complete. It is understood that the information contained in the web feed is being used at one’s own risk.”</p><p>The modifications that have been made to the dataset can all be read clearly from my code.</p><p>license for this article: <a href="https://creativecommons.org/licenses/by-sa/3.0/">https://creativecommons.org/licenses/by-sa/3.0/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d7eb182b540" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-predict-a-time-series-part-1-6d7eb182b540">How to Predict a Time Series Part 1</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ranking Programming Languages by Wikipedia Page Views]]></title>
            <link>https://medium.com/data-science/ranking-programming-languages-by-wikipedia-page-views-f810a04ec55b?source=rss-93a17102968d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f810a04ec55b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Bryant Crocker]]></dc:creator>
            <pubDate>Sat, 06 Apr 2019 21:19:40 GMT</pubDate>
            <atom:updated>2023-07-06T12:07:21.993Z</atom:updated>
            <content:encoded><![CDATA[<h4>A demonstration of using APIs and plotting in python</h4><p>There are many different ways to rank the popularity of programming languages. The <a href="https://www.tiobe.com/tiobe-index/">Tiobe Index</a> is a popular site that ranks programming languages by popularity. I’ve also seen articles where people look at counts of job listings or counts of Stack Overflow questions to rank the popularity of programming languages.</p><p>Today I am going to make use of the <a href="https://wikimedia.org/api/rest_v1/#/Pageviews%20data">Wikimedia API </a>to rank a list of programming languages by there total page views since the start of 2018.</p><p>Luckily, python comes with the handy, built in, requests library, which makes getting data from APIs extremely easy. I defined a simple function to get pageviews data from <a href="https://wikimedia.org/api/rest_v1/">pageviews API</a>.</p><p><strong>API request function:</strong></p><pre>import requests<br>import numpy as np<br>import pandas as pd</pre><pre>def wikimedia_request(page_name, start_date, end_date = None):<br>    &#39;&#39;&#39;<br>    A fucntion that makes requests to the wikimedia pagecveiws API</pre><pre>Parameters<br>    ----------<br>    page_name : string<br>    A string containing the name of the wikipeida page you would like pageviews for<br>    <br>    start_date : string<br>    a date string YYYY/MM/DD indicating the first date that the request should return<br>    <br>    end_date : string<br>    a date string YYYY/MM/DD indicating the last date that the request should return. defaults to system date<br>    Returns<br>    -------<br>    df : pandas DataFrame<br>    A dataframe with the article name and the number of pageviews.<br>    &#39;&#39;&#39;<br>    <br>    # get rid of the / in the date<br>    sdate = start_date.split(&quot;/&quot;)<br>    # join together the text that was split<br>    sdate = &#39;&#39;.join(sdate)<br>    # if an end date is not specified<br>    if end_date == None:<br>        #get the current date<br>        end_date = str(datetime.datetime.now())[0:10].split(&quot;-&quot;)<br>        edate = &#39;&#39;.join(end_date)<br>    else:<br>        # use date from end_date argument<br>        edate = end_date.split(&quot;/&quot;)<br>        edate = edate[0] + edate[1] + edate[2]<br>    # use these elements to make an api request<br>    r = requests.get(<br>        &quot;<a href="https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/%7B%7D/daily/%7B%7D/%7B">https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/{}/daily/{}/{</a>}&quot;.format(page_name,sdate, edate)<br>    )<br>    # get the json<br>    result = r.json()<br>    # convert to dateframe<br>    df = pd.DataFrame(result[&#39;items&#39;])<br>    # the wikimedia api returns 2 extra zeros at the end of the timestamp for some reason<br>    df[&#39;timestamp&#39;] = [i[:-2] for i in df.timestamp]<br>    # convert to datetime<br>    df[&#39;timestamp&#39;] = pd.to_datetime(df[&#39;timestamp&#39;])<br>    # set timestamp as index<br>    df.set_index(&#39;timestamp&#39;, inplace = True)<br>    # return the article and views columns<br>    return df[[&#39;article&#39;, &#39;views&#39;]]</pre><p>Once this function is defined it can easily be used in conjunction with a list comprehension to create a dataframe of page views for multiple pages. I define a list of 20 programming languages that I am interested in (admittedly a somewhat random list, this post is mostly to demonstrate a technique), and then do exactly that.</p><pre>names = [&#39;Python (programming language)&#39;, &#39;R (programming language)&#39;, &#39;Java (programming language)&#39;, <br>         &#39;Scala (programming_language)&#39;, &#39;JavaScript&#39;, &#39;Swift (programming language)&#39;, &#39;C++&#39;, <br>         &#39;C (programming language)&#39;, &#39;Clojure&#39;, &#39;C Sharp (programming language)&#39;, &#39;F Sharp (programming language)&#39;,<br>        &#39;Julia (programming language)&#39;, &#39;Visual Basic .NET&#39;, &#39;Perl&#39;, &#39;Haskell (programming language)&#39;,<br>        &#39;Go (programming language)&#39;, &#39;Ruby (programming language)&#39;, &#39;PHP&#39;, &#39;Bash (Unix shell)&#39;, &#39;TypeScript&#39;]</pre><pre>dfs = pd.concat([wikimedia_request(x, start_date) for x in names])</pre><p>I personally love python list comprehensions because they allow for clean, readable code. Most of the things in this article would take much more code in other languages.</p><h3>Graphing Popularity:</h3><p>Now that I have the data on programming languages, I can use pandas and matplotlib to create a simple plot to see which languages have had the most search volume over since the start of 2018.</p><pre>means = dfs.groupby(&#39;article&#39;).mean()[&#39;views&#39;]<br>means.sort_values(ascending = False).plot(kind = &#39;barh&#39;, color =&#39;C0&#39;, figsize = (12,6))<br>plt.title(&#39;Total Wikipedia Page Views&#39;)<br>sns.despine()<br>plt.xlabel(&#39;Count of Page Views&#39;)<br>plt.ylabel(&quot;&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*cXD6VxW6LAr6rWZaYwUV1A.png" /></figure><ul><li>In most language ranking lists python, java , javascript and C fight for the top spot</li><li>It looks like from my data, python is the most popular</li><li>Python use has been growing over the last few years</li><li>This is good for me, because python is the main language I use</li></ul><p>I’m also interested in the trends in monthly search volume for each of the language’s page. Which languages are showing an upward trend in interest? Which languages are showing a downward trend in interest?</p><p>I’d like to make simple regression plots to evaluate the temporal trends in language interest. This is a bit hard to do in python, because seaborn’s regplot does not accept datetime objects. I’ve adapted code from this <a href="https://stackoverflow.com/questions/29308729/can-i-plot-a-linear-regression-with-datetimes-on-the-x-axis-with-seaborn">stack overflow</a> answer to create regression plots with time series in python.</p><pre>def tsregplot(series, ax = None, days_forward = 10, color = &#39;C0&#39;):<br>        &#39;&#39;&#39;<br>    A fucntion that makes requests to the wikimedia pagecveiws API</pre><pre>Parameters<br>    ----------<br>    series : Pandas datetime index Series<br>    A pandas Series with datetime index<br>    <br>    ax : matplotlib axes object<br>    A matplotlib axes obect<br>    <br>    days_forward : int<br>    An integer indicating how many days to extend the regression line. This is set at 10 by default so that all points can show. increasing it can be used to forecast regression line foreward<br>    <br>    color : string<br>    A matplotlib color string <br>    <br>    Returns<br>    -------<br>    ax : matplotlib axes object<br>    returns a matplotlib axes object with regplot<br>    &#39;&#39;&#39;<br>    series = series.reset_index()<br>    series.columns = [&#39;date&#39;, &#39;value&#39;]<br>    if ax == None:<br>        series[&#39;date_ordinal&#39;] = pd.to_datetime(series[&#39;date&#39;]).apply(lambda date: date.toordinal())<br>        ax = sns.regplot(<br>        data=series,<br>        x=&#39;date_ordinal&#39;,<br>        y=&#39;value&#39;,<br>        color = color<br>        )<br>        ax.set_xlim(series[&#39;date_ordinal&#39;].min() - 2, series[&#39;date_ordinal&#39;].max() + days_forward)<br>        ax.set_ylim(series[&#39;value&#39;].min() - 1000, series[&#39;value&#39;].max() + 1000)<br>        ax.set_xlabel(&#39;date&#39;)<br>        new_labels = [date.fromordinal(int(item)) for item in ax.get_xticks()]<br>        ax.set_xticklabels(new_labels)<br>    else:<br>        series[&#39;date_ordinal&#39;] = pd.to_datetime(series[&#39;date&#39;]).apply(lambda date: date.toordinal())<br>        ax = sns.regplot(<br>        data=series,<br>        x=&#39;date_ordinal&#39;,<br>        y=&#39;value&#39;,<br>        ax = ax, <br>        color = color<br>        )<br>    <br>        ax.set_xlim(series[&#39;date_ordinal&#39;].min() - 5, series[&#39;date_ordinal&#39;].max() + days_forward)<br>        ax.set_ylim(series[&#39;value&#39;].min() * 0.9 , series[&#39;value&#39;].max()* 1.1)<br>        ax.set_xlabel(&#39;date&#39;)<br>        new_labels = [date.fromordinal(int(item)).strftime(&quot;%m/%Y&quot;) for item in ax.get_xticks()]<br>        ax.set_xticklabels(new_labels)<br>        return ax</pre><p>I can create a simple for loop to plot a time series regression plot for each of the 20 languages:</p><pre>fig, ax = plt.subplots(10,2, figsize = (16, 20))<br>ax = ax.ravel()<br>counter = 0<br>for i, j in zip(dfs.article.unique(), names):<br>    string = i<br>    selected = dfs.query(&quot;article == &#39;{}&#39;&quot;.format(string))<br>    tsregplot(selected[&#39;views&#39;].resample(&#39;M&#39;).sum()[:-1], ax = ax[counter])<br>    ax[counter].set_title(j)<br>    plt.tight_layout()<br>    counter += 1<br>plt.savefig(&#39;trendplots.png&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vPdOfVGIdXTJa4igw5hGQ.png" /></figure><p><strong>A few things to note:</strong></p><ul><li>Based on Wikipedia page views, <strong>python interest has actually been declining</strong>.</li><li>Based on Wikipedia page views, there may be an increase in Julia interested, but it looks like its more than likely noise.</li><li>Based on Wikipedia page views, interest in Java is growing and interest in Scala is shrinking. <a href="https://medium.com/skedulo-engineering/scala-programming-a-skeptics-journey-ac680053780f">Scala was created to be a more simple and modern substitute for Java</a>. This surprises me a bit.</li><li>There is a steep growth in interest in TypeScript, this has been documented in <a href="https://medium.com/javascript-scene/the-typescript-tax-132ff4cb175b">many articles</a></li><li>Based on Wikipedia page views, GO interest has been increasing modestly. GO is often said to be the python killer for server languages. I’ve played with GO a tiny bit myself and but don’t find it very useful for what I do (mostly data science).</li></ul><p><strong>Conclusion:</strong></p><p>There are many different ways to rank programming languages. I currently am unable to find anyone else that has used wikipedia page views to rank programming languages (yes someone has likely already done it, but its not common enough to find articles about it).</p><p>I think that Wikipedia page views are a pretty reasonable way to gauge interest in programming languages or other topics of public interest. When I am interested in a new programming language, wikipedia is usually the first place I look. I think it is also safe to assume that many others do the same.</p><p><a href="https://github.com/pysr1/wikimediaProgrammingLanguages"><strong>The code can be found here</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f810a04ec55b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/ranking-programming-languages-by-wikipedia-page-views-f810a04ec55b">Ranking Programming Languages by Wikipedia Page Views</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring The SP500 With R Part 2: Asset Analysis]]></title>
            <link>https://medium.com/data-science/exploring-the-sp500-with-r-part-2-asset-analysis-657d3c1caf60?source=rss-93a17102968d------2</link>
            <guid isPermaLink="false">https://medium.com/p/657d3c1caf60</guid>
            <category><![CDATA[asset-management]]></category>
            <category><![CDATA[r-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tidyverse]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Bryant Crocker]]></dc:creator>
            <pubDate>Fri, 05 Apr 2019 23:31:15 GMT</pubDate>
            <atom:updated>2021-05-14T12:43:22.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scraping and Exploring The SP500 With R Part 2</h3><h4>Asset analysis and visualization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*hpXiAvYrZm5HKViB" /><figcaption>photo credit: <a href="https://unsplash.com/photos/uJhgEXPqSPk">https://unsplash.com/photos/uJhgEXPqSPk</a></figcaption></figure><p>In the<a href="https://medium.com/@Psr1/exploring-the-sp500-with-r-part-1-scraping-data-acquisition-and-functional-programming-56c9498f38e8"> first part of this blog post,</a> I walked through scraping a list of SP500 symbols from wikipedia and using that information to pull OHLC (Open, High Low, Close) data for all SP500 tickers from the yahoo finance API.</p><p>In the second part of this blog post, I will walk through answering my original question:</p><p><em>Which SP500 assets had the highest average return over the last 3 months?</em></p><p>In part 1, we created tickers_df, a dataframe with all 505 SP500 tickers.</p><p><strong>lets take a quick look again at tickers_df:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*0Sy_35tvfxR7kAopeXRMQw.png" /></figure><p>This data is <strong>tidy</strong> meaning:</p><ul><li>each variable is a column</li><li>each observation (or case) is a row</li></ul><p>This structure makes the data easy to filter and aggregate, and makes it easier to scale. We can easily extract and visualize one of the assets raw prices over time with just a few lines of code:</p><pre>ticker = &quot;GOOGL&quot;<br>tickers_df %&gt;% <br>  filter(symbol == !!ticker) %&gt;% <br>  ggplot(aes(date, adjusted))+<br>  geom_line()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*83xB0ioS1yED2NHl1OnU-w.png" /></figure><p>We can look at raw price data all day, but it is hard to compare assets that have drastically different prices. Typically, when we analyze assets, we look at the percentage change in prices or returns. Using the tidyquant package, it is extremely easy to calculate returns. In the following snippet, I convert each assets raw adjusted closing prices to returns. This is done using the tq_transmute() function.</p><pre>daily_sector = tickers_df %&gt;% group_by(security, gics_sector, symbol) %&gt;% <br>tq_transmute(select     = adjusted, <br>              mutate_fun = periodReturn, <br>              period     = &quot;daily&quot;) %&gt;% <br>              ungroup()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*om_44v5YSmLFTbI6ocA1iw.png" /></figure><p>A few things to note:</p><ul><li>The data is still tidy</li><li>We have information from both the Yahoo finance API and the wikipedia page that we scraped</li><li>With this format it is very easy to aggregate by symbol, security or gics_sector</li><li>Don’t forget to ungroup! I did initially</li></ul><p><strong>Top Performers:</strong></p><p>Let’s go ahead and compute the average daily return by security and then sort by this, to answer my question. I will also compute the standard deviation of the returns. In quantitative finance, the standard deviation of returns is generally referred to as volatility.</p><pre>avg_return =daily_sector %&gt;% <br>  group_by(security, gics_sector) %&gt;%<br>  summarise(avg_return = round(mean(daily.returns), 4),Volatility =   sd(daily.returns)) %&gt;%         <br>arrange(desc(avg_return), desc(Volatility))<br>avg_return %&gt;% head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*YbwZnrxu3HT--3c84EZ5OA.png" /></figure><p>From this table we can quickly see that Dow Inc, the famous American chemical company, has had the highest average daily return over the last 3 months. This table answers my original question.</p><p>Let’s visualize this table as a bar graph using ggplot:</p><pre>avg_return %&gt;% head(20) %&gt;% ggplot(aes(reorder(security, -avg_return), avg_return, fill = avg_return))+<br>  geom_col()+<br>  coord_flip()+<br>  labs(title = &quot;Securities With Highest Average Returns In SP500 Over Past 3 Month&quot;, x = &quot;Security&quot;, y = &quot;Average Return&quot;)+<br>  theme_classic()+<br>  theme(legend.position=&quot;none&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*GuLPHmYwzf1Fu3mN5PePhw.png" /></figure><p>Wow Dow Inc.’s average return is much higher than the rest of the market. There may be something big I’m missing here. A quick google search tells me there’s an obvious reason for this. <a href="https://www.ccn.com/dow-surges-toward-record-high-after-dowdupont-spinoff">Dow INC has only been traded as an independent chemical company since the end of March</a>, when it formally split from Dowdupont. The average return is likely only this high because it is a newly traded asset and we don’t have many observations.</p><p>Looking at the other top performers I notice a few things:</p><ul><li>Many of the top performing companies over the past 30 days have been technology companies.</li><li>I’m a bit suprised by the strong performance of Chipotle. They have clearly rebounded from their previous controversies around <a href="https://www.cnbc.com/2018/02/06/chipotle-has-a-plan-to-regain-customers-it-keeps-losing-to-food-safety-issues.html">food poisoning</a></li><li>Nvidia and Advanced Micro Devices, two computer hardware manufacturers, have seen higher returns than there competitor Intel, who historically has performed better.</li></ul><p>Typically when you answer a question with data, more questions arise. I already know what stocks had the highest return on average over the last few months, but what about volatility? Volatility is one of the most important investment metrics for a security or portfolio.</p><p>According to <a href="https://en.wikipedia.org/wiki/Volatility_(finance)">Wikipedia</a> Investors care about volatility for at least eight reasons:</p><ol><li>The wider the swings in an investment’s price, the harder emotionally it is to not worry;</li><li>Price volatility of a trading instrument can define position sizing in a portfolio;</li><li>When certain cash flows from selling a security are needed at a specific future date, higher volatility means a greater chance of a shortfall;</li><li>Higher volatility of returns while saving for retirement results in a wider distribution of possible final portfolio values;</li><li>Higher volatility of return when retired gives withdrawals a larger permanent impact on the portfolio’s value;</li><li>Price volatility presents opportunities to buy assets cheaply and sell when overpriced;</li><li>Portfolio volatility has a negative impact on the <a href="https://en.wikipedia.org/wiki/Compound_annual_growth_rate">compound annual growth rate</a> (CAGR) of that portfolio</li><li>Volatility affects pricing of <a href="https://en.wikipedia.org/wiki/Option_(finance)">options</a>, being a parameter of the <a href="https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model">Black–Scholes model</a>.</li></ol><p>Typically, younger investors can take on more volatility, while investors closer to retirement want to be careful about volatility.</p><p>Using ggplot2 we can easily plot the relationship between average return and volatility of returns. I will create a scatter plot, using the asset tickers rather than points in the plot.</p><pre>plot = avg_return %&gt;% ggplot(aes(avg_return, Volatility))+<br>  geom_text(aes(label = symbol), size = 3)+<br>  labs(title = &quot;Average Return vs Volatility Over Last 3 Months In SP500&quot;, x = &quot;Average Return&quot;, subtitle = &quot;Data Source: Yahoo Finance&quot;)+<br>  theme_minimal()<br>    <br>plot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*w9rJHgh2_4yybhKZJyLs0Q.png" /></figure><p>This plot gives a much better idea of what’s happening in the market than our previous bar graph.</p><p>A few tickers really stand out compared to the rest of the market</p><ul><li>DOW INC has the highest average return and seems to be around market volatility.</li><li>AMD and Coty stand out as having above market volatility and return. These might be solid investment opportunities for younger investors</li><li>Matel and EA games stand out as having around market returns, but higher volatility. This high volatility gives investors the opportunity to buy when the securities are underpriced and sell when they are overpriced.</li><li>The biggest thing that stands out in the top left corner of the figure is the high volatility and low average return of both Fox corporations asset classes</li></ul><p>Lets highlight Fox Corporation’s tickers on the graph:</p><pre>avg_return = avg_return %&gt;% <br>  mutate(Indicator = case_when(symbol %in% c(&#39;FOX&#39;, &#39;FOXA&#39;) ~ &quot;Fox Corporation&quot;,<br>                               TRUE ~ &quot;The Rest of the SP500&quot;))</pre><pre>plot = avg_return %&gt;% ggplot(aes(avg_return, Volatility, color = Indicator))+<br>  geom_text(aes(label = symbol), size = 3)+<br>  labs(title = &quot;Average Return vs Volatility Over Last 3 Months In SP500&quot;, x = &quot;Average Return&quot;, subtitle = &quot;Data Source: Yahoo Finance&quot;)+<br>  theme_minimal()<br>    <br>plot</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*6xIgqgaeEpnC_YHW8pXjxQ.png" /></figure><p>Wow! look at that! I walked into this analysis interested in which companies were performing the best. But, at the end, what really stood out is the Fox Corporation which, appears to be performing quite weak relative to the rest of the market over the last 3 months.</p><p>The Fox Corporation, especially their news station Faux News (did I spell that right?), has been rather controversial over the years. The network takes a unique perspective on many issues and features much more opinion based shows than the average news network.</p><p>Lets get a little more price data for the Fox Corporation tickers:</p><pre>symbols = c(&#39;FOX&#39;, &#39;FOXA&#39;)<br>fox = tq_get(symbols, from = &#39;2017/01/01&#39;)<br>fox %&gt;% <br>  ggplot(aes(date, adjusted))+<br>  geom_line()+<br>  geom_smooth(method = &#39;lm&#39;, alpha = 0.3)+<br>  facet_wrap(~symbol)+<br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*YjAMr5m_ma6weuDslrix0Q.png" /></figure><ul><li>It appears that over the last few years, both fox symbols have grown steadily</li><li>There was a huge drop in the price recently. and a continued downward trend following</li></ul><p>Lets zoom in on recent prices:</p><pre>tickers_df %&gt;% <br>  filter(symbol %in% c(&#39;FOX&#39;, &#39;FOXA&#39;)) %&gt;% <br>  ggplot(aes(date, adjusted))+<br>  geom_point(alpha = 0.3, color = &#39;black&#39;)+<br>  geom_line()+<br>  facet_wrap(~symbol)+<br>  theme_classic()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*HLAeU8T7kN7On9FOWt1hMA.png" /></figure><p>We can see that the price drop happened in early March. There was an initial large drop on March 13, followed by a brief rebound. Following the rebound the price, dropped and has continued trending downward.</p><p>Let’s turn to Google to figure out what happened on March 13. A quick Google search tells me that Media Matters organized a large protest against Fox Corporation on <a href="https://www.rollingstone.com/politics/politics-news/protesters-flock-to-fox-news-headquarters-to-scare-off-advertisers-807788/">March 13th</a>.</p><p>Following the March 13th drop, on March 19, 2019, Fox Corp began trading independently of 21st Century Fox. This made the price of the asset radically drop. This did not though represent weak performance by the asset, as one would initially think.</p><p>What actually happened is that Fox corporation began trading under 21st Century Fox’s tickers, 21st century Fox is now trading under the tickers TFCF and TFCFA. This led many news outlets to <a href="https://finance.yahoo.com/m/380e2aef-0a4c-3fc3-ad63-aab81c74f8cc/twdc-holdco-613-corp.-.html"><strong>incorrectly report that FOX and FOXA were down 22%</strong></a><strong>.</strong></p><p>Finishing Up and Producing a Final Plot:</p><p>Alright now we want to share what we have found in an interactive plot, so that none technical users can have a fun, informative plot that they can interact with.</p><p>R has a lot of great frameworks for interactive data visualization. My Personal favorite interactive graphing library in R is the plotly library. Plotly is an interactive javascript library with APIs for many different programming languages. I am more familiar with the python API (and the python language in general).</p><p>With very similar code to as used in ggplot2 we can produce a beautiful interactive plot. I will embed the plot in this article.</p><pre>p &lt;- plot_ly(avg_return, x = ~avg_return, y = ~Volatility, type = &#39;scatter&#39;,<br>        mode = &#39;text&#39;, text = ~symbol, textposition = &#39;middle right&#39;,<br>        color = ~Indicator, colors = &#39;Set1&#39;,<br>        textfont = list(size = 8)) %&gt;%<br>  layout(title = &#39;Average Return vs Volatility Over Last 3 Months In SP500&#39;,<br>         xaxis = list(title = &#39;Averaage Return&#39;, zeroline = FALSE<br>                      ),<br>         yaxis = list(title = &#39;Volatility&#39;<br>                      ))</pre><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Ecrocker4569883%2F3%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Ecrocker4569883%2F3.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4115eb9d1a5f9663c362eb055e5af438/href">https://medium.com/media/4115eb9d1a5f9663c362eb055e5af438/href</a></iframe><p><strong>To recap, in this two part series we:</strong></p><ul><li>Went over an introduction to scraping, functional programming, and the tidyverse</li><li>Imported stock data for the whole SP500</li><li>Proposed a question, <strong>Which stocks had the highest average return over the last 3 months?</strong></li><li>We answered this question, and by asking more questions of our data, we answered the question more fully and found what was ultimately interesting was the <strong>seemingly low average return and high volatility of the Fox Corporation tickers relative to the market.</strong></li><li>This circular workflow of continuously asking questions of your data is common in data science</li><li>We need to be careful about data quality and make sure we understand our data. <strong>FOX, FOXA look like they are performing badly and DOW looks like it is performing way better than the rest of the market. These conclusions would be misleading!</strong></li></ul><p><strong><em>Note from Towards Data Science’s editors:</em></strong><em> While we allow independent authors to publish articles in accordance with our </em><a href="https://towardsdatascience.com/questions-96667b06af5"><em>rules and guidelines</em></a><em>, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our </em><a href="https://towardsdatascience.com/readers-terms-b5d780a700a4"><em>Reader Terms</em></a><em> for details.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=657d3c1caf60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exploring-the-sp500-with-r-part-2-asset-analysis-657d3c1caf60">Exploring The SP500 With R Part 2: Asset Analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring The SP500 With R Part 1: Scraping, Data Acquisition and Functional Programming]]></title>
            <link>https://medium.com/data-science/exploring-the-sp500-with-r-part-1-scraping-data-acquisition-and-functional-programming-56c9498f38e8?source=rss-93a17102968d------2</link>
            <guid isPermaLink="false">https://medium.com/p/56c9498f38e8</guid>
            <category><![CDATA[tidyverse]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[scraping]]></category>
            <dc:creator><![CDATA[Bryant Crocker]]></dc:creator>
            <pubDate>Fri, 05 Apr 2019 23:29:18 GMT</pubDate>
            <atom:updated>2021-05-14T12:42:45.706Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scraping and Exploring The SP500 with R Part 1</h3><h4>Scraping, Data Acquisition and Functional Programming</h4><p>Today I wanted to walk through a quick example combining scraping, calls to the Yahoo finance api, data joining and simple asset analysis using functional programming and tidy iteration concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*6-QdVL1GBENc5skt" /><figcaption>photo credit: <a href="https://unsplash.com/">https://unsplash.com</a></figcaption></figure><h3>End Goal:</h3><p>I would like to identify <em>which SP500 assets had the highest average return over the last 3 months.</em></p><h4><strong>The Final result of this </strong><a href="https://medium.com/@Psr1/exploring-the-sp500-with-r-part-2-asset-analysis-657d3c1caf60"><strong>analysis</strong></a><strong> is this chart:</strong></h4><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Ecrocker4569883%2F3%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Ecrocker4569883%2F3.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4115eb9d1a5f9663c362eb055e5af438/href">https://medium.com/media/4115eb9d1a5f9663c362eb055e5af438/href</a></iframe><p>The making of this chart, asset analysis and answering my question will be covered in the <a href="https://medium.com/@Psr1/exploring-the-sp500-with-r-part-2-asset-analysis-657d3c1caf60"><strong>second part of this series</strong></a>.</p><h3>Introduction and the Tidyverse:</h3><p>In todays analysis I will be using the R programming language. If you have read any of my posts on Linkedin or Medium in the past, you may have noticed that I usually program in python. In general, I prefer the python programming language because it has simpler syntax, wider adoption and is easier to put into production.</p><p><strong>R Tidyverse Ecosystem:</strong></p><p>In the R programming language, there is a set of packages that make up what is called the <a href="https://www.tidyverse.org/"><strong>tidyverse</strong></a>. These packages are mostly maintained by engineers and data scientists at Rstudio and provide a simple, integrated and uniform way to manipulate data in R. The tidyverse centers around the idea of <a href="https://vita.had.co.nz/papers/tidy-data.pdf"><strong>tidy data</strong></a> a term coined by Hadley Wickham to describe data where:</p><ul><li>each variable is a column</li><li>each observation (or case) is a row</li></ul><p>I will make use of several tidyverse libraries todays. In the following chunk I import the libraries that I will be using.</p><pre># for scraping<br>library(rvest)<br># blanket import for core tidyverse packages<br>library(tidyverse)<br># tidy financial analysis <br>library(tidyquant)<br># tidy data cleaning functions<br>library(janitor)</pre><p>The next thing that I will do is define a variable with todays date. I then subtract 3 months from todays date. This returns another date object, indicating what day came 3 months before today. I will need this because I want to get the last 3 months of price data for each ticker.</p><pre># save current system date to a variable<br>today &lt;- Sys.Date()<br># subtract 3 months from the current date<br>date = today %m+% months(-3)<br>print(date)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*SOA9vlk0zx1YHNS_TpeFTA.png" /></figure><h3>One Ticker</h3><p>I’m going to use the tidyquant package to get the financial data for all SP500 tickers. The tidyqunat package’s core function is tq_get(), which can be used to get various information about stocks. If I pass a string containing a ticker name to tq_get(), it will return Open, High, Low, Close or OHLC data. I pass ^GSPC, the SP500’s ticker to the tq_get() function.</p><pre># pass SP500 ticker ^GSPC to tq_get function<br>one_ticker = tq_get(&quot;^GSPC&quot;, from = date)<br>one_ticker %&gt;% <br>  head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*wSBIkv74i6uuE_YOhn2Ajg.png" /></figure><p><strong>Theres a few things to note above:</strong></p><ul><li>tq_get() returns a tidy dataframe</li><li>the ticker name is not in the dataframe</li><li>the %&gt;% operator is called a pipe. It passes the object that precedes it as the first argument to the function that follows it.</li></ul><h3>Scaling up part 1 — Getting a Vector of all 505 Tickers:</h3><p><strong>I want OHLC data for all SP500 tickers.</strong> In order to do this, I will need a to do a few things:</p><ul><li>Create a vector of all SP500 tickers</li><li>Iterate over this vector and call tq_get() on each element of the vector, returning a dataframe for each element in the vector</li><li>combine all these dataframes into one dataframe</li></ul><p>Wow! That sounds a little complicated, right? luckily, with R, going about this will be pretty simple. Wikipedia has a table of all 505 SP500 tickers (some companies, like Google, have multiple asset classes) located at this URL:</p><p><a href="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies">https://en.wikipedia.org/wiki/List_of_S%26P_500_companies</a></p><p>To get all the SP500 tickers, we are going to scrape this table, using the rvest package. The rvest package is a simple scraping package in R that is very similar to python’s beautiful soup. In the context of programming, scraping is defined as programmatically collecting human readable content from the internet and webpages.</p><p>In the code below I scrape the wikipedia table and create a vector of all SP500 tickers:</p><ul><li>I first assign the wikipedia URL to a variable</li><li>Read in the html from the URL</li><li>Select the correct html nodes and extract the html table</li><li>Make a small change to ticker names because yahoo finance uses a ‘_’ instead of ‘.’ for certain symbol names</li></ul><p>The hardest part of scraping is figuring out the xpath or css to indicate which html nodes to select. I really don’t know much about html or css, but using Google Chrome I was able to find the correct xpath (more on this below).</p><pre># get the URL for the wikipedia page with all SP500 symbols<br>url &lt;- &quot;<a href="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies">https://en.wikipedia.org/wiki/List_of_S%26P_500_companies</a>&quot;<br># use that URL to scrape the SP500 table using rvest<br>tickers &lt;- url %&gt;%<br>  # read the HTML from the webpage<br>  read_html() %&gt;%<br>  # one way to get table<br>  #html_nodes(xpath=&#39;//*[<a href="http://twitter.com/id">@id</a>=&quot;mw-content-text&quot;]/div/table[1]&#39;) %&gt;%<br>  # easier way to get table<br>  html_nodes(xpath = &#39;//*[<a href="http://twitter.com/id">@id</a>=&quot;constituents&quot;]&#39;) %&gt;% <br>  html_table()<br>#create a vector of tickers<br>sp500tickers &lt;- tickers[[1]]<br>sp500tickers = sp500tickers %&gt;% mutate(Symbol = case_when(Symbol == &quot;BRK.B&quot; ~ &quot;BRK-B&quot;,<br>                                           Symbol == &quot;BF.B&quot; ~ &quot;BF-B&quot;,<br>                                            TRUE ~ as.character(Symbol)))</pre><h4>How to find the xpath I passed to the html_nodes function using Google Chrome:</h4><ul><li>Go to <a href="https://en.wikipedia.org/wiki/List_of_S%26P_500_companies">https://en.wikipedia.org/wiki/List_of_S%26P_500_companies</a></li><li>right click on webpage, select inspect option</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*38DmIWFgt4aVg7FzhM2uCg.png" /></figure><ul><li>Most webpage content is usually in the body of an html document. We’ll expand that section. That will look like this:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*GnDShJcWHEfLP0ghj8OctQ.png" /></figure><ul><li>Looking at the webpage, I can see the table that I want is right below the first h2 header:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*zhge3H80lHcdSsLT7YM3dA.png" /></figure><ul><li>After navigating around the page structure I found the first h2 header and the table I wanted below it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*LErvj_goGgW_evZ7zsuDZw.png" /></figure><ul><li>I can click on the table, right click and copy the xpath that is needed to scrape the table</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*tloKkE86Rm0M2VOVVc6Lcg.png" /></figure><ul><li>xpath = //*[<a href="http://twitter.com/id">@id</a>=”constituents”], this is what was passed to html_nodes</li></ul><pre>html_nodes(xpath = &#39;//*[<a href="http://twitter.com/id">@id</a>=&quot;constituents&quot;]&#39;</pre><h3>Scaling up part 2— Purrr, Iteration, and functional programming:</h3><p>Iterating refers to programmatically repeating a step or sets of steps, a set number of times or until a condition is meant.</p><p>Typically, when we iterate in any programming language, we use a loop, typically a for loop. I will need to iterate over each element in the vector of SP500 tickers and pass it to the function tq_get(). I could do this with a for loop, but using the purrr package is a better idea. Loops in R are slow and hard to read. The purrr package provides a suite of functions for iteration and functional programming that integrate well with the rest of the tidyverse. The core function in purrr in map(). <a href="https://en.wikipedia.org/wiki/Map_(higher-order_function)">Most programming languages</a> (including my favorite one python) have a map function that serves to apply a function to all elements of an object.</p><p><strong>Functional Programming</strong> is a programming paradigm in which functions, as opposed to <a href="https://softwareengineering.stackexchange.com/questions/179965/functional-programming-compared-to-oop-with-classes">classes</a>, build the structure and logic of programs. For loops are typically avoided in functional programming. Instead, functions are mapped or applied to lists or other objects.</p><p>As Hadley Wickham stated perfectly in his <a href="https://adv-r.hadley.nz/fp.html">Advanced R book</a>:</p><p>“It’s hard to describe exactly what a functional <em>style</em> is, but generally I think it means decomposing a big problem into smaller pieces, then solving each piece with a function or combination of functions. When using a functional style, you strive to decompose components of the problem into isolated functions that operate independently. Each function taken by itself is simple and straightforward to understand; complexity is handled by composing functions in various ways.”</p><p>Let’s look at the difference between iteration in purrr and a for loop with an example. Both of these operations are roughly equivalent:</p><pre># get a sequence of the numbers 1 to 5<br>numbers = seq(1:5)<br>print(&#39;for loop&#39;)</pre><pre># for loop <br>for (i in numbers){<br>  <br>  print(i)<br>}</pre><pre>print(&#39;purrr :)&#39;)</pre><pre># purr functional programming approach<br>list = map(numbers, print)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*ypS2rbPj-4wAiCaWancCxQ.png" /></figure><p><strong>A few things to note:</strong></p><ul><li>both the for loop and map function do an operation <strong>for</strong> each element in the vector</li><li>the map function returns a nested list where each entry is the result of the function called inside of it for one of the entries in the object that being iterated over. I assign this to a variable list to avoid it from printing.</li><li>Using purrr’s map function is only one line and less code</li><li>Using purrr’s map function is easier to read</li></ul><h4>Alright now lets iterate to get all 505 SP500 tickers!</h4><p>First I need to write a function to iterate over or apply to each element of the vector. I cannot simply use tq_get() with map() because it does not return the ticker name as a column of the dataframe. In order to get the ticker with the dataframe, I will use the mutate() function from dplyr to create a new column with the ticker name.</p><pre>get_symbols = function(ticker = &quot;AAPL&quot;){<br>  df = tq_get(ticker, from = date) %&gt;% mutate(symbol = rep(ticker, length(date)))<br>}</pre><p>I then use this function in conjunction with map() to iterate over the list of all symbols. This returns a nested list containing a dataframe for each ticker. I use the dplyr bind_rows() function to bind the dataframes together row-wise, to create one dataframe with all the SP500 tickers.</p><pre>#create the dataframe of SP500 data by interating over our list of symbols and call our get symbols function each time<br>#the map function accomplishes this</pre><pre>tickers_df = map(symbols, get_symbols) %&gt;% bind_rows()</pre><p>I also want this dataframe to contain the information from the wikipedia table, most importantly, the name of the company. This can be achieved by joining the two dataframes by the symbol.</p><pre>tickers_df = tickers_df %&gt;% <br>  # left join with wikipedia data<br>  left_join(sp500tickers, by = c(&#39;symbol&#39; = &#39;Symbol&#39;)) %&gt;% <br>  # make names R compatible<br>  clean_names() %&gt;% <br>  # keep only the columns we need<br>  select(date:security, gics_sector, gics_sub_industry)</pre><p>After joining the data we should do a quick sanity check to make sure that we have all 505 SP500 tickers</p><pre>tickers_df %&gt;% <br># select just the symbol column<br>select(symbol)%&gt;% <br># get the distinct values<br>distinct()%&gt;% <br># count the distinct values <br>count() %&gt;% <br># we can use select to rename columns <br>select(&quot;Total Number of Tickers&quot; = n)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*zEuOR28-CKUdPB2muee4fA.png" /></figure><p>Finally, we can inspect the first few rows of the dataframe, to confirm we have gotten the data we want:</p><pre>tickers_df %&gt;% <br>  head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*wMaG5dh-jCOuInpBV-ijNg.png" /></figure><p>Perfect! Exactly what we expected.</p><p><strong>Wrapping up:</strong></p><p>In this first blog post we have:</p><ul><li>Learned about the basics of the tidyverse ecosystem and tidyquant</li><li>Learned about the basics of tidy iteration and functional programming</li><li>Learned how to leverage rvest and chrome to scrape data from wikipedia</li><li>Learned how to move from reading in a single asset to the whole SP500</li></ul><p><strong>In the </strong><a href="https://medium.com/@Psr1/exploring-the-sp500-with-r-part-2-asset-analysis-657d3c1caf60"><strong>next post</strong></a><strong>:</strong></p><p>I will answer my original question:</p><p><strong>Which SP500 assets had the highest average return over the last 3 months?</strong></p><p>A few things to note:</p><ul><li>You can obtain a list of all SP500 stocks much more easily with tq_index(“SP500&quot;). This function does require the XLConnect library. I currently am having issues getting that library to import and run on my local machine.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*kkScs3UM5wBWw6XvdQHo6g.png" /></figure><ul><li>tq_get() actually accepts lists of tickers, so using map() isn’t necessary</li><li>I intentionally wrote the code this way, to demonstrate the described concepts</li></ul><p>Disclaimer: In college, I did a project with SP500 data and python. It is against class policy to share this project. While what I am doing here is somewhat similar, I am using a completely different programming language and answering a completely different question. Given my previous statement, I assert that this is not a violation of that courses policy. I intentionally used the R programming language as opposed to python to completely avoid any issues and to respect my former professors wishes.</p><p><a href="https://github.com/pysr1/medium_sp500">The Code can be found here</a></p><p>This is another great source on scraping that helped a bit when writing the article.</p><p><a href="https://medium.com/@kyleake/wikipedia-data-scraping-with-r-rvest-in-action-3c419db9af2d">https://medium.com/@kyleake/wikipedia-data-scraping-with-r-rvest-in-action-3c419db9af2dhttps://medium.com/@kyleake/wikipedia-data-scraping-with-r-rvest-in-action-3c419db9af2d</a></p><p><strong><em>Note from Towards Data Science’s editors:</em></strong><em> While we allow independent authors to publish articles in accordance with our </em><a href="https://towardsdatascience.com/questions-96667b06af5"><em>rules and guidelines</em></a><em>, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our </em><a href="https://towardsdatascience.com/readers-terms-b5d780a700a4"><em>Reader Terms</em></a><em> for details.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56c9498f38e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exploring-the-sp500-with-r-part-1-scraping-data-acquisition-and-functional-programming-56c9498f38e8">Exploring The SP500 With R Part 1: Scraping, Data Acquisition and Functional Programming</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Docker and Pyspark]]></title>
            <link>https://levelup.gitconnected.com/using-docker-and-pyspark-134cd4cab867?source=rss-93a17102968d------2</link>
            <guid isPermaLink="false">https://medium.com/p/134cd4cab867</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sparql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Bryant Crocker]]></dc:creator>
            <pubDate>Thu, 10 Jan 2019 04:06:26 GMT</pubDate>
            <atom:updated>2019-05-02T17:06:41.985Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Docker and PySpark</h3><p>Recently, I have been playing with PySpark a bit and decided I would write a blog post about using PySpark and Spark SQL. Spark is a great open source tool for munging data and machine learning across distributed computing clusters. PySpark is the python API to Spark.</p><p>PySpark can be a bit difficult to get up and running on your machine. Docker is a quick and easy way to get a Spark environment working on your local machine and is how I run PySpark on my local machine.</p><h3>What is Docker?</h3><p>I’ll start by giving an introduction to Docker. According to <a href="https://en.wikipedia.org/wiki/Docker_(software)">wikipedia</a> “Docker is a <a href="https://en.wikipedia.org/wiki/Computer_program">computer program</a> that performs <a href="https://en.wikipedia.org/wiki/Operating-system-level_virtualization">operating-system-level virtualization</a>, also known as ‘containerization’ ”. To greatly simplify, Docker creates a walled off linux operating system to run software on top of your machine’s OS called a container. For those familiar with virtual machines, a container is basically a vm without a hypervisor. These containers can be preconfigured with scripts to install specific software and provide customized functionality. Dockerhub is a website that contains various preconfigured docker containers that can be quickly run on your computer. One of these is the <a href="https://hub.docker.com/r/jupyter/pyspark-notebook">jupyter/pysparknotebook.</a> This is the docker image we will be using today.</p><h3>Starting up the Docker container:</h3><p>Setting up a Docker container on your local machine is pretty simple. Simply download docker from the <a href="https://www.docker.com/get-started">docker website</a> and run the following command in the terminal:</p><pre>docker run -it -p 8888:8888 jupyter/pyspark-notebook</pre><p>navigate to <a href="http://localhost:8888/">http://localhost:8888</a> in your browser and you will see the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*fv0U7mbZu8JJdRYbaYcd5Q.png" /></figure><p>In your terminal you should see a token:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*ayYvL0yfVks5aiSSGsqxig.png" /></figure><p>copy and paste this token, the numbers following “/?token=”, into the token textbook and set a password for the Jupyter notebook server in the New Password box.</p><p>With that done, you are all set to go! Spark is already installed in the container. You are all ready to open up a notebook and start writing some Spark code. I will include a copy of the notebook but I would recommend entering the code from this article into a new Jupyter notebook on your local computer. This helps you to learn.</p><p>To stop the docker container and Jupyter notebook server, simply enter control + c in the terminal that is running it.</p><h3>PySpark Basics</h3><p>Spark is an open source cluster computing framework written in mostly scala with APIs in R, python, scala and java. It is made mostly for large scale data analysis and machine learning that cannot fit into local memory. In this brief tutorial, I will not use a dataset that is too big to fit into memory. This tutorial borrows from the official getting starting guide: <a href="https://spark.apache.org/docs/latest/sql-getting-started.html">https://spark.apache.org/docs/latest/sql-getting-started.html</a>.</p><h3>Spark Datatypes:</h3><p>There are two main datatypes in the spark ecosystem, Resilient Distributed Datasets or RDDs (which are kind of like a cross between a python list and dictionary) and dataframes (dataframes much like in R and python). Both data types in spark are partitioned and immutable (which means you cannot change the object, a new one is returned instead). In this tutorial I am going to focus on the dataframe datatype.</p><h3>The Dataset:</h3><p>The dataset that I will be using is a somewhat large Vermont vendor data dataset from the <a href="https://data.vermont.gov/Finance/Vermont-Vendor-Payments/786x-sbp3">Vermont open data Socrata portal.</a> It can be downloaded easily by following the link.</p><h3>Setting up a Spark session:</h3><p>This code snippet starts up the PySpark enviroment in the docker container and imports basic libraries for numerical computing.</p><pre># import necessary libraries<br>import pandas as pd <br>import numpy<br>import matplotlib.pyplot as plt <br>from pyspark.sql import SparkSession</pre><pre># create sparksession<br>spark = SparkSession \<br>    .builder \<br>    .appName(&quot;Pysparkexample&quot;) \<br>    .config(&quot;spark.some.config.option&quot;, &quot;some-value&quot;) \<br>    .getOrCreate()</pre><h3>Reading in a CSV:</h3><p>I wanted to start by comparing reading in a CSV with pandas vs Spark. Spark ends up reading in the CSV much faster than pandas. This demonstrates how Spark dataframes are much faster when compared to their pandas equivalent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f852lSq0MwP8H807jcjb8Q.png" /></figure><p>For this analysis I will read in the data using the inferSchema option and cast the Amount column to a double.</p><pre>df = spark.read.csv(&#39;Vermont_Vendor_Payments (1).csv&#39;, header=&#39;true&#39;, inferSchema = True)<br>df = df.withColumn(&quot;Amount&quot;, df[&quot;Amount&quot;].cast(&quot;double&quot;))</pre><h3>Basic Spark Methods:</h3><p>like with pandas, we access column names with the .columns attribute of the dataframe.</p><pre>#we can use the columns attribute just like with pandas<br>columns = df.columns<br>print(&#39;The column Names are:&#39;)<br>for i in columns:<br>    print(i)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*rz7O_aDOnCfzfJz8U225KA.png" /></figure><p>We can get the number of rows using the .count() method and we can get the number of columns by taking the length of the column names.</p><pre>print(&#39;The total number of rows is:&#39;, df.count(), &#39;\nThe total number of columns is:&#39;, len(df.columns))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*ihyAjdmnLf5u5mMeLTBP1w.png" /></figure><p>The .show() method prints the first 20 rows of the dataframe by default. I chose to only print 5 in this article.</p><pre>#show first 5 rows<br>df.show(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*MiQcU9mJKWFn6xghso1dyQ.png" /></figure><p>The .head() method can also be used to display the first row. This prints much nicer in the notebook.</p><pre>#show first row<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*7zaa9WXBCBoBmjQ9c0vORw.png" /></figure><p>Like in pandas, we can call the describe method to get basic numerical summaries of the data. We need to use the show method to print it to the notebook.This does not print very nicely in the notebook.</p><pre>df.describe().show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*cvY2Ky7sVGT1RKbKZ_qiLg.png" /></figure><h3>Querying the data:</h3><p>One of the strengths of Spark is that it can be queried with each language’s respective Spark library or with Spark SQL. I will demonstrate a few queries using both the pythonic and SQL options.</p><p>The following code registers temporary table and selects a few columns using SQL syntax:</p><pre># I will start by creating a temporary table query with SQL<br>df.createOrReplaceTempView(&#39;VermontVendor&#39;)<br>spark.sql(<br>&#39;&#39;&#39;<br>SELECT `Quarter Ending`, Department, Amount, State FROM VermontVendor<br>LIMIT 10<br>&#39;&#39;&#39;<br>).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*YunX8UY--fyEmpY_Ca9log.png" /></figure><p>This code performs pretty much the same operation using pythonic syntax:</p><pre>df.select(&#39;Quarter Ending&#39;, &#39;Department&#39;, &#39;Amount&#39;, &#39;State&#39;).show(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*hUp3IXbOuCWIUjv76nUVJA.png" /></figure><p>One thing to note is that the pythonic solution is significantly less code. I like SQL and it’s syntax, so I prefer the SQL interface over the pythonic one.</p><p>I can filter the columns selected in my query using the SQL WHERE clause</p><pre>spark.sql(<br>&#39;&#39;&#39;</pre><pre>SELECT `Quarter Ending`, Department, Amount, State FROM VermontVendor <br>WHERE Department = &#39;Education&#39;<br>LIMIT 10</pre><pre>&#39;&#39;&#39;<br>).show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*MGNwBRaREWdDu76NCggBFw.png" /></figure><p>A similar result can be achieved with the .filter() method in the python API.</p><pre>df.select(&#39;Quarter Ending&#39;, &#39;Department&#39;, &#39;Amount&#39;, &#39;State&#39;).filter(df[&#39;Department&#39;] == &#39;Education&#39;).show(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*txBQB_82zGyR5yEIabzEWQ.png" /></figure><h3>Plotting</h3><p>Unfortunately, one cannot directly create plots with a Spark dataframe. The simplest solution is to simply use the .toPandas() method to convert the result of Spark computations to a pandas dataframe. I give a couple examples below.</p><pre>plot_df = spark.sql(<br>&#39;&#39;&#39;</pre><pre>SELECT Department, SUM(Amount) as Total FROM VermontVendor <br>GROUP BY Department<br>ORDER BY Total DESC<br>LIMIT 10</pre><pre>&#39;&#39;&#39;<br>).toPandas()</pre><pre><br>fig,ax = plt.subplots(1,1,figsize=(10,6))<br>plot_df.plot(x = &#39;Department&#39;, y = &#39;Total&#39;, kind = &#39;barh&#39;, color = &#39;C0&#39;, ax = ax, legend = False)<br>ax.set_xlabel(&#39;Department&#39;, size = 16)<br>ax.set_ylabel(&#39;Total&#39;, size = 16)<br>plt.savefig(&#39;barplot.png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*wf9dVFkqBDKL7kb1J8SLWQ.png" /></figure><pre>import numpy as np<br>import seaborn as sns<br>plot_df2 = spark.sql(<br>&#39;&#39;&#39;<br>SELECT Department, SUM(Amount) as Total FROM VermontVendor <br>GROUP BY Department<br>&#39;&#39;&#39;<br>).toPandas()<br>plt.figure(figsize = (10,6))<br>sns.distplot(np.log(plot_df2[&#39;Total&#39;]))<br>plt.title(&#39;Histogram of Log Totals for all Departments in Dataset&#39;, size = 16)<br>plt.ylabel(&#39;Density&#39;, size = 16)<br>plt.xlabel(&#39;Log Total&#39;, size = 16)<br>plt.savefig(&#39;distplot.png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bonNNl75ZJG5djc_eadtzA.png" /></figure><h3>Starting up you docker container again:</h3><p>Once you have started and exited out of your docker container the first time, you will start it differently for future uses since the container has already been run.</p><p>Pass the following command to return all container names:</p><pre>docker ps -a</pre><p>Get the container id from the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*Ao0Sr1PEIGoNf73INYlO3w.png" /></figure><p>Then run docker start with the container id to start the container:</p><pre>docker start 903f152e92c5</pre><p>Your Jupyter notebook server will then again be running on <a href="http://localhost:8888/">http://localhost:8888</a>.</p><p>The full code with a few more examples can be found on my github:</p><p><a href="https://github.com/crocker456/PlayingWithPyspark">https://github.com/crocker456/PlayingWithPyspark</a></p><h3>Sources:</h3><ul><li><a href="https://stackoverflow.com/questions/39652767/pyspark-2-0-the-size-or-shape-of-a-dataframe">PySpark 2.0 The size or shape of a DataFrame</a></li><li><a href="https://spark.apache.org/docs/latest/sql-getting-started.html">Getting Started</a></li></ul><figure><a href="https://levelup.gitconnected.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaoZbi7tTKJ5vL7i2OAYMQ.png" /></a></figure><p><a href="https://gitconnected.com/learn/python">Learn Python - Best Python Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=134cd4cab867" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/using-docker-and-pyspark-134cd4cab867">Using Docker and Pyspark</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visual Parameter Tuning with Facebook Prophet and Python]]></title>
            <link>https://medium.com/@Psr1/visual-parameter-tuning-with-facebook-prophet-and-python-8f50719c7318?source=rss-93a17102968d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f50719c7318</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Bryant Crocker]]></dc:creator>
            <pubDate>Wed, 19 Dec 2018 21:09:34 GMT</pubDate>
            <atom:updated>2019-04-09T21:06:06.117Z</atom:updated>
            <content:encoded><![CDATA[<h4>Visualizing time series cross validation</h4><p>Facebook prophet is by far my favorite python package. It allows for quick and easy forecasting of many time series with a novel bayesian model. Prophet estimates various parameters using a general additive model. More on Facebook prophet can be found right <a href="https://facebook.github.io/prophet/docs/quick_start.html"><em>here</em></a><em>. </em>Forecasting is important in many business situations, particularly supply chain management and demand planning.</p><p>In their<a href="https://peerj.com/preprints/3190.pdf"> paper</a> about Facebook prophet, the package authors recommend using visual means to asses the quality of forecasts. This is essential because a scalar model metric often doesn’t tell us much about how the model performs over time. The package provides convenient plotting functions to see how prophet predictive performance changes over time. The authors suggest the use of shiny application to tune parameters. A while back I made a <a href="https://crocker456.shinyapps.io/Commiditiesapp2/#section-interactive-forecast-plot"><em>shiny app </em></a>that allows the user to visually assess prophet models on commodity data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zU3Cp9z9gwy8GjygMXJ7Cw.png" /></figure><h3>Now, the python part!</h3><p>The focus of this article will be another way to achieve the same thing using simple python code. I Personally have not been able to find any examples of visual parameter tuning with prophet, so I decided to write some quick code to do that.</p><p>I start by simply importing essential libraries and pulling historical Russel 2000 data from Yahoo. The Russel 2000 has been very rocky the past few months, it would certainly be interesting to forecast where it’s going.</p><pre>#Import Necessary Libaries<br>import pandas as pd <br>import numpy as np <br>import matplotlib.pyplot as plt <br>import seaborn as sns <br>import pandas as pd<br>import quandl<br>from fbprophet import Prophet<br>from fbprophet.plot import plot_cross_validation_metric <br>from fbprophet.diagnostics import performance_metrics<br>from fbprophet.diagnostics import cross_validation<br>#this is needed for ffn to import<br>pd.core.common.is_list_like = pd.api.types.is_list_like<br>import ffn<br>import fix_yahoo_finance as yf<br>#this makes fix yahoo finance work<br>yf.pdr_override()</pre><pre>#grab the Russel 2000 data and select adj close<br>mydata = yf.download(&#39;^RUT&#39;, start=&quot;2012-01-01&quot;)<br>RUT = mydata[[&#39;Adj Close&#39;]]<br>%matplotlib inline <br>plt.style.use(&#39;seaborn&#39;)</pre><p>The next step is first do a quick exploratory plot to make sure the data is what we think it is. This is always a necessary step in data analysis.</p><pre>fix, ax = plt.subplots(1,1,figsize = (14,8))<br>RUT.plot(ax = ax)<br>ax.set_title(&#39;Russel 2000 Adjusted Closing Price&#39;)<br>ax.set_ylabel(&#39;Closing Price&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*3bEuk2SQyx5w8tEwrIulNg.png" /></figure><p>It looks like things are as I expected, a quick Google search could be used to confirm this is what we expect the prices to look like. The next step will be fitting prophet models and visualizing changes to the parameters.</p><p>In this example I will tune the change_point_prior parameter for the model. Parameter tuning is an important step for any machine learning model. During parameter tuning different values of a parameter are tried and the value that optimizes predictive accuracy is chosen. In this example the mean absolute percentage error is used to evaluate models. This is the metric suggested by the authors.</p><p>In order to evaluate the model I use time series cross validation. Time series cross validation is different than regular k-fold cross validation that is typically used with machine learning models. With Facebook Prophet’s time series cross validation you select historical cutoff points and fit the model using data up to that cutoff point. More information about this procedure can be found <a href="https://facebook.github.io/prophet/docs/diagnostics.html"><em>here</em></a>.</p><p>Time series cross validation is easy with Facebook prophet and is included with the package.</p><pre>fig, ax = plt.subplots(10,1, figsize = (14, 20))<br>ax = ax.ravel()<br>j = 0<br>for i in [0.01, 0.05, 0.10, 0.15, 0.20]:<br>    RUT2 = RUT.reset_index()<br>    RUT2 = RUT2.rename(columns = {&#39;Date&#39; : &#39;ds&#39;, &#39;Adj Close&#39; : &#39;y&#39;} )<br>    m = Prophet(changepoint_prior_scale=i)<br>    #fit the prophet model on the data<br>    m.fit(RUT2)<br>    # make a dataframe of the next two years <br>    future = m.make_future_dataframe(periods=365)<br>    #predict on this future dataframe<br>    forecast = m.predict(future)<br>    # plot the forecast <br>    fig = m.plot(forecast, ax = ax[j])<br>    ax[j].set_title(&#39;changepoint prior = &#39; + str(i))<br>    j += 1<br>    df_cv = cross_validation(m, initial=&#39;365 days&#39;, period=&#39;180 days&#39;, horizon = &#39;365 days&#39;)<br>    df_p = performance_metrics(df_cv)<br>    fig = plot_cross_validation_metric(df_cv, metric=&#39;mape&#39;, ax = ax[j])<br>    ax[j].set_title(str(str(i) + &#39; Change Point Prior Mean Absolute Percentage Error&#39;))<br>    ax[j].set_ylim(0,0.5)<br>    j += 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*OTcVtFUWGh8cImvbGqMXCw.png" /></figure><p>It’s easy to see visually that varying the change_point_prior doesn’t make a big effect on the accuracy of the model. It appears that the default value of 0.05 is the best choice. This tends to occur when tuning prophet models in my experience. Often I don’t tune them at all because of this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f50719c7318" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>