蟒蛇熊猫计算滚动手段

时间:2016-06-06 20:45:26

标签: python numpy pandas

我正在尝试计算facebook股票的布林带。但我发现rm_FB(计算的滚动平均值)都是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()

1 个答案:

答案 0 :(得分:2)

我对你的提问感到困惑。我制作了数据并创建了一个我希望有帮助的功能。

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)

示范

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