如何调整移动平均线以进行每周分析?

时间:2018-12-04 18:23:53

标签: python pandas algorithm dataframe nsepy

我需要根据每周间隔(例如3周间隔或21天)绘制移动平均值,但是在调整错过的日期时,它现在计数为0,因此得出的结果不正确。

from nsepy import get_history as gh
from datetime import date
import pandas as pd

nifty = gh(symbol="NIFTY IT", 
                    start=date(2015,1,1), 
                    end=date(2016,1,3),
                    index=True)
idx = pd.date_range('01-01-2015', '01-01-2016')
nifty.index = pd.DatetimeIndex(nifty.index)
nifty = nifty.reindex(idx, fill_value=0)
nifty["3weekMA"]=nifty["Close"].rolling(21).mean()
nifty[nifty.Open != 0]

该如何解决?

这是实际结果: ![enter image description here

所需的结果必须类似于:

![enter image description here

这是因为收盘的移动平均线必须在11000而不是8000的范围内。

1 个答案:

答案 0 :(得分:1)

想到的最简单的事情就是从数据中删除周末值:

nifty=nifty[nifty['Close']!=0]

然后执行移动平均:

nifty["3weekMA"]=nifty["Close"].rolling(15).mean()

只需使用15而不是21,就可以正常工作。不过,几乎没有什么指针。滚动均值将给出最后15个值的均值,但问题在于它的结果是第15个值或您的情况下的第21个值,因此生成的图看起来像这样:

enter image description here

因此,要解决此问题,我们所需要做的就是向上移动找到的新移动平均值,或者仅绘制前7个,最后7个之前的Close值以及移动平均值,就像:

plt.figure(figsize=(10,8))
plt.plot(nifty['Close'].values.tolist()[7:-7])
plt.plot(nifty['3weekMA'].values.tolist()[14:])

enter image description here

但是可视化只是为了表示目的;我希望您能对如何处理此类数据有所了解。我希望这能解决您的问题,是的,“移动平均”值的确以11K而不是以8K为单位。

样本输出:

        Date         Open       High        Low         Close       Volume      Turnover        3weekMA
        -------------------------------------------------------------------------------------------------
        2015-01-15  11672.30    11774.50    11575.10    11669.85    13882213    1.764560e+10    NaN
        2015-01-16  11708.85    11708.85    11582.85    11659.60    12368107    1.714690e+10    NaN
        2015-01-19  11732.50    11797.60    11629.05    11642.75    13696381    1.183750e+10    NaN
        2015-01-20  11681.80    11721.90    11635.70    11695.00    11021415    1.234730e+10    NaN
        2015-01-21  11732.45    11838.30    11659.70    11813.70    18679282    1.973070e+10    11418.113333
        2015-01-22  11832.55    11884.50    11782.95    11850.85    15715515    1.655670e+10    11460.456667
        2015-01-23  11877.90    11921.00    11767.40    11885.15    30034833    2.001210e+10    11494.660000
        2015-01-27  11915.60    11917.25    11679.55    11693.45    17005337    1.866840e+10    11524.320000
        2015-01-28  11712.55    11821.80    11693.80    11809.55    16876897    1.937590e+10    11580.963333
        2015-01-29  11812.35    11861.50    11728.75    11824.15    15520902    2.160790e+10    11641.506667
        2015-01-30  11998.35    12003.35    11799.35    11824.75    18559078    2.905950e+10    11695.280000
        2015-02-02  11871.35    11972.60    11847.80    11943.95    17272113    2.304050e+10    11731.566667
        2015-02-03  11963.75    12000.65    11849.00    11963.90    21053605    1.770590e+10    11759.583333
相关问题