My Problem
I have written some code that joins up 4 independent technical signals (Buy, Sell, Short and Cover) each in their own column into one column. The signals can only be joined up in a particular order e.g. if you buy a stock in one time period then in the next time period the only possible actions are to sell it or to short it and you can't cover it.
The code works exactly how it should but the problem I have is that the loops make the code very slow, and I want to make it faster and more efficient.
Current Working Slow Code
import numpy as np
import pandas as pd
csv1 = pd.read_csv('signals.csv', delimiter = ',')
df = pd.DataFrame(csv1)
df.loc[df.index[0], 'Signal'] = "Buy"
for x in range(1,len(df.index)):
if df["Signal"].iloc[x-1] == "Buy" and (df["Sell"].iloc[x] == "Sell" or df["Short"].iloc[x] == "Short"):
df["Signal"].iloc[x] = df["Sell"].iloc[x] + df["Short"].iloc[x]
elif df["Signal"].iloc[x-1] == "Short" and (df["Buy"].iloc[x] == "Buy" or df["Cover"].iloc[x] == "Cover"):
df["Signal"].iloc[x] = df["Buy"].iloc[x] + str(df["Cover"].iloc[x])
elif df["Signal"].iloc[x-1] == "Cover" and (df["Buy"].iloc[x] == "Buy" or df["Short"].iloc[x] == "Short"):
df["Signal"].iloc[x] = df["Buy"].iloc[x] + df["Short"].iloc[x]
elif df["Signal"].iloc[x-1] == "Sell" and (df["Buy"].iloc[x] == "Buy" or df["Short"].iloc[x] == "Short"):
df["Signal"].iloc[x] = df["Buy"].iloc[x] + df["Short"].iloc[x]
else:
df["Signal"].iloc[x] = df["Signal"].iloc[x-1]
df
Expected Input
Short,Cover,Buy,Sell
,,,
Short,,,
,,,
,Cover,,
,,,
,,,
,,Buy,
,,,
,,,
,,,Sell
,,,
,,,
,,Buy,
,,,
,,,Sell
,,,
Expected Output
Short,Cover,Buy,Sell,Signal
,,,,Buy
Short,,,,Short
,,,,Short
,Cover,,,Cover
,,,,Cover
,,,,Cover
,,Buy,,Buy
,,,,Buy
,,,,Buy
,,,Sell,Sell
,,,,Sell
,,,,Sell
,,Buy,,Buy
,,,,Buy
,,,Sell,Sell
,,,,Sell
Any idea how i could do it?
Cheers!