I am currently trying to iterate through a dataframe containing MultIndex and calculate a signal that will make the SIGNAL column either 1.0, -1.0 or stay at 0.
Below is an example of how the DataFrame looks. | | | | AAPL| | | | AMZN| |:-|:-------:| :--------:| :----------: |:-:|:-------:| :-----------:|---------: | | SIGNAL| close | BB_LOWER | BB_UPPER | SIGNAL | close | BB_LOWER | BB_UPPER | | | | | | | | | | |0 | 123 | 123 | 123 | 0|123 | 123 | 123 | | 0| 123 | 123 | 123 | 0|123 | 123 | 123 |
This is the code I have been trying to tinker with and create so the output is accurate.
for x in ticker_list:
for index, row in df[x].iterrows():
if row['close'] < row['BB_LOWER']:
df[x, 'SIGNAL'].loc[index] = 1.0
if row['close'] > row['BB_UPPER']:
df[x, 'SIGNAL'].loc[index] = -1.0
df.sort_index(axis=1)
I understand the problem is coming from these sections but I have been unable to come to a solution.
df[x, 'SIGNAL'].loc[index] = 1.0
and
df[x, 'SIGNAL'].loc[index] = -1.0
My output is, every row in the SIGNAL column is changing to -1.0
AAPL | AMZN | ||||||
---|---|---|---|---|---|---|---|
SIGNAL | close | BB_LOWER | BB_UPPER | SIGNAL | close | BB_LOWER | BB_UPPER |
-1 | 123 | 123 | 123 | -1 | 123 | 123 | 123 |
-1 | 123 | 123 | 123 | -1 | 123 | 123 | 123 |
Ideally I would like to keep this DataFrame in MultiIndex form. Any help would be greatly appreciated!