Search code examples
pythonsmoothingexponentialforecastais

How to implement exponential smoothing manually with Python?


This is my first question here and I'm also new to Python (without a CS background, I must add) as well!

I'm trying to implement triple exponential smoothing to make predictions. My data is based on AIS data and I'm focusing on SOG (Speed Over Ground) values specifically. Mathematical approach that I'm following is the Triple Exponential Smoothing Model.

I've still only followed the basics of Python and I'm struggling to figure out the iteration part. What I expect, however, is to read data from a CSV (which includes Time and SOG) and forecast the Speed values, so I can compare the predicted and real values.

Here is the example/test data table that I'm using atm.

I tried coding the equation part (shown below) and I know it is beyond sloppy. But I didn't want to come here without anything.

alpha = 0.9
m = 3


def test(ssv_current, x_current, ssv_previous, dsv_previous, tsv_previous):
    # ssv = single smoothing value (s'(t-1) and s'(t))
    ssv_current = (alpha * x_current) + ((1 - alpha) * ssv_previous)
    # dsv = double smoothing value (s''(t-1) and s''(t))
    dsv_current = (alpha * ssv_current) + ((1 - alpha) * dsv_previous)
    # tsv = triple smoothing value (s'''(t-1) and s'''(t))
    tsv_current = (alpha * dsv_current) + ((1 - alpha) * tsv_previous)
    at = (3 * ssv_current) - (3 * dsv_current) + tsv_current

    bt = ((alpha ** 2) / (2 * ((1 - alpha) ** 2))) * (((6 - 5 * alpha) * ssv_current) - ((10 - 8 * alpha) * dsv_current)
                                                      + ((4 - 3 * alpha) * tsv_current))
    ct = ((alpha ** 2) / ((1 - alpha) ** 2)) * (ssv_current - (2 * dsv_current) + tsv_current)

    ft = at + (m * bt) + (0.5 * (m ** 2) * ct)  # mth predicted value at time t

I know both my question and piece of code seem trash, but I look forward to learning from this community. I've only worked with MatLab before and any tip here would really help me. TIA!

EDIT: I realized my post does not convey what I really want. Basically, I want the code to read through the speed values one-by-one and iterate through it and print the predicted value.


Solution

  • A very basic iterator would be

    import csv
    
    datafile = open('datafile.csv', 'r')
    csv_file = csv.reader(datafile)
    
    for row in csv_file:
       print(row)
    

    Each 'row' item would have the data

    Refer: CSV Library reference

    You could do the same with pandas as well.

    import pandas as pd
    
    df = pd.read_csv('datafile.csv')
    

    Now, you dont need to iterate. Just do calculations using entire columns at once and pandas will create those results. e.g.

    df['total'] = df['a'] + df['b']
    

    Just like that Refer: Pandas