如何解决事件发生时在python中收集数据点
当股票价格超过移动平均线(MA)时,我想收集价格点。在这里,我将以Microsoft为例。
我的股票价格为:
Microsoft_Stock = web.DataReader(['MSFT'],'yahoo',start =...,end=...)
,然后将此股票的移动平均线设为:
Microsoft_Stock['Moving_Average_20_Days'] = Microsoft_Stock['Close'].rolling(window = 20,min_periods = 1).mean()
如何获得这两条线交叉的点的列表?
解决方法
可能有一种更聪明的提取价格的方法,但是您可以通过找到收盘价和移动平均线之间的差并提取其绝对值(例如低于1)来找到交叉点的价格。 / p>
MSFT['cross_point'] = MSFT['Adj Close'] - MSFT['MA_20_Days']
MSFT[abs(MSFT['cross_point']) < 1]
Attributes Adj Close Close High Low Open Volume MA_20_Days cross_point
Date
2019-01-04 99.652115 101.930000 102.510002 98.930000 99.720001 44060600.0 100.505001 -0.852886
2019-01-08 100.502670 102.800003 103.970001 101.709999 103.040001 31514400.0 101.146667 -0.643997
2019-01-09 101.939812 104.269997 104.879997 103.239998 103.860001 32280800.0 101.592857 0.346954
2019-01-10 101.284798 103.599998 103.750000 102.379997 103.220001 30067600.0 101.843750 -0.558952
2019-01-15 102.663292 105.010002 105.050003 101.879997 102.510002 31587600.0 102.237273 0.426018
... ... ... ... ... ... ... ... ...
2020-08-14 208.396240 208.899994 209.589996 207.509995 208.759995 17958900.0 208.239999 0.156241
2020-09-28 209.440002 209.440002 212.570007 208.059998 210.880005 32004900.0 209.644500 -0.204498
2020-10-02 206.190002 206.190002 210.990005 205.539993 208.000000 33154800.0 206.369000 -0.178998
2020-10-06 205.910004 205.910004 210.179993 204.820007 208.820007 28554300.0 206.338000 -0.427997
2020-10-27 213.250000 213.250000 214.669998 210.330002 211.589996 36700300.0 214.202501 -0.952501
103 rows × 8 columns
,
由于您尚未指定所需的输出确切是什么,因此我假设您要使用两个值相同的日期或交叉点之后的日期。
import numpy as np
from matplotlib import pyplot as plt
import datetime as dt
import pandas_datareader.data as web
#your input routine
start,end = dt.datetime(2020,3,1),dt.datetime(2020,5,31)
MS = web.DataReader('MSFT','yahoo',start=start,end=end)
MS['MA_20_D'] = MS['Close'].rolling(window = 20,min_periods = 1).mean()
#identify changes between the curves
MS["CP"] = MS["Close"] - MS["MA_20_D"]
MS["CP_Arr"] = MS["CP"].map(np.sign).diff().abs()
#deal with the special case that they have the same value
#either at one point
MS.loc[MS["CP"].shift() == 0,"CP_Arr"] = 0
#or a series of points
MS.loc[MS["CP"] == 0,"CP_Arr"] = 1
#if CP_Arr is now >0,then there was
#either a crossover between this and the previous date
#or the values are equal at this specific date
#now we filter for this to get an array of all these points
CP_MS = MS[MS["CP_Arr"].ge(1)]
print(CP_MS)
#to verify our approach,let's plot the curves
plt.plot(MS["Close"],label="Close")
plt.plot(MS["MA_20_D"],label="Moving_Average_20_Days")
#and mark the dates we have identified
for covdate in CP_MS.index.values:
print(covdate)
plt.axvline(covdate)
plt.xticks(rotation = 45,ha="right")
plt.legend()
plt.tight_layout()
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。