python_移动窗口函数
Moving Window Functions
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
close_px_all = pd.read_csv('examples/stock_px_2.csv',
parse_dates=True, index_col=0)
close_px = close_px_all[['AAPL', 'MSFT', 'XOM']]
close_px = close_px.resample('B').ffill()
close_px.AAPL.plot()
close_px.AAPL.rolling(250).mean().plot()
<matplotlib.axes._subplots.AxesSubplot at 0x1557c8bcef0>
plt
plt.figure()
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
appl_std250 = close_px.AAPL.rolling(250, min_periods=10).std()
appl_std250[5:12]
appl_std250.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x1557c9ae0f0>
expanding_mean = appl_std250.expanding().mean()
plt.figure()
close_px.rolling(60).mean().plot(logy=True)
<matplotlib.axes._subplots.AxesSubplot at 0x16dee0be7f0>
close_px.rolling('20D').mean()
Exponentially Weighted Functions
plt.figure()
指数加权函数
aapl_px = close_px.AAPL['2006':'2007']
ma60 = aapl_px.rolling(30, min_periods=20).mean()
ewma60 = aapl_px.ewm(span=30).mean()
ma60.plot(style='k--', label='Simple MA')
ewma60.plot(style='k-', label='EW MA')
plt.legend()
<matplotlib.legend.Legend at 0x1557da34ba8>
Binary Moving Window Functions
⼆元移动窗⼝函数
plt.figure()
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
spx_px = close_px_all['SPX']
spx_rets = spx_px.pct_change()
returns = close_px.pct_change()
corr = returns.AAPL.rolling(125, min_periods=100).corr(spx_rets)
corr.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x1557dbac550>
plt.figure()
假设你想要⼀次性计算多只股票与标准普尔500指数的相关系
corr = returns.rolling(125, min_periods=100).corr(spx_rets)
corr.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x1557dc7e898>
User-Defined Moving Window Functions
plt.figure()
⽤户定义的移动窗⼝函数
from scipy.stats import percentileofscore
score_at_2percent = lambda x: percentileofscore(x, 0.02)
result = returns.AAPL.rolling(250).apply(score_at_2percent)
result.plot()
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:9: FutureWarning: Currently, 'apply' passes the values as ndarrays to the applied function. In the future, this will change to passing it as Series objects. You need to specify 'raw=True' to keep the current behaviour, and you can pass 'raw=False' to silence this warning
if __name__ == '__main__':
<matplotlib.axes._subplots.AxesSubplot at 0x1557e7b4ac8>
pd.options.display.max_rows = PREVIOUS_MAX_ROWS
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-20-1d8d9b03b286> in <module>()
----> 1 pd.options.display.max_rows = PREVIOUS_MAX_ROWS
NameError: name 'PREVIOUS_MAX_ROWS' is not defined
Conclusion