gpt4 book ai didi

python panda 计算滚动平均值

转载 作者:行者123 更新时间:2023-12-01 03:54:41 24 4
gpt4 key购买 nike

我正在尝试计算 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()

最佳答案

你问的方式让我很困惑。我制造了数据并创建了一个希望有所帮助的函数。

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

关于python panda 计算滚动平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37666601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com