我在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()从前一行中获取“close”价格。当前我得到错误:
AttributeError: 'numpy.float64' object has no attribute 'shift'
…我知道在这种情况下我用错了轮班。我发现的几个解决方案如下:
get previous row's value and calculate new column pandas python
Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?
Comparing previous row values in Pandas DataFrame
…但我不知道我在读什么,以及其中一个如何应用到我的应用程序。我希望一个更熟练的程序员能给我一个正确的方向,给我一些解释,这样我就可以学习了。谢谢!