def mov_avg(rates, window=14):
    """
    Returns the moving average with the given window size.

    rates (iterable):   each element is a tick.
    window (int):       each moving average tick is computed as the last
                        <window> ticks including the current tick.
    """
    if len(rates) < window:
        return []

    mas = []
    for i, rate in enumerate(rates):
        if i < window - 1:
            continue

        mas_idx = i - window + 1

        # First moving average value: initialize it using the last 'window' values
        if len(mas) == 0:
            assert(mas_idx == 0)
            mas.append(sum(rates[:window]) / window)
            continue

        assert(mas_idx > 0)
        """
        The next moving average value is calculated as follows:

            mas_n    = ( (window - 1) * mas_{n-1} + rate ) / window
                    = mas_{n-1} * (window - 1) / window   +   rate / window
        """
        mas.append(mas[mas_idx-1] * ( (window-1) / window ) + (rate / window))

    return mas