As pandas is very slow trying to use Polars. I was able to calculate the SMA and MACD values to the data frame( Not sure the values are correct for now). How can I convert the said code to use with Polars.
def implement_macd_strategy(df):
buy_price = []
sell_price = []
macd_signal = []
signal = 0
for i in range(len(df)):
if df['MACD_8_21_5'][i] > df['MACDs_8_21_5'][i]:
if signal != 1:
buy_price.append(df['Close'][i])
sell_price.append(np.nan)
signal = 1
macd_signal.append(signal)
else:
buy_price.append(np.nan)
sell_price.append(np.nan)
macd_signal.append(0)
elif df['MACD_8_21_5'][i] < df['MACDs_8_21_5'][i]:
if signal != -1:
buy_price.append(np.nan)
sell_price.append(df['Close'][i])
signal = -1
macd_signal.append(signal)
else:
buy_price.append(np.nan)
sell_price.append(np.nan)
macd_signal.append(0)
else:
buy_price.append(np.nan)
sell_price.append(np.nan)
macd_signal.append(0)
df['buy_price MACD'] = buy_price
df['sell_price MACD'] = sell_price
df['signal MACD'] = signal
return df
it is better in such cases to give some input and desired output for testing purposes. Can you try this and say if it is ok for you: