Build a timeseries from the internal state

def callback_show_timeseries(internal_state_string, state_uid, **kwargs):
    'Build a timeseries from the internal state'

    cache_key = _get_cache_key(state_uid)
    state = cache.get(cache_key)

    # If nothing in cache, prepopulate
    if not state:
        state = {}

    colour_series = {}

    colors = {'red':'#FF0000',
              'blue':'#0000FF',
              'green':'#00FF00',
              'yellow': '#FFFF00',
              'cyan': '#00FFFF',
              'magenta': '#FF00FF',
              'black' : '#000000',
             }

    for colour, values in state.items():
        timestamps = [datetime.fromtimestamp(int(0.001*ts)) for _, ts, _ in values if ts > 0]
        #users = [user for user, ts, _ in values if ts > 0]
        levels = [level for _, ts, level in values if ts > 0]
        if colour in colors:
            colour_series[colour] = pd.Series(levels, index=timestamps).groupby(level=0).first()

    df = pd.DataFrame(colour_series).fillna(method="ffill").reset_index()[-25:]

    traces = [go.Scatter(y=df[colour],
                         x=df['index'],
                         name=colour,
                         line=dict(color=colors.get(colour, '#000000')),
                        ) for colour in colour_series]

    return {'data':traces,
            #'layout': go.Layout
           }