【发布时间】:2019-11-14 16:56:48
【问题描述】:
我在这里查看了 StackOverflow 上的一些不同解决方案,但我无法在我的应用程序中成功实现其中一个。主要是因为我不完全确定每个解决方案在做什么,所以我希望有人可以帮助我。
我有一个简单的脚本,它使用 DataReader 收集每日股票数据,将这些数据重新采样为每周数据,然后我试图查看从上周收盘价到本周开盘价之间的价格是否存在差距.
我的代码如下所示,任何人都应该能够实现:
import pandas_datareader.data as web
from datetime import datetime
import pandas as pd
# Inputs for stock data
stocks = ['AAPL']
ex = 'yahoo'
start = datetime(2018, 1, 2)
end = datetime(2019, 7, 2)
# Now, it'll get the daily stock data for each stock, and convert it to weekly data
for i in stocks:
a = web.DataReader(i, ex, start, end)
output = a.resample('W').agg({'Open': 'first',
'High': 'max',
'Low': 'min',
'Close': 'last',
'Volume': 'sum'})
output.index=output.index+pd.DateOffset(days=-6) # -6 Makes it Monday as the start of the week
print(output)
# Now, to iterate over each row, and print each time theres a gap
for index, row in output.iterrows():
currentopen = row['Open']
prevclose = row['Close'].shift(1)
if currentopen > prevclose:
print('The current open gapped up from last weeks close.')
elif currentopen < prevclose:
print('Houston we have a gap down!')
所以“for”循环中的当前行代表当前的一周,我正在尝试使用 .shift() 从上一行获取“收盘价”。目前我收到错误:
AttributeError: 'numpy.float64' object has no attribute 'shift'
...我知道在这种情况下我使用了错误的班次。我找到的几个解决方案如下:
get previous row's value and calculate new column pandas python
Comparing previous row values in Pandas DataFrame
...但我不确定我在阅读这些内容,以及其中一个如何应用于我的应用程序。我希望更熟练的程序员可以通过一些解释为我指明正确的方向,以便我可以学习。谢谢!
【问题讨论】:
-
您可以使用变量来保留您在
for循环中获得的上一行的值 -
您可以使用移位数据创建新列,然后您将在同一行中拥有两个值。
标签: python python-3.x pandas