我在下面的代码中遇到了一个小问题。它工作得很好,但它不是我写的,有一部分我不明白。在我的头脑中,我需要返回rm&来自get_rolling_mean()
和get_rolling_std()
的rstd,但这并不是真的发生在这里。所以我的问题是:我知道它有效,但它是如何工作的?
get_bollinger_bands(rm, rstd)
变量中的rm和rstd在何处以及如何从中获取其值?
"""Bollinger Bands."""
import os
import pandas as pd
import matplotlib.pyplot as plt
def symbol_to_path(symbol, base_dir="data"):
"""Return CSV file path given ticker symbol."""
return os.path.join(base_dir, "{}.csv".format(str(symbol)))
def get_data(symbols, dates):
"""Read stock data (adjusted close) for given symbols from CSV files."""
df = pd.DataFrame(index=dates)
if 'SPY' not in symbols: # add SPY for reference, if absent
symbols.insert(0, 'SPY')
for symbol in symbols:
df_temp = pd.read_csv(symbol_to_path(symbol), index_col='Date',
parse_dates=True, usecols=['Date', 'Adj Close'], na_values=['nan'])
df_temp = df_temp.rename(columns={'Adj Close': symbol})
df = df.join(df_temp)
if symbol == 'SPY': # drop dates SPY did not trade
df = df.dropna(subset=["SPY"])
return df
def plot_data(df, title="Stock prices"):
"""Plot stock prices with a custom title and meaningful axis labels."""
ax = df.plot(title=title, fontsize=12)
ax.set_xlabel("Date")
ax.set_ylabel("Price")
plt.show()
def get_rolling_mean(values, window):
"""Return rolling mean of given values, using specified window size."""
return pd.rolling_mean(values, window=window)
def get_rolling_std(values, window):
"""Return rolling standard deviation of given values, using specified window size."""
return pd.rolling_std(values, window=window)
def get_bollinger_bands(rm, rstd):
"""Return upper and lower Bollinger Bands."""
upper_band = rm + (rstd * 2)
lower_band = rm - (rstd * 2)
return upper_band, lower_band
def test_run():
# Read data
dates = pd.date_range('2012-01-01', '2012-12-31')
symbols = ['SPY']
df = get_data(symbols, dates)
# Compute Bollinger Bands
# 1. Compute rolling mean
rm_SPY = get_rolling_mean(df['SPY'], window=20)
# 2. Compute rolling standard deviation
rstd_SPY = get_rolling_std(df['SPY'], window=20)
# 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['SPY'].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()
答案 0 :(得分:2)
Get rollinger bands函数从用户获取变量:
get_bollinger_bands(rm, rstd):
upper_band = rm + (rstd * 2)
lower_band = rm - (rstd * 2)
return upper_band, lower_band
使用的唯一变量是函数名后面的括号之间的变量。这意味着他们将被用户所污染。
def get_rolling_mean(values, window):
return pd.rolling_mean(values, window=window)
def get_rolling_std(values, window):
return pd.rolling_std(values, window=window)
函数得到滚动均值和标准都使用两个投入:值(又名x = 1,2,3和y = 2,3,4)和窗口(滚动平均值中包含的观察量)< / p>
有关其他信息,我建议使用文档:http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_mean.html
和维基百科(滚动均值和移动平均值是相同的):https://en.wikipedia.org/wiki/Moving_average