Search code examples
pythonhammingweight

How to make smoother wave by apply hamming window?


I have try to make the smoother wave (from stock price) but I don't know how to apply it to my wave.

import numpy as np
wave = [1575.7918235085228, 1574.2183726917613, 1571.9212868430398, 1569.5071067116478, 1568.4249178799716, 1567.4649192116478, 1566.7141801313921, 1565.9849054509943, 1565.4699951171874, 1566.766004527699, 1567.222733931108, 1567.4478271484375, 1566.3074729225852, 1563.4207475142045, 1559.6012806285512, 1555.0241965553978, 1552.6043723366477, 1550.9003773082386, 1549.0460116299716, 1548.2069202769887, 1549.2643687855114, 1551.792538174716, 1554.6467240767045, 1557.9874578302556, 1560.9547341086648, 1563.2614679509943, 1565.0818204012785, 1565.241825727983, 1565.4223677201705, 1566.1059992009943, 1566.3267223011364, 1566.7634410511364, 1566.691796875, 1567.2850763494318, 1567.2025368430398, 1566.6512761896306, 1567.7338201349432, 1569.591093306108, 1570.538554243608, 1571.8510919744317, 1573.8294588955966]
hamm = np.hamming(len(wave))

here is example image example Reference of hamming moving average from aspen program

my wave variable is green line after plot. this program have function to apply hamming to it then plot the red line

So I just want to know how this program do.

Thank you.


Solution

  • Typically stock prices are "smoothed" using a sliding window technique. The window duration is typically 10-100 days or so. Starting with the day 1, grab the next N days of data and calculate the average (the window of time here is day 1 to 1 + N). This is your new "smoothed" value for day 1. Then move to day 2 and do the same thing, but now your window is day 2 to 2+N and you have your smoothed value for day 2. Repeat until you run out of data.

    Without realizing it, you have applied a rectangular window function each time you did this. The rectangular window function has value 1 at all times in the window and 0 everywhere else. When you multiply your original data by the window you have effectively sampled only the data points that fell into the window. The values of the data points are unchanged though because with a rectangular window you multiplied by 1.

    The rectangular window function has some undesireable properties though. If you take the Fourier transform of it you'll see that it has very high sidelobes. This has the effect of broadening or "smearing" frequency spikes in the original data. Thus people use other windowing functions such as hamming, hanning, etc. These window functions do not have a constant value of 1 for each point in the window function.

    So what you need to do in your code is take your original wave array and set up a loop that extracts N samples, multiplies them by a hamming window array of length N, then calculate the average and store it in a new array.