滚动平均值未显示在我的图表上

时间:2016-03-27 16:57:38

标签: python pandas

我在python pandas上运行,并且无法弄清楚,为什么窗口大小为40的滚动平均值没有显示yahoo的股票价格图

首先我获取数据(已通过日期):

def get_data(dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
df = pd.DataFrame(index=dates)
df_temp = pd.read_csv('table.csv', index_col='Date', parse_dates=True,    

     usecols=['Date', 'Adj Close'], na_values=['nan'])
df = df.join(df_temp)
df.dropna()


return df

然后我去寻找滚动平均值(其中值= df(雅虎股票价格和窗口数据= 40)):

def get_rolling_mean(values, window):
"""Return rolling mean of given values, using specified window size."""
return values.rolling(center=False, window=window).mean()

然后我去绘图:

ax = df.plot(title="Bollinger Bands", label='YAHO')
rm_SPY.plot(label='Rolling mean', ax=ax)

最后,我只得到雅虎的Adj Close价格图表,没有其他人喜欢说的“滚动平均值”或“移动点平均值”

完整的代码在这里:

def get_data(dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
df = pd.DataFrame(index=dates)
df_temp = pd.read_csv('table.csv', index_col='Date', parse_dates=True, 
                      usecols=['Date', 'Adj Close'], na_values=['nan'])
df = df.join(df_temp)
df.dropna()


return df



def get_rolling_mean(values, window):
"""Return rolling mean of given values, using specified window size."""
return values.rolling(center=False, window=window).mean()


def get_rolling_std(values, window):
"""Return rolling standard deviation of given values, using specified window
      size."""
# TODO: Compute and return rolling standard deviation
return values.rolling(center=False, window=window).std()


def get_bollinger_bands(rm, rstd):
"""Return upper and lower Bollinger Bands."""
# TODO: Compute upper_band and lower_band
upper_band = rm+rstd
lower_band = rm-rstd
return upper_band, lower_band


def test_run():
# Read data
dates = pd.date_range('2012-01-01', '2012-12-31')
df = get_data(dates)

# Compute Bollinger Bands
# 1. Compute rolling mean
rm_SPY = get_rolling_mean(df, window=40)


# 2. Compute rolling standard deviation
rstd_SPY = get_rolling_std(df, window=40)

# 3. Compute upper and lower bands
upper_band, lower_band = get_bollinger_bands(rm_SPY, rstd_SPY)

# Plot raw SPY values, rolling mean and Bollinger Bands
ax = df.plot(title="Bollinger Bands", label='SPY')
rm_SPY.plot(label='Rolling mean', ax=ax)
upper_band.plot(label='upper band', ax=ax)
lower_band.plot(label='lower band', ax=ax)

# Add axis labels and legend
ax.set_xlabel("Date")
ax.set_ylabel("Price")
ax.legend(loc='upper left')


plt.show()


if __name__ == "__main__":
    test_run()

1 个答案:

答案 0 :(得分:1)

请查看这是否对您有所帮助:

from pandas_datareader import data

def get_rolling_mean(values, window):
    """Return rolling mean of given values, using specified window size."""
    return values.rolling(center=False, window=window).mean()

def get_rolling_std(values, window):
    """Return rolling standard deviation of given values, using specified window
          size."""
    # TODO: Compute and return rolling standard deviation
    return values.rolling(center=False, window=window).std()

def get_bollinger_bands(rm, rstd):
    """Return upper and lower Bollinger Bands."""
    # TODO: Compute upper_band and lower_band
    upper_band = rm+rstd
    lower_band = rm-rstd
    return upper_band, lower_band

df = data.get_data_yahoo('YHOO')['Adj Close']

# Compute Bollinger Bands
# 1. Compute rolling mean
rm_YHOO = get_rolling_mean(df, window=40)

# 2. Compute rolling standard deviation
rstd_YHOO = get_rolling_std(df, window=40)

# 3. Compute upper and lower bands
upper_band, lower_band = get_bollinger_bands(rm_YHOO, rstd_YHOO)

# Plot raw SPY values, rolling mean and Bollinger Bands
_, ax = plt.subplots()
df.plot(title="Bollinger Bands", label='YHOO', ax=ax)
rm_YHOO.plot(label='Rolling mean', ax=ax)
upper_band.plot(label='upper band', ax=ax)
lower_band.plot(label='lower band', ax=ax)

# Add axis labels and legend
ax.set_xlabel("Date")
ax.set_ylabel("Price")
ax.legend(loc='upper left')

plt.show()

enter image description here