<?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 Andrej on Medium]]></title>
        <description><![CDATA[Stories by Andrej on Medium]]></description>
        <link>https://medium.com/@dr0ff?source=rss-48f7c52915e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sD5Y1yRA6dexSHLf2xWpEQ.jpeg</url>
            <title>Stories by Andrej on Medium</title>
            <link>https://medium.com/@dr0ff?source=rss-48f7c52915e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 13:13:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dr0ff/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 physical activity trackers data with Apache Spark and Spark Notebook.]]></title>
            <link>https://medium.com/@dr0ff/analyzing-physical-activity-tracker-data-with-apache-spark-and-spark-notebook-b1500c255ce3?source=rss-48f7c52915e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1500c255ce3</guid>
            <category><![CDATA[spark-notebook]]></category>
            <category><![CDATA[wearables]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Andrej]]></dc:creator>
            <pubDate>Mon, 18 Sep 2017 21:37:30 GMT</pubDate>
            <atom:updated>2017-09-19T05:12:32.143Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analyzing physical activity trackers data with Apache Spark and Spark Notebook. Part I. Transition matrix</h3><p>The inspiration and ideas for this article were taken from <a href="https://www.youtube.com/watch?v=9DoBLwvvZDA">Timofey Pyrkov’s talk</a> on Yandex Data Science conference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*C_IxH5YjGlGfu7slIxjWyw.png" /></figure><p>This article is based on materials of my <a href="https://github.com/drewnoff/spark-notebooks-gallery/tree/master/gallery/physical-activity-monitor">spark notebooks gallery repository</a>. All computations were performed using<strong> Apache Spark</strong> and <a href="http://github.com/spark-notebook/spark-notebook/"><strong>Spark Notebook</strong></a> technologies. To get some instructions on how to get started with Spark Notebook one might refer to “requirements” section of my previous <a href="https://medium.com/@dr0ff/analyzing-time-series-cryptocurrencies-data-using-apache-spark-flint-and-spark-notebook-ba770d6c25e4">article</a>.</p><p>In nowdays it’s quite easy to collect locomotor activity data using portable physical activity monitors (wearable devices, smarphones). And it’s quite interesting to find a way to process this data in such a way that it could tell us something about our mortality risks and wellness score.</p><h3>NHANES dataset</h3><p>There is publicly available dataset called NHANES which contains locomotor activity tracks along with various demographic data for thousands of respondents. To get instruction on how to obtain codebooks and load this dataset refer to NHANES_data <a href="https://github.com/drewnoff/spark-notebooks-gallery/blob/master/gallery/physical-activity-monitor/NHANES_data.md">spark notebook</a> in the same repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2c7d87f9c346bd08b995dbc0d165bc0/href">https://medium.com/media/f2c7d87f9c346bd08b995dbc0d165bc0/href</a></iframe><h3>Physical activity monitor data</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d66e228208edc874836117a6b9ddd646/href">https://medium.com/media/d66e228208edc874836117a6b9ddd646/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d780eeaf3dc6479230d06b1e5bed266/href">https://medium.com/media/1d780eeaf3dc6479230d06b1e5bed266/href</a></iframe><h4>Demographics data</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3455e9c491680707a3eda4f9b1a09b5/href">https://medium.com/media/f3455e9c491680707a3eda4f9b1a09b5/href</a></iframe><h3>Cleaning physical activity monitor data</h3><p>The physical activity monitors (PAMs) used in NHANES were programmed to detect and record the magnitude of acceleration or “intensity” of movement. Intensity readings were summed over each 1-minute epoch.</p><p>The dataset has some abnormally high “intensity” values stored by several devices. We can plot intensity value distribution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08b1d7e5fce144f02eb11fa63041282d/href">https://medium.com/media/08b1d7e5fce144f02eb11fa63041282d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*edtUwpfmBpUEqQNU.png" /></figure><p>Count the number of devices which recorded abnormally high intensity values</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a5c99a17184efb1a083765cd49a6df4/href">https://medium.com/media/4a5c99a17184efb1a083765cd49a6df4/href</a></iframe><p>Let’s remove those devices from the dataset.</p><p>We will create a broadcasted variable containing a set of Respondent sequence numbers (SEQN) with abnormally high intensity values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4eb06116a1af085c0870d327c24620b/href">https://medium.com/media/c4eb06116a1af085c0870d327c24620b/href</a></iframe><pre>Number of reliable devices: 14182<br>Number of unreliable devices: 449</pre><p>Now that we have respondent sequence numbers for somewhat reliable and unreliable data we can have a look at raw intensity values over the tracking period. We will make and add synthetic datetime column to be able order records more easily and make timeseries charts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*C1eLyuBc-no3Gn_V.png" /></figure><p>This is a locomotor activity data. What can we do with this data? What can it tell us about human health or age? It’s hard to directly compare different locomotor activity tracks because much of individual’s social activity habbits are mixed into this data. But we’re interested to extract physiological information from noisy locomotor activity. For that we need to perform feature engineering.</p><h3>Transition Matrix</h3><p>One way to describe locomotor activity track is to apply the model of <a href="https://en.wikipedia.org/wiki/Markov_chain">Markov process</a> to it which is described by probabilities of transitions from one state to another. We can define such probabilities in a form of <a href="https://en.wikipedia.org/wiki/Stochastic_matrix">transition matrix</a>.</p><p>First, we need to define finite state space of such a locomotor activity process, let’s say something like: low, medium, high, very high level of activity.</p><p>After that we need to go through a physical activity intensity track of an individual person and count probabilities of transitions from one level of activity to another for given person. As a result we’ll get a locomotor activity transition matrix for a single person which can be treated as a locomotor findgerprint of a person.</p><h3>Spark ML Bucketizer</h3><p>To define finite state space of locomotor activities we can use <a href="https://spark.apache.org/docs/latest/ml-features.html#bucketizer">Bucketizer</a> transformer from Spark ML library.</p><p>We can look at intencity value distribution recorded from reliable trackers to define desired intensity levels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f60365cf73896b91ec45119b0d873ba0/href">https://medium.com/media/f60365cf73896b91ec45119b0d873ba0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*CkYdXuOca7z6EoK7.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/210f21bd4254e0d98084044f7a979d70/href">https://medium.com/media/210f21bd4254e0d98084044f7a979d70/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e5aaaf1c2d4ef5dcb41dd2671191e5/href">https://medium.com/media/93e5aaaf1c2d4ef5dcb41dd2671191e5/href</a></iframe><h3>Computing Transition Matrix with Spark SQL Window Functions</h3><p>To compute a transition matrix we need to collect previous minute activity of a given person for each minute of activity for the same person.</p><p>That’s where Spark SQL Funcitons come in handy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92b9bd55bcf22ffce5b112d11471bc6a/href">https://medium.com/media/92b9bd55bcf22ffce5b112d11471bc6a/href</a></iframe><p>Here we specified a window to contain all records from one Respondent (partitioned by SEQN) and ordered by time.</p><p>And we’re using lag window funciton to access previous record in specified window which in this case is a previous minute activity level of a given person.</p><p>Now that we have previous minute activity level we can start to build a transition matrix of desired size. We can store the transition matrix W in a form of Array[Array[Double]] where W(i)(j) has the value of probability of transition from state j to state i.</p><p>First we will store in W(i)(j) a number of transitions from level j to level i of a given person and after that we will devide this value by total number of transitions in recorded track for the person.</p><p>Let’s obtain total number of transitions from one sate to another.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/077e7933e6ec818eea3e4b94c15bdb37/href">https://medium.com/media/077e7933e6ec818eea3e4b94c15bdb37/href</a></iframe><p>For each record we created a matrix with single transition count: from previous minute acitivty level to current one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d450d5bad3de942184e8d34aa8527d7/href">https://medium.com/media/6d450d5bad3de942184e8d34aa8527d7/href</a></iframe><p>Finally we need to sum all single-transition matrices of a single respondent and divide the result matrix by total number of transition of the respondent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb0c76efe2515a7dd5d345d628cbca6d/href">https://medium.com/media/eb0c76efe2515a7dd5d345d628cbca6d/href</a></iframe><p>It’s a good idea to persist computed transition matrices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c070886fb6c3cd352d8397bf82f6f12/href">https://medium.com/media/6c070886fb6c3cd352d8397bf82f6f12/href</a></iframe><p>We also obtained respondent cumulative intensity value. Let’s take a look at its distribution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e4a0d63629f1a550ed7639c2c9a93e/href">https://medium.com/media/97e4a0d63629f1a550ed7639c2c9a93e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*5YCAL4gvdXKpVBUh.png" /></figure><p>There is a peak in distribution at very low cumulative intensity value. Low cumulative intensity value might be obtained when the physical activity monitor has not been used. We can filter out these measurements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79611d62607bb16a0ccb3f207c10ec68/href">https://medium.com/media/79611d62607bb16a0ccb3f207c10ec68/href</a></iframe><p>Now we can visualise transition matrices for different respondents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6bb1bbda8fa01eea35f52be77143c831/href">https://medium.com/media/6bb1bbda8fa01eea35f52be77143c831/href</a></iframe><pre>plotTrMatrix(sampleTrMatrices(0))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*ckidJHreBbC3c9L1.png" /></figure><pre>plotTrMatrix(sampleTrMatrices(4))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*oNtay5fhyiI2i_ec.png" /></figure><pre>plotTrMatrix(sampleTrMatrices(5))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*W-qFpNgFjO37xp8Y.png" /></figure><p>A transitoin matrix looks like a locomotor fingerprint and we already can say something about a person’s activity patterns from looking into her locomotor transition matrix.</p><h3>Aging</h3><p>We collected and cleaned a lot of data recorded by physical activity monitors and extracted quite interesting feature from raw data.</p><p>Interesting to see how does physiological changes encoded in transition matrix relates to the aging process.</p><p>For that we’ll use Principal component analysis (<a href="https://spark.apache.org/docs/latest/ml-features.html#pca">PCA</a>). We’ll project high dimentional feature space which is in our case is 10x10=100 (the number of elements in the matrix) of possibly correlated variables into lower dimentional space of linearly uncorrelated variables called principal components.</p><p>We’ll use <a href="https://spark.apache.org/docs/latest/ml-features.html#pca">PCA</a> feature transformaer from Spark ML library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77be6592ad07cc4eb73f217290029f7b/href">https://medium.com/media/77be6592ad07cc4eb73f217290029f7b/href</a></iframe><p>Here we flatten the matrix into single feature Vector and apply log transformation to the feature vector. Also we join age data from demographics dataset. And let&#39;s consider only respondents older than 35 years (since we&#39;re interested in the aging process).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2635961b5454c242b0917b29d9d3d20/href">https://medium.com/media/f2635961b5454c242b0917b29d9d3d20/href</a></iframe><p>Let’s extract each principal component as an individual feature and compute mean value and standard deviation of each principal component for given age.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/041422e53f7d45c0da9f19d8cc61ed1b/href">https://medium.com/media/041422e53f7d45c0da9f19d8cc61ed1b/href</a></iframe><pre>plotPrincipalComponentVsAge(1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*5OfK_DrLFcZf5uyp.png" /></figure><pre>plotPrincipalComponentVsAge(2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*BAcmYmbUpXVOLSgy.png" /></figure><pre>plotPrincipalComponentVsAge(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*nMGv1-caiscbWFIT.png" /></figure><p>PCA analysis finds the largest variance associated with age. That means that PC1 of locomotor transition matrix contains information about biological age.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/956a9f977dfcbfe1debc0a799423aa1c/href">https://medium.com/media/956a9f977dfcbfe1debc0a799423aa1c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IsI0LPA6Eybbu80G.png" /></figure><p>We’ve obtained pretty strong feature and there are plenty of things we can do with this. For example, we can use it for mortality risks prediction based on locomotor activity.</p><p>Let’s try to conduct this analysis in the next part of this lab.</p><pre>By Andrey Romanov<br>Software engineer, ML pipelines builder, GPU burner<br><a href="https://github.com/drewnoff">GitHub</a>, <a href="https://twitter.com/izhmyh">Twitter</a>, <a href="https://www.linkedin.com/in/andrey-romanoff/">LinkedIn</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1500c255ce3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing time series cryptocurrencies data using Apache Spark, Flint and Spark Notebook]]></title>
            <link>https://medium.com/@dr0ff/analyzing-time-series-cryptocurrencies-data-using-apache-spark-flint-and-spark-notebook-ba770d6c25e4?source=rss-48f7c52915e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba770d6c25e4</guid>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[flint]]></category>
            <category><![CDATA[spark-notebook]]></category>
            <dc:creator><![CDATA[Andrej]]></dc:creator>
            <pubDate>Mon, 24 Jul 2017 06:29:20 GMT</pubDate>
            <atom:updated>2017-09-18T21:40:20.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*F03MeASCQdbdIx-l-uKVfA.png" /></figure><p>This article is based on my <a href="https://github.com/drewnoff/spark-notebooks-gallery/tree/master/gallery/cryptocurrency-ts">spark notebook</a> and highly inspired by <a href="https://blog.timescale.com/@sarahpan">@sarahpan</a> great <a href="https://blog.timescale.com/analyzing-ethereum-bitcoin-and-1200-cryptocurrencies-using-postgresql-3958b3662e51">article</a> on analysis of cryptocurrencies data using PostgreSQL. The main goal of this article is not to provide you with Ethereum, Bitcoin and other cryptocurrencies insights (for this one please refer to @sarahpan’s article) but to get you familiar with tools which Apache Spark ecosystem can provide you to perform similar kind of analysis.</p><p>In this notebook we perform time series data analysis using <strong>Apache Spark</strong>, a time series library for Apache Spark called <a href="https://github.com/twosigma/flint"><strong>Flint</strong></a> and interactive computations and visualization capabilities of <a href="http://github.com/spark-notebook/spark-notebook/"><strong>Spark Notebook</strong></a>.</p><h3>Data</h3><p><a href="https://timescaledata.blob.core.windows.net/datasets/crypto_data.tar.gz">Direct link</a> to download the dataset. Also <a href="https://blog.timescale.com/analyzing-ethereum-bitcoin-and-1200-cryptocurrencies-using-postgresql-downloading-the-dataset-a1bbc2d4d992">here</a> one can find detailed description for the dataset.</p><p>We are interested in two files:</p><ul><li>btc_prices.csv — A CSV file with the daily BTC price data (OHLCV format), spanning seven years from 2010 to 2017 across multiple currencies (e.g. USD, CAD, EUR, CNY, etc.)</li><li>crypto_prices.csv — A CSV file with the daily cryptocurrency price data (OHLCV format) for over 1200 cryptocurrencies since 2013</li></ul><p>This is a small dataset and Spark lanched on laptop in local mode should be enough to work with it.</p><h3>Requirements</h3><p>spark 2.0 or higher, 2.11.7 or higher.</p><p>Spark Notebook. Get it via</p><pre>(for Spark 2.X.X)</pre><pre>$ unzip spark-notebook.zip</pre><pre>$ cd spark-notebook-0.7.0-scala-2.11.8-spark-2.0.2-hadoop-2.7.2-with-hive/</pre><pre>$ ./bin/spark-notebook</pre><pre>http://localhost:9001</pre><p>or from the <a href="https://github.com/spark-notebook/spark-notebook/">source code</a>:</p><pre>sbt -Dspark.version=2.1.1 -Dhadoop.version=2.7.0 -Dscala.version=2.11.8</pre><pre>[spark-notebook] $ start</pre><p>Navigate to `<a href="https://github.com/drewnoff/spark-notebooks-gallery/blob/master/gallery/cryptocurrency-ts/cryptocurrency_ts.snb">cryptocurrency_ts.snb</a>` from Spark Notebook browser window and click to launch it.</p><p>We also need to provide custom dependencies on <a href="https://github.com/twosigma/flint">Flint</a> library. It&#39;s not published on maven central repository but you can simply build it from the source and publish locally by running</p><pre>sbt publishLocal</pre><p>After that provide coordinates for dependencies in customDeps section of Notebook metadata (Edit -&gt; Edit Notebook Metadata):</p><pre>&quot;customDeps&quot;: [    &quot;com.twosigma % flint_2.11 % 0.2.0-SNAPSHOT&quot;  ]</pre><h3>Reading the data</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db15d8cd7ba34533206e7e13a8557e49/href">https://medium.com/media/db15d8cd7ba34533206e7e13a8557e49/href</a></iframe><p>Apache Spark supports direct read from csv files and can try to automatically infer schema. But we also can provide our own schema while reading csv data. This will prevent from full scan of csv file to infer schema and it&#39;s also more accurate if we know what we&#39;re doing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee255f5b76f7b6869a09706a9dbde33f/href">https://medium.com/media/ee255f5b76f7b6869a09706a9dbde33f/href</a></iframe><pre>btcPricesDF.show(5)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed85c615764aa2fe421cfe7615f178eb/href">https://medium.com/media/ed85c615764aa2fe421cfe7615f178eb/href</a></iframe><pre>cryptoPricesDF.show(5)</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc2aa6cdb5fa4f2e11c8a6804851b978/href">https://medium.com/media/fc2aa6cdb5fa4f2e11c8a6804851b978/href</a></iframe><h4>OHLC charts</h4><p>Since the data is presented in OHLCV format the natural way to plot them would be using OHLC charts. Spark Notebook comes with build in support (CustomPlotlyChart) for <a href="https://plot.ly/javascript/">Plotly javascript API</a> for data visualizations. To get some examples on usage of CustomPlotlyChart refer to notebooks from notebooks/viz directory which comes with Spark Notebook distribution or explore online with <a href="https://viewer.kensu.io/notebooks/viz/00_Data%20Visualisation%20With%20Plotly.snb">nbviewer</a>.</p><p>Resulting Plotly charts are interactive so fill free to zoom and hover over data directly from the Notebook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41f6ebb0e634ab3e6881a0235a4a6fbe/href">https://medium.com/media/41f6ebb0e634ab3e6881a0235a4a6fbe/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F42.embed%3Fautosize%3Dtrue&amp;url=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F42%2F&amp;image=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F42.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/27bccd8aadb68fd13e6c686289223566/href">https://medium.com/media/27bccd8aadb68fd13e6c686289223566/href</a></iframe><h3>TimeSeriesRDD</h3><p>Now let’s start with some time series analysis. From Flint getting started guide you can find that the entry point into all functionalities for time series analysis in Flint is the TimeSeriesRDD class or object. And we can create one from an existing DataFrame, for that we have to make sure the DataFrame contains a column named &quot;time&quot; of type LongType. And that&#39;s why we performed that extra .withColumn(&quot;time&quot;, unix_timestamp($&quot;datetime&quot;, &quot;yyyy-MM-dd HH:mm:ssX&quot;)) steps to create btcPricesDF and cryptoPricesDF dataframes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e3d63a45a8227ae4139b7c45cd778f0/href">https://medium.com/media/0e3d63a45a8227ae4139b7c45cd778f0/href</a></iframe><p>After creating our TimeSeriesRDD we can perform various transformations on it. If we want to perform some grouping or aggregation on our time series data then there are several options provided by Flint for that depending on your needs. Let&#39;s say we want to split our data into 14 day time buckets and obtain some summary information per each bucket.</p><h4>Generating clockTS RDD for time buckets</h4><p>Time buckets could be defined by another TimeSeriesRDD. Its timestamps will be used to defined intervals, i.e. two sequential timestamps define an interval.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9cf1ef14445b0f179a609f6e50e39b2/href">https://medium.com/media/e9cf1ef14445b0f179a609f6e50e39b2/href</a></iframe><p>Now that we defined time intervals we’re able to apply available summarizers for each interval.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0594eba20d506ac7ccfd10b11b98b106/href">https://medium.com/media/0594eba20d506ac7ccfd10b11b98b106/href</a></iframe><p>So we obtained mean closing price in USD per each 14 day interval.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab446253bafcddeb34008fcab31ed5d2/href">https://medium.com/media/ab446253bafcddeb34008fcab31ed5d2/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F44.embed%3Fautosize%3Dtrue&amp;url=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F44%2F&amp;image=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F44.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b4cab3de05c516fafba7863f6212edc/href">https://medium.com/media/2b4cab3de05c516fafba7863f6212edc/href</a></iframe><h3>Spark SQL Window Functions</h3><p>Another useful thing in Apache Spark toolbox is <a href="https://databricks.com/blog/2015/07/15/introducing-window-functions-in-spark-sql.html">Spark SQL Window Functions</a>. So what it can be useful for? It provides the ability to perform calculations across set of rows like calculating a moving average, calculating a cumulative sum, or accessing the values of a row appearing before the current row.</p><p>Let’s take an example of calculating the day-by-day volatility of BTC where we want to calculate BTC daily return as a factor of the previous day’s rate.</p><p>For that we can use DataFrame API or use SQL expressions by registering temporary view of our dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/599e729bcffba8db571331201cfa6f87/href">https://medium.com/media/599e729bcffba8db571331201cfa6f87/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78d4f53c9b835ab892c91b942d69cd2b/href">https://medium.com/media/78d4f53c9b835ab892c91b942d69cd2b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F46.embed%3Fautosize%3Dtrue&amp;url=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F46%2F&amp;image=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F46.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b9d21cfab025745d4b7f225e58f3f5b/href">https://medium.com/media/2b9d21cfab025745d4b7f225e58f3f5b/href</a></iframe><h4>Volumes by currency</h4><p>Now let’s get back to TimeSeriesRDD and refresh our knowledge on time seriese data summarization with one more example. Let&#39;s say we want to track changes in volume of BTC in different fiat currencies in 14 day intervals. For that we can use already seen .summarizeIntervals method with additional key argument to group results by currency_code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c05d14d16594d07065d5e4e6964d4288/href">https://medium.com/media/c05d14d16594d07065d5e4e6964d4288/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f2ef6baf43821e4838d13e46f146294/href">https://medium.com/media/4f2ef6baf43821e4838d13e46f146294/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F48.embed%3Fautosize%3Dtrue&amp;url=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F48%2F&amp;image=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F48.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6988f2f4d58f185a946327729527ae09/href">https://medium.com/media/6988f2f4d58f185a946327729527ae09/href</a></iframe><p>and to take a closer look at CNY currency</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4d2f83b8f7428b9f1cf0af344242dae/href">https://medium.com/media/d4d2f83b8f7428b9f1cf0af344242dae/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F50.embed%3Fautosize%3Dtrue&amp;url=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F50%2F&amp;image=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F50.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/75d6b86dbd189a24de270bb56aa786cb/href">https://medium.com/media/75d6b86dbd189a24de270bb56aa786cb/href</a></iframe><h3>Temporal Join</h3><p>Now we want to obtain ETH prices in fiat currencies. But in crypto_prices table we have only BTC prices for all other crypto currencies while prices in fiat currencies we have only for BTC in btc_prices table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a81956cc8127e287de16981b24b7ced/href">https://medium.com/media/2a81956cc8127e287de16981b24b7ced/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bea7bebd3f846e9674f32badb0dd205/href">https://medium.com/media/7bea7bebd3f846e9674f32badb0dd205/href</a></iframe><p>And this is where JOIN comes in handy. But in case of time series data it would be a <a href="https://github.com/twosigma/flint#temporal-join-functions">Temporal Join</a>. And again Flint provide several options for that.</p><p>Temporal join functions define a matching criteria over time. It could be an exact match or it can look past or look future to find closest row from other table with timesatmp located within some tolerance interval.</p><p>So given BTC prices in fiat currencies for some timestamp in btc_prices table we want to find closest ETH prices in BTC within 1 day from crypto_prices table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa4ed825fe761e9b5968362250f769b1/href">https://medium.com/media/aa4ed825fe761e9b5968362250f769b1/href</a></iframe><p>we keep only those records for which matching criteria is met.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe343916ec045d2a1edc783e8d8af3e1/href">https://medium.com/media/fe343916ec045d2a1edc783e8d8af3e1/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F52.embed%3Fautosize%3Dtrue&amp;url=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F52%2F&amp;image=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F52.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/64e73811c41b839e682f6eff4309eed4/href">https://medium.com/media/64e73811c41b839e682f6eff4309eed4/href</a></iframe><p>Prices in different fiat currencies might be in different scales like for USD and CNY, so plotting them on the same chart with single yaxis might be not a good idea. For that one can plot them on the same chart but with <a href="https://plot.ly/javascript/multiple-axes/">multiple yaxes</a> or use <a href="https://plot.ly/javascript/subplots/">subplots</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce332d0ffd869f72e9d77e8f50368b49/href">https://medium.com/media/ce332d0ffd869f72e9d77e8f50368b49/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F54.embed%3Fautosize%3Dtrue&amp;url=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F54%2F&amp;image=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F54.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bd2b6ec8eff1a6ad012f3bcfeaed766/href">https://medium.com/media/4bd2b6ec8eff1a6ad012f3bcfeaed766/href</a></iframe><p>Another good example on using temporal joins would be calculating of total transaction volume in USD for top all crypto currencies in the dataset over the past week.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8abc39d70a55677d6dc2ba55759c2dc3/href">https://medium.com/media/8abc39d70a55677d6dc2ba55759c2dc3/href</a></iframe><p>An important thing to note here is that when performing a join temporal join function tries to find one closest row from right table. But in our case several rows from crypto_prices table corresponding to different currencies share the same timestamp and we want to join BTC prices for all of them. The solution is to group all rows sharing exactly the same timestamp in crypto_prices table using .groupByCycle function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34becb4480ae867128b8cffd6c17f508/href">https://medium.com/media/34becb4480ae867128b8cffd6c17f508/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cffddb4527d20b3df21acb8f41bf136b/href">https://medium.com/media/cffddb4527d20b3df21acb8f41bf136b/href</a></iframe><p>After this we can use explode function to create a new row for each element in rows array which contains all the rows from crypto_prices table sharing exactly the same timestamp.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/382e24d112102154594c76bb8f68d954/href">https://medium.com/media/382e24d112102154594c76bb8f68d954/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6744a7186c575203217f68b77e625e71/href">https://medium.com/media/6744a7186c575203217f68b77e625e71/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6368f97bbb7e5493a5082da468581eb/href">https://medium.com/media/a6368f97bbb7e5493a5082da468581eb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/796018d042b114b053b2b47501b818af/href">https://medium.com/media/796018d042b114b053b2b47501b818af/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5e22212664e27fce6e929b2ec72faa1/href">https://medium.com/media/b5e22212664e27fce6e929b2ec72faa1/href</a></iframe><p>Now we can perform required aggregation on both crypto_btc_usd_prices and btc_usd_prices tables and unite the the results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2e785c394928842ceab0a2eb8b4c5c0/href">https://medium.com/media/b2e785c394928842ceab0a2eb8b4c5c0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f43a327f9d3c2cbc2e639cafc618d34f/href">https://medium.com/media/f43a327f9d3c2cbc2e639cafc618d34f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eebc8d2593fca707401f99a05fc1be09/href">https://medium.com/media/eebc8d2593fca707401f99a05fc1be09/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8122218cc29e85f04118529f45a711aa/href">https://medium.com/media/8122218cc29e85f04118529f45a711aa/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F56.embed%3Fautosize%3Dtrue&amp;url=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F56%2F&amp;image=https%3A%2F%2Fplot.ly%2F%7Edrewnoff%2F56.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/51a7d43f9c305dbca475792a7a9cf722/href">https://medium.com/media/51a7d43f9c305dbca475792a7a9cf722/href</a></iframe><h3>Conclusion</h3><p>I hope this notebook has given you some ideas on how can you use these great tools like Apache Spark, Flint library, Spark Notebook and Plotly scientific graphing library for time series data analysis. Also given that Apache Spark is a fast and general engine for big data processing you can use all these tools on much larger datasets in cluster computing environment.</p><p><em>And again many thanks to </em><a href="https://blog.timescale.com/@sarahpan"><em>@sarahpan</em></a><em> for </em><a href="https://blog.timescale.com/analyzing-ethereum-bitcoin-and-1200-cryptocurrencies-using-postgresql-3958b3662e51"><em>sharing</em></a><em> her ideas on analysis of given dataset</em>.</p><pre>By Andrey Romanov<br>Software engineer, ML pipelines builder, GPU burner<br><a href="https://github.com/drewnoff">GitHub</a>, <a href="https://twitter.com/izhmyh">Twitter</a>, <a href="https://www.linkedin.com/in/andrey-romanoff/">LinkedIn</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba770d6c25e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>