<h1>Robust peak detection algorithm (using z-scores)</h1>
<p>I came up with an algorithm that works very well for these types of datasets. It is based on the principle of <a href="https://en.wikipedia.org/wiki/Statistical_dispersion" rel="noreferrer">dispersion</a>: if a new datapoint is a given x number of standard deviations away from some moving mean, the algorithm signals (also called <a href="https://en.wikipedia.org/wiki/Standard_score" rel="noreferrer">z-score</a>). The algorithm is very robust because it constructs a <em>separate</em> moving mean and deviation, such that signals do not corrupt the threshold. Future signals are therefore identified with approximately the same accuracy, regardless of the amount of previous signals. The algorithm takes 3 inputs: <code>lag = the lag of the moving window</code>, <code>threshold = the z-score at which the algorithm signals</code> and <code>influence = the influence (between 0 and 1) of new signals on the mean and standard deviation</code>. For example, a <code>lag</code> of 5 will use the last 5 observations to smooth the data. A <code>threshold</code> of 3.5 will signal if a datapoint is 3.5 standard deviations away from the moving mean. And an <code>influence</code> of 0.5 gives signals <em>half</em> of the influence that normal datapoints have. Likewise, an <code>influence</code> of 0 ignores signals completely for recalculating the new threshold. An influence of 0 is therefore the most robust option (but assumes <a href="https://en.wikipedia.org/wiki/Stationary_process" rel="noreferrer">stationarity</a>); putting the influence option at 1 is least robust. For non-stationary data, the influence option should therefore be put somewhere between 0 and 1.</p>
<p>It works as follows:</p>
<p><em><strong>Pseudocode</strong></em></p>
<pre class="lang-r prettyprint-override"><code># Let y be a vector of timeseries data of at least length lag+2
# Let mean() be a function that calculates the mean
# Let std() be a function that calculates the standard deviaton
# Let absolute() be the absolute value function

# Settings (these are examples: choose what is best for your data!)
set lag to 5;          # average and std. are based on past 5 observations
set threshold to 3.5;  # signal when data point is 3.5 std. away from average
set influence to 0.5;  # between 0 (no influence) and 1 (full influence)

# Initialize variables
set signals to vector 0,...,0 of length of y;   # Initialize signal results
set filteredY to y(1),...,y(lag)                # Initialize filtered series
set avgFilter to null;                          # Initialize average filter
set stdFilter to null;                          # Initialize std. filter
set avgFilter(lag) to mean(y(1),...,y(lag));    # Initialize first value average
set stdFilter(lag) to std(y(1),...,y(lag));     # Initialize first value std.

for i=lag+1,...,t do
  if absolute(y(i) - avgFilter(i-1)) &gt; threshold*stdFilter(i-1) then
    if y(i) &gt; avgFilter(i-1) then
      set signals(i) to +1;                     # Positive signal
    else
      set signals(i) to -1;                     # Negative signal
    end
    set filteredY(i) to influence*y(i) + (1-influence)*filteredY(i-1);
  else
    set signals(i) to 0;                        # No signal
    set filteredY(i) to y(i);
  end
  set avgFilter(i) to mean(filteredY(i-lag+1),...,filteredY(i));
  set stdFilter(i) to std(filteredY(i-lag+1),...,filteredY(i));
end
</code></pre>
<p>Rules of thumb for selecting good parameters for your data can be found below.</p>
<hr />
<h2>Demo</h2>
<p><a href="https://i.imgur.com/LFvEM2Y.gif" rel="noreferrer"><img src="https://i.imgur.com/LFvEM2Y.gif" alt="Demonstration of robust thresholding algorithm" /></a></p>
<p><sub>The Matlab code for this demo can be found <a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/54507329#54507329"><strong>here</strong></a>. To use the demo, simply run it and create a time series yourself by clicking on the upper chart. The algorithm starts working after drawing <code>lag</code> number of observations.</sub></p>
<hr />
<h2>Result</h2>
<p>For the original question, this algorithm will give the following output when using the following settings: <code>lag = 30, threshold = 5, influence = 0</code>:</p>
<p><a href="https://i.stack.imgur.com/KdpF7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/KdpF7.jpg" alt="Thresholding algorithm example" /></a></p>
<hr />
<h2>Implementations in different programming languages:</h2>
<ul>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/54507329#54507329">Matlab</a> (me)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/54507329#54507329">R</a> (me)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/42144471#42144471">Golang</a> (Xeoncross)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/72502027#72502027">Golang</a> [efficient version] (Micah Parks)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/43512887#43512887">Python</a> (R Kiselev)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/56451135#56451135">Python</a> [efficient version] (delica)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/43583302/peak-detection-for-growing-time-series-using-swift/43607179#43607179">Swift</a> (me)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/46575416#46575416">Groovy</a> (JoshuaCWebDeveloper)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/46956908#46956908">C++</a> (brad)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/46998001#46998001">C++</a> (Animesh Pandey)</h2>
</li>
<li><h2><a href="https://github.com/swizard0/smoothed_z_score" rel="noreferrer">Rust</a> (swizard)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/48231877#48231877">Scala</a> (Mike Roberts)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/48772305#48772305">Kotlin</a> (leoderprofi)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/48895639#48895639">Ruby</a> (Kimmo Lehto)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/51185583#51185583">Fortran</a> [for resonance detection] (THo)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/52447946#52447946">Julia</a> (Matt Camp)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/53614452#53614452">C#</a> (Ocean Airdrop)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/54507140#54507140">C</a> (DavidC)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/56174275#56174275">Java</a> (takanuva15)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/57889588#57889588">JavaScript</a> (Dirk Lüsebrink)</h2>
</li>
<li><h2><a href="https://github.com/Bluejay47/zScore" rel="noreferrer">TypeScript</a> (Jerry Gamble)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/58859333#58859333">Perl</a> (Alen)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/59687045#59687045">PHP</a> (radhoo)</h2>
</li>
<li><h2><a href="https://github.com/gtjamesa/php-zscore" rel="noreferrer">PHP</a> (gtjamesa)</h2>
</li>
<li><h2><a href="https://stackoverflow.com/a/66700221/833188">Dart</a> (Sga)</h2>
</li>
</ul>
<hr />
<h2>Rules of thumb for configuring the algorithm</h2>
<p><em><strong><code>lag</code></strong></em>: the lag parameter determines how much your data will be smoothed and how adaptive the algorithm is to changes in the long-term average of the data. The more <a href="https://en.wikipedia.org/wiki/Stationary_process" rel="noreferrer">stationary</a> your data is, the more lags you should include (this should improve the robustness of the algorithm). If your data contains time-varying trends, you should consider how quickly you want the algorithm to adapt to these trends. I.e., if you put <code>lag</code> at 10, it takes 10 'periods' before the algorithm's treshold is adjusted to any systematic changes in the long-term average. So choose the <code>lag</code> parameter based on the trending behavior of your data and how adaptive you want the algorithm to be.</p>
<p><em><strong><code>influence</code></strong></em>: this parameter determines the influence of signals on the algorithm's detection threshold. If put at 0, signals have no influence on the threshold, such that future signals are detected based on a threshold that is calculated with a mean and standard deviation that is not influenced by past signals. If put at 0.5, signals have <em>half</em> the influence of normal data points. Another way to think about this is that if you put the influence at 0, you implicitly assume stationarity (i.e. no matter how many signals there are, you always expect the time series to return to the same average over the long term). If this is not the case, you should put the influence parameter somewhere between 0 and 1, depending on the extent to which signals can systematically influence the time-varying trend of the data. E.g., if signals lead to a <a href="https://en.wikipedia.org/wiki/Structural_break" rel="noreferrer">structural break</a> of the long-term average of the time series, the influence parameter should be put high (close to 1) so the threshold can react to structural breaks quickly.</p>
<p><em><strong><code>threshold</code></strong></em>: the threshold parameter is the number of standard deviations from the moving mean above which the algorithm will classify a new datapoint as being a signal. For example, if a new datapoint is 4.0 standard deviations above the moving mean and the threshold parameter is set as 3.5, the algorithm will identify the datapoint as a signal. This parameter should be set based on how many signals you expect. For example, if your data is normally distributed, a threshold (or: z-score) of 3.5 corresponds to a signaling probability of 0.00047 (from <a href="https://imgur.com/a/UJlXNJo" rel="noreferrer">this table</a>), which implies that you expect a signal once every 2128 datapoints (1/0.00047). The threshold therefore directly influences how sensitive the algorithm is and thereby also determines how often the algorithm signals. Examine your own data and choose a sensible threshold that makes the algorithm signal when you want it to (some trial-and-error might be needed here to get to a good threshold for your purpose).</p>
<hr />
<p><strong>WARNING: The code above always loops over all datapoints everytime it runs.</strong> When implementing this code, make sure to split the calculation of the signal into a separate function (without the loop). Then when a new datapoint arrives, update <code>filteredY</code>, <code>avgFilter</code> and <code>stdFilter</code> once. Do not recalculate the signals for all data everytime there is a new datapoint (like in the example above), that would be extremely inefficient and slow in real-time applications.</p>
<p>Other ways to modify the algorithm (for potential improvements) are:</p>
<ol>
<li>Use median instead of mean</li>
<li>Use a <a href="https://en.wikipedia.org/wiki/Robust_measures_of_scale" rel="noreferrer">robust measure of scale</a>, such as the median absolute deviation (MAD), instead of the standard deviation</li>
<li>Use a signalling margin, so the signal doesn't switch too often</li>
<li>Change the way the influence parameter works</li>
<li>Treat <em>up</em> and <em>down</em> signals differently (asymmetric treatment)</li>
<li>Create a separate <code>influence</code> parameter for the mean and std (<a href="https://stackoverflow.com/questions/43583302/peak-detection-for-growing-time-series-using-swift/43607179#43607179">as in this Swift translation</a>)</li>
</ol>
<hr />
<h2>(Known) academic citations to this StackOverflow answer:</h2>
<ul>
<li><p>Cai, Y., Wang, X., Joos, G., &amp; Kamwa, I. (2022). <a href="https://arxiv.org/pdf/2207.05356.pdf" rel="noreferrer"><strong>An Online Data-Driven Method to Locate Forced Oscillation Sources from Power Plants Based on Sparse Identification of Nonlinear Dynamics (SINDy)</strong></a>. IEEE Transactions on Power Systems.</p>
</li>
<li><p>Yang, S., Yim, J., Kim, J., &amp; Shin, H. V. (2022). <a href="https://dl.acm.org/doi/abs/10.1145/3491102.3517461" rel="noreferrer"><strong>CatchLive: Real-time Summarization of Live Streams with Stream Content and Interaction Data</strong></a>. <em>CHI Conference on Human Factors in Computing Systems</em>, 1-20.</p>
</li>
<li><p>Feng, D., Tan, Z., Engwirda, D., Liao, C., Xu, D., Bisht, G., ... &amp; Leung, R. (2022). <a href="https://hess.copernicus.org/preprints/hess-2022-251/" rel="noreferrer"><strong>Investigating coastal backwater effects and flooding in the coastal zone using a global river transport model on an unstructured mesh</strong></a>. <em>Hydrology and Earth System Sciences Discussions</em>, 1-31 [preprint].</p>
</li>
<li><p>Link, J., Perst, T., Stoeve, M., &amp; Eskofier, B. M. (2022). <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9002797/" rel="noreferrer"><strong>Wearable sensors for activity recognition in ultimate frisbee using convolutional neural networks and transfer learning</strong></a>. <em>Sensors</em>, 22(7), 2560.</p>
</li>
<li><p>Romeiro, J. M. N., Torres, F. T. P., &amp; Pirotti, F. (2021). <a href="https://www.sifet.org/bollettino/index.php/bollettinosifet/article/view/2266" rel="noreferrer"><strong>Evaluation of Effect of Prescribed Fires Using Spectral Indices and SAR Data</strong></a>. <em>Bollettino della società italiana di fotogrammetria e topografia</em>, (2), 36-56.</p>
</li>
<li><p>Moore, J., Goffin, P., Wiese, J., &amp; Meyer, M. (2021). <a href="https://dl.acm.org/doi/abs/10.1145/3494964" rel="noreferrer"><strong>An Interview Method for Engaging Personal Data</strong></a>. <em>Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies</em>, 5(4), 1-28.</p>
</li>
<li><p>Rykov, Y., Thach, T. Q., Bojic, I., Christopoulos, G., &amp; Car, J. (2021). <a href="https://mhealth.jmir.org/2021/10/e24872" rel="noreferrer"><strong>Digital Biomarkers for Depression Screening With Wearable Devices: Cross-sectional Study With Machine Learning Modeling</strong></a>. <em>JMIR mHealth and uHealth</em>, 9(10), e24872.</p>
</li>
<li><p>Hong, Y., Xin, Y., Martin, H., Bucher, D., &amp; Raubal, M. (2021). <a href="https://drops.dagstuhl.de/opus/volltexte/2021/14763/" rel="noreferrer"><strong>A Clustering-Based Framework for Individual Travel Behaviour Change Detection</strong></a>. In 11th International Conference on Geographic Information Science (GIScience 2021)-Part II.</p>
</li>
<li><p>Grammenos, A., Kalyvianaki, E., &amp; Pietzuch, P. (2021). <a href="https://arxiv.org/abs/2104.13429" rel="noreferrer"><strong>Pronto: Federated Task Scheduling</strong></a>. arXiv preprint arXiv:2104.13429.</p>
</li>
<li><p>Courtial, N. (2020). <a href="https://tel.archives-ouvertes.fr/tel-03048963/" rel="noreferrer"><strong>Fusion d’images multimodales pour l’assistance de procédures d’électrophysiologie cardiaque</strong></a>. <em>Doctoral dissertation</em>, Université Rennes.</p>
</li>
<li><p>Beckman, W. F., Jiménez, M. Á. L., Moerland, P. D., Westerhoff, H. V., &amp; Verschure, P. J. (2020). <a href="https://www.biorxiv.org/content/10.1101/2020.12.23.424175v1.full" rel="noreferrer"><strong>4sUDRB-sequencing for genome-wide transcription bursting quantification in breast cancer cells</strong></a>. bioRxiv.</p>
</li>
<li><p>Olkhovskiy, M., Müllerová, E., &amp; Martínek, P. (2020). <a href="https://content.sciendo.com/view/journals/jee/71/6/article-p397.xml" rel="noreferrer"><strong>Impulse signals classification using one dimensional convolutional neural network</strong></a>. Journal of Electrical Engineering, 71(6), 397-405.</p>
</li>
<li><p>Gao, S., &amp; Calderon, D. P. (2020). <a href="https://www.nature.com/articles/s41598-020-77162-3" rel="noreferrer"><strong>Robust alternative to the righting reflex to assess arousal in rodents</strong></a>. Scientific reports, 10(1), 1-11.</p>
</li>
<li><p>Chen, G. &amp; Dong, W. (2020). <a href="https://dl.acm.org/doi/abs/10.1145/3418210" rel="noreferrer"><strong>Reactive Jamming and Attack Mitigation over Cross-Technology Communication Links</strong></a>. ACM Transactions on Sensor Networks, 17(1).</p>
</li>
<li><p>Takahashi, R., Fukumoto, M., Han, C., Sasatani, T., Narusue, Y., &amp; Kawahara, Y. (2020). <a href="https://dl.acm.org/doi/abs/10.1145/3379337.3415873" rel="noreferrer"><strong>TelemetRing: A Batteryless and Wireless Ring-shaped Keyboard using Passive Inductive Telemetry</strong></a>. In Proceedings of the 33rd Annual ACM Symposium on User Interface Software and Technology (pp. 1161-1168).</p>
</li>
<li><p>Negus, M. J., Moore, M. R., Oliver, J. M., Cimpeanu, R. (2020). <a href="https://arxiv.org/abs/2009.09872" rel="noreferrer"><strong>Droplet impact onto a spring-supported plate: analysis and simulations</strong></a>. Journal of Engineering Mathematics, 128(3).</p>
</li>
<li><p>Yin, C. (2020). <a href="https://arxiv.org/abs/2006.00280" rel="noreferrer"><strong>Dinucleotide repeats in coronavirus SARS-CoV-2 genome: evolutionary implications</strong></a>. ArXiv e-print, accessible from: <a href="https://arxiv.org/pdf/2006.00280.pdf" rel="noreferrer">https://arxiv.org/pdf/2006.00280.pdf</a></p>
</li>
<li><p>Esnaola-Gonzalez, I., Gómez-Omella, M., Ferreiro, S., Fernandez, I., Lázaro, I., &amp; García, E. (2020). <a href="https://www.mdpi.com/1424-8220/20/6/1549" rel="noreferrer"><strong>An IoT Platform Towards the Enhancement of Poultry Production Chains</strong></a>. Sensors, 20(6), 1549.</p>
</li>
<li><p>Gao, S., &amp; Calderon, D. P. (2020). <a href="https://www.biorxiv.org/content/10.1101/2020.02.19.956789v1" rel="noreferrer"><strong>Continuous regimens of cortico-motor integration calibrate levels of arousal during emergence from anesthesia</strong></a>. bioRxiv.</p>
</li>
<li><p>Cloud, B., Tarien, B., Liu, A., Shedd, T., Lin, X., Hubbard, M., ... &amp; Moore, J. K. (2019). <a href="https://journals.plos.org/plosone/article/file?type=printable&amp;id=10.1371/journal.pone.0225690" rel="noreferrer"><strong>Adaptive smartphone-based sensor fusion for estimating competitive rowing kinematic metrics</strong></a>. PloS one, 14(12).</p>
</li>
<li><p>Ceyssens, F., Carmona, M. B., Kil, D., Deprez, M., Tooten, E., Nuttin, B., ... &amp; Puers, R. (2019). <a href="https://doi.org/10.1016/j.snb.2018.12.030" rel="noreferrer"><strong>Chronic neural recording with probes of subcellular cross-section using 0.06 mm² dissolving microneedles as insertion device</strong></a>. <em>Sensors and Actuators B: Chemical</em>, 284, pp. 369-376.</p>
</li>
<li><p>Dons, E., Laeremans, M., Orjuela, J. P., Avila-Palencia, I., de Nazelle, A., Nieuwenhuijsen, M., ... &amp; Nawrot, T. (2019). <a href="https://www.sciencedirect.com/science/article/pii/S1352231019304261" rel="noreferrer"><strong>Transport Most Likely to Cause Air Pollution Peak Exposures in Everyday Life: Evidence from over 2000 Days of Personal Monitoring</strong></a>. <em>Atmospheric Environment</em>, 213, 424-432.</p>
</li>
<li><p>Schaible B.J., Snook K.R., Yin J., et al. (2019). <a href="http://www.thepermanentejournal.org/issues/2019/summer/7190-twitter-poliomyelitis.html" rel="noreferrer"><strong>Twitter conversations and English news media reports on poliomyelitis in five different countries, January 2014 to April 2015</strong></a>. <em>The Permanente Journal</em>, 23, 18-181.</p>
</li>
<li><p>Lima, B. (2019). <a href="http://dx.doi.org/10.20381/ruor-24195" rel="noreferrer"><strong>Object Surface Exploration Using a Tactile-Enabled Robotic Fingertip</strong></a> (Doctoral dissertation, Université d'Ottawa/University of Ottawa).</p>
</li>
<li><p>Lima, B. M. R., Ramos, L. C. S., de Oliveira, T. E. A., da Fonseca, V. P., &amp; Petriu, E. M. (2019). <a href="https://proceedings.cmbes.ca/index.php/proceedings/article/view/850" rel="noreferrer"><strong>Heart Rate Detection Using a Multimodal Tactile Sensor and a Z-score Based Peak Detection Algorithm</strong></a>. <em>CMBES Proceedings</em>, 42.</p>
</li>
<li><p>Lima, B. M. R., de Oliveira, T. E. A., da Fonseca, V. P., Zhu, Q., Goubran, M., Groza, V. Z., &amp; Petriu, E. M. (2019, June). <a href="https://ieeexplore.ieee.org/abstract/document/8802209" rel="noreferrer"><strong>Heart Rate Detection Using a Miniaturized Multimodal Tactile Sensor</strong></a>. <em>In 2019 IEEE International Symposium on Medical Measurements and Applications (MeMeA)</em> (pp. 1-6). IEEE.</p>
</li>
<li><p>Ting, C., Field, R., Quach, T., Bauer, T. (2019). <a href="https://ieeexplore.ieee.org/abstract/document/8682257" rel="noreferrer"><strong>Generalized Boundary Detection Using Compression-based Analytics</strong></a>. <em>ICASSP 2019 - 2019 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP)</em>, Brighton, United Kingdom, pp. 3522-3526.</p>
</li>
<li><p>Carrier, E. E. (2019). <a href="http://hdl.handle.net/2142/104752" rel="noreferrer"><strong>Exploiting compression in solving discretized linear systems</strong></a>. <em>Doctoral dissertation</em>, University of Illinois at Urbana-Champaign.</p>
</li>
<li><p>Khandakar, A., Chowdhury, M. E., Ahmed, R., Dhib, A., Mohammed, M., Al-Emadi, N. A., &amp; Michelson, D. (2019). <a href="https://www.mdpi.com/1424-8220/19/7/1563" rel="noreferrer"><strong>Portable system for monitoring and controlling driver behavior and the use of a mobile phone while driving</strong></a>. <em>Sensors</em>, 19(7), 1563.</p>
</li>
<li><p>Baskozos, G., Dawes, J. M., Austin, J. S., Antunes-Martins, A., McDermott, L., Clark, A. J., ... &amp; Orengo, C. (2019). <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6343954/" rel="noreferrer"><strong>Comprehensive analysis of long noncoding RNA expression in dorsal root ganglion reveals cell-type specificity and dysregulation after nerve injury</strong></a>. <em>Pain</em>, 160(2), 463.</p>
</li>
<li><p>Cloud, B., Tarien, B., Crawford, R., &amp; Moore, J. (2018). <a href="https://doi.org/10.31224/osf.io/nykuh" rel="noreferrer"><strong>Adaptive smartphone-based sensor fusion for estimating competitive rowing kinematic metrics</strong></a>. <em>engrXiv Preprints</em>.</p>
</li>
<li><p>Zajdel, T. J. (2018). <a href="https://escholarship.org/uc/item/7vb3835n" rel="noreferrer"><strong>Electronic Interfaces for Bacteria-Based Biosensing</strong></a>. <em>Doctoral dissertation</em>, UC Berkeley.</p>
</li>
<li><p>Perkins, P., Heber, S. (2018). <a href="https://ieeexplore.ieee.org/abstract/document/8541902" rel="noreferrer"><strong>Identification of Ribosome Pause Sites Using a Z-Score Based Peak Detection Algorithm</strong></a>. <em>IEEE 8th International Conference on Computational Advances in Bio and Medical Sciences (ICCABS)</em>, ISBN: 978-1-5386-8520-4.</p>
</li>
<li><p>Moore, J., Goffin, P., Meyer, M., Lundrigan, P., Patwari, N., Sward, K., &amp; Wiese, J. (2018). <a href="https://www.cs.utah.edu/%7Ewiese/publications/MAAV_paper_v40.pdf" rel="noreferrer"><strong>Managing In-home Environments through Sensing, Annotating, and Visualizing Air Quality Data</strong></a>. <em>Proceedings of the ACM on Interactive, Mobile, Wearable and Ubiquitous Technologies</em>, 2(3), 128.</p>
</li>
<li><p>Lo, O., Buchanan, W. J., Griffiths, P., and Macfarlane, R. (2018), <a href="https://doi.org/10.1155/2018/5906368" rel="noreferrer"><strong>Distance Measurement Methods for Improved Insider Threat Detection</strong></a>, <em>Security and Communication Networks</em>, Vol. 2018, Article ID 5906368.</p>
</li>
<li><p>Apurupa, N. V., Singh, P., Chakravarthy, S., &amp; Buduru, A. B. (2018). <a href="https://repository.iiitd.edu.in/jspui/handle/123456789/632" rel="noreferrer"><strong>A critical study of power consumption patterns in Indian Apartments</strong></a>. <em>Doctoral dissertation</em>, IIIT-Delhi.</p>
</li>
<li><p>Scirea, M. (2017). <a href="https://en.itu.dk/%7E/media/en/research/phd-programme/phd-defences/2017/phd-thesis-temporary-version-marco-scirea-pdf.pdf?la=en" rel="noreferrer"><strong>Affective Music Generation and its effect on player experience</strong></a>. <em>Doctoral dissertation</em>, IT University of Copenhagen, Digital Design.</p>
</li>
<li><p>Scirea, M., Eklund, P., Togelius, J., &amp; Risi, S. (2017). <a href="http://sebastianrisi.com/wp-content/uploads/scirea_ceec17.pdf" rel="noreferrer"><strong>Primal-improv: Towards co-evolutionary musical improvisation</strong></a>. <em>Computer Science and Electronic Engineering (CEEC)</em>, 2017 (pp. 172-177). IEEE.</p>
</li>
<li><p>Catalbas, M. C., Cegovnik, T., Sodnik, J. and Gulten, A. (2017). <a href="https://ieeexplore.ieee.org/document/8266142/" rel="noreferrer"><strong>Driver fatigue detection based on saccadic eye movements</strong></a>, <em>10th International Conference on Electrical and Electronics Engineering (ELECO), pp. 913-917.</em></p>
</li>
</ul>
<p><strong>Other works using the algorithm from this answer</strong></p>
<ul>
<li><p>Bergamini, E. and E. Mourlon-Druol (2021). <a href="https://www.bruegel.org/wp-content/uploads/2021/03/WP-2021-04.pdf" rel="noreferrer"><strong>Talking about Europe: exploring 70 years of news archives</strong></a>. Working Paper 04/2021, Bruegel.</p>
</li>
<li><p>Cox, G. (2020). <a href="https://www.baeldung.com/cs/signal-peak-detection" rel="noreferrer"><strong>Peak Detection in a Measured Signal</strong></a>. <em>Online article on <a href="https://www.baeldung.com/cs/signal-peak-detection" rel="noreferrer">https://www.baeldung.com/cs/signal-peak-detection</a></em>.</p>
</li>
<li><p>Raimundo, D. W. (2020). <a href="https://pub.tik.ee.ethz.ch/students/2020-FS/SA-2020-09.pdf" rel="noreferrer"><strong>SwitP: Mobile Application for Real-Time Swimming Analysis.</strong></a>. <em>Semester Thesis</em>, ETH Zürich.</p>
</li>
<li><p>Bernardi, D. (2019). <a href="https://aaltodoc.aalto.fi/handle/123456789/39146" rel="noreferrer"><strong>A feasibility study on pairing a smartwatch and a mobile device through multi-modal gestures</strong></a>. <em>Master thesis</em>, Aalto University.</p>
</li>
<li><p>Lemmens, E. (2018). <a href="https://pure.tue.nl/ws/portalfiles/portal/125708557/1026332_Master_Thesis_Eef_Lemmens_BIS_269.pdf" rel="noreferrer"><strong>Outlier detection in event logs by using statistical methods</strong></a>, <em>Master thesis</em>, University of Eindhoven.</p>
</li>
<li><p>Willems, P. (2017). <a href="http://purl.utwente.nl/essays/73246" rel="noreferrer"><strong>Mood controlled affective ambiences for the elderly</strong></a>, <em>Master thesis</em>, University of Twente.</p>
</li>
<li><p>Ciocirdel, G. D. and Varga, M. (2016). <a href="https://event.cwi.nl/lsde/2016/papers/group02.pdf" rel="noreferrer"><strong>Election Prediction Based on Wikipedia Pageviews</strong></a>. <em>Project paper</em>, Vrije Universiteit Amsterdam.</p>
</li>
</ul>
<p><strong>Other applications of the algorithm from this answer</strong></p>
<ul>
<li><p><a href="https://www.avo.app/blog/avo-audit" rel="noreferrer"><strong>Avo Audit dbt package</strong></a>. Avo Company (next-generation analytics governance).</p>
</li>
<li><p><a href="https://openbci.com/community/synthesized-speech-with-openbci-system/" rel="noreferrer"><strong>Synthesized speech with OpenBCI system</strong></a>, SarahK01.</p>
</li>
<li><p><a href="https://github.com/hudson-and-thames/mlfinlab/blob/master/mlfinlab/filters/filters.py" rel="noreferrer"><strong>Python package: Machine Learning Financial Laboratory</strong></a>, based on the work of De Prado, M. L. (2018). <a href="https://link.springer.com/article/10.1007/s11408-019-00341-4" rel="noreferrer"><strong>Advances in financial machine learning</strong></a>. John Wiley &amp; Sons.</p>
</li>
<li><p><a href="https://github.com/adafruit/Adafruit_CircuitPlayground" rel="noreferrer"><strong>Adafruit CircuitPlayground Library</strong></a>, Adafruit board (Adafruit Industries)</p>
</li>
<li><p><a href="https://github.com/jeeshnair/ubicomp" rel="noreferrer"><strong>Step tracker algorithm</strong></a>, Android App (jeeshnair)</p>
</li>
<li><p><a href="https://cran.r-project.org/package=animaltracker" rel="noreferrer"><strong>R package: animaltracker</strong></a> (Joe Champion, Thea Sukianto)</p>
</li>
</ul>
<p><strong>Links to other peak detection algorithms</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/59557910/real-time-peak-detection-in-noisy-sinusoidal-time-series/59565524#59565524"><strong>Real-time peak detection in noisy sinusoidal time-series</strong></a></li>
</ul>
<hr />
<h2>How to reference this algorithm:</h2>
<blockquote>
<p>Brakel, J.P.G. van (2014). &quot;Robust peak detection algorithm using z-scores&quot;. Stack Overflow. Available at: <a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/22640362#22640362"> https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/22640362#22640362</a> (version: 2020-11-08).</p>
</blockquote>
<blockquote>
<p><sub><strong>Bibtex</strong>
@misc{brakel2014, author = {Brakel, J.P.G van}, title = {Robust peak detection algorithm using z-scores}, url = {https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/22640362#22640362}, language = {en}, year = {2014}, urldate = {2022-04-12}, journal = {Stack Overflow}, howpublished = {https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/22640362#22640362}}</sub></p>
</blockquote>
<hr />
<p><em>If you use this function somewhere, please credit me by using above reference. If you have any questions about the algorithm, post them in the comments below or contact me on <a href="https://www.linkedin.com/in/jpgvb" rel="noreferrer">LinkedIn</a>.</em></p>
<hr />
Peak signal detection in realtime timeseries data
<hr />
<p><strong>Update:</strong> The best performing algorithm <em>so far</em> <a href="https://stackoverflow.com/questions/22583391/peak-recognition-in-realtime-timeseries-data/22640362#22640362"><strong>is this one</strong></a>.</p>
<hr />
<p><em>This question explores robust algorithms for detecting sudden peaks in real-time timeseries data.</em></p>
<p>Consider the following example data:</p>
<p><a href="https://i.stack.imgur.com/yUeKr.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/yUeKr.jpg" alt="Plot of data" /></a></p>
<p><sub>Example of this data is in Matlab format (but this question is not about the language but about the algorithm):</sub></p>
<pre><code>p = [1 1 1.1 1 0.9 1 1 1.1 1 0.9 1 1.1 1 1 0.9 1 1 1.1 1 1 1 1 1.1 0.9 1 1.1 1 1 0.9, ...
     1 1.1 1 1 1.1 1 0.8 0.9 1 1.2 0.9 1 1 1.1 1.2 1 1.5 1 3 2 5 3 2 1 1 1 0.9 1 1, ... 
     3 2.6 4 3 3.2 2 1 1 0.8 4 4 2 2.5 1 1 1];
</code></pre>
<p>You can clearly see that there are three large peaks and some small peaks. This dataset is a specific example of the class of timeseries datasets that the question is about. This class of datasets has two general features:</p>
<ol>
<li>There is basic noise with a general mean</li>
<li>There are large '<em>peaks</em>' or '<em>higher data points</em>' that significantly deviate from the noise.</li>
</ol>
<p>Let's also assume the following:</p>
<ul>
<li>The width of the peaks cannot be determined beforehand</li>
<li>The height of the peaks significantly deviates from the other values</li>
<li>The algorithm updates in realtime (so updates with each new datapoint)</li>
</ul>
<p>For such a situation, a boundary value needs to be constructed which triggers signals. However, the boundary value cannot be static and must be determined realtime based on an algorithm.</p>
<hr />
<p><strong>My Question: what is a good algorithm to calculate such thresholds in realtime?</strong> Are there specific algorithms for such situations? What are the most well-known algorithms?</p>
<hr />
<p><sub>Robust algorithms or useful insights are all highly appreciated. (can answer in any language: it's about the algorithm)</sub></p>