Objective is to replace a for
loop with dataframe.apply()
.
Below is the code for the for
loop:
#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
I'm unable to get a correct solution.
Question: How do I take care of setting up the toggle (cash indicator) and referencing the next row element?
df
is the complete dataset, and buy_data
is the result which I want
buy_data = df.apply(lambda x : (x ['Close'+ 1]) if (x ['Close'] > x ['ma']
and cash ==1) else 0)
Key Errors etc.