0

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.

AnJ
  • 23
  • 3
  • 1
    `apply` (in this case you seem to still be thinking in terms of `axis=1` **is** still a loop. The goal should be to avoid this all together. Please provide a [mcve] with sample data and your expected output. However, I can tell you your result is going to be to use `np.where` with a combintion of `DataFrame.shift`. See: https://stackoverflow.com/questions/19913659/pandas-conditional-creation-of-a-series-dataframe-column for how to implement if-else logic properly. – ALollz Jun 15 '19 at 16:59
  • Thanks @ALollz, can you help me in both ways i.e. by axis = 1 via apply and via np.where. – AnJ Jun 16 '19 at 04:25

0 Answers0