目标是将for
循环替换为dataframe.apply()
。
下面是for
循环的代码:
#ma is moving average of a number of days say 100
#days is the number of days for which stock data is available
for d in range(ma-1, days):
# Buy if stock price > Moving average & if not bought yet
if df['Close'] > df['ma'] and cash == 1:
buyPrice = closingprices[d + 1] #buy next day
buy_data.append(buyPrice)
cash = 0
stock = 1
if df['Close'] < df['ma'] and stock == 1:
sellPrice = closingprices[d + 1]
sell_data.append(sellPrice)
cash = 1
stock = 0
我无法找到正确的解决方案。
问题:我该如何设置拨动开关(现金指示器)并引用下一行元素?
df
是完整的数据集,而buy_data
是我想要的结果
buy_data = df.apply(lambda x : (x ['Close'+ 1]) if (x ['Close'] > x ['ma']
and cash ==1) else 0)
主要错误等