Template sensor and automation to track speed / acceleration from GPS device tracker

Hi all, I am working on a project that uses GPS data from my phone to track speed.

It works OK but I do get crazy data from time to time and this creates spikes in speed that are incorrect. I have tried different ways to filter the data and my latest idea is to calculate acceleration between each speed data point. To do this I need the following:

  1. current speed (I have this)
  2. time stamp for current speed (I have this)
  3. time since last GPS/speed (I have this)

So I can create input number helpers for this data and then use them to calculate acceleration etc when I receive new data. But this is clunky as for each device i will need to create multiple input number helpers.

I have been trying to create a template sensor that holds all the data I need as attributes but I can’t find a way to hold the data from the previous speed/gps data.

I tried using this.state and this.attributes.name and states(entity) as I hoped one would have the previous data. Here is my working/testing yaml.

Any advice appreciated

- sensor:
    - name: "Jago iPhone Acceleration Test"
      unique_id: jago_iphone_acc_test
      icon: "mdi:speedometer"
      state: >
        {% set speed = states('sensor.jago_iphone_speed') | float(0) %}
        {% set gps_age = states('sensor.jago_gps_age') | float(0) %}
        {% set speed_last = state_attr('sensor.jago_iphone_acc_test', 'speed_last') %}
        {% if speed_last == 'None' %}{% set acc = 0 %}{% else %}{% set acc = ((speed - speed_last) / gps_age) | int(2) %}{% endif %} 
        "{{ acc }}"       
      attributes:
        speed_last: "{{ states('sensor.jago_iphone_speed') | float(0) }}"
        gps_age_last: "{{ states('sensor.jago_gps_age') | float(0) }}"
        time_last: "{{ state_attr('device_tracker.jago_iphone_2', 'last_seen') }}"
        acc_last: "{{ states('jago_iphone_acc_test') | float(0) }}"