esther fang esther fang - 6 months ago 68
Python Question

python panda to calculate rolling means

I am trying to calculate the bollinger band of facebook stock. But I found the rm_FB (the calculated rolling mean) are all nan

BollingerBands

def get_rolling_mean(values, window):
"""Return rolling mean of given values, using specified window size."""
t = pd.date_range('2016-02-01', '2016-06-06', freq='D')
# print("Hey")
# print(values);
D = pd.Series(values, t)

return D.rolling(window=20,center=False).mean()



def test_run():
# Read data
dates = pd.date_range('2016-02-01', '2016-06-06')
symbols = ['FB']
df = get_data(symbols, dates)

# Compute Bollinger Bands
# 1. Compute rolling mean
rm_FB = get_rolling_mean(df['FB'], window=20)
print("Hey")
print(rm_FB)


if __name__ == "__main__":
test_run()

Answer

I was confused by how you asked. I manufactured the data and created a function I hope helps.

import pandas as pd
import numpy as np

def bollinger_bands(s, k=2, n=20):
    """get_bollinger_bands DataFrame
    s is series of values
    k is multiple of standard deviations
    n is rolling window
    """

    b = pd.concat([s, s.rolling(n).agg([np.mean, np.std])], axis=1)
    b['upper'] = b['mean'] + b['std'] * k
    b['lower'] = b['mean'] - b['std'] * k

    return b.drop('std', axis=1)

Demonstration

np.random.seed([3,1415])
s = pd.Series(np.random.randn(100) / 100, name='price').add(1.001).cumprod()

bollinger_bands(s).plot()

enter image description here