Reputation: 13
I have the following dataset:
data = {'ROC_9': [0.006250, 0.087230, 0.045028, 0.165738, -0.006993, -0.432736, -0.11162, 0.057466, 0.203138, -0.008234]}
price_data = pd.DataFrame (data)
It is an indicator about a stock price, namely rate of change.
I want to write a code that creates a new feature (column) on the pandas data frame when a current feature on the pandas data frame goes from positive to negative, or vica versa.
It is easier explained through an example: lets use the feature ROC9.
I create a new variable called ROC9_signal and set it equal to 0:
price_data['ROC9_signal'] = 0
When ROC_9 goes from negative to positive, I want to change the ROC9_signal from 0 to 1.
When ROC_9 goes from positive to negative, I want to change the ROC9_signal from 0 to -1.
Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.16 (positive) to -0.006 (negative).
Looking at the data, I would like ROC_9 signal to change from 0 to 1, since the value has gone from -0.11 (negative) to 0.05 (positive).
Looking at the data, I would like ROC9_signal to change from 0 to -1, since the value has gone from 0.20 (positive) to -0.008 (negative).
It is only the row where the change happens that I want to change from 0 to 1 or 0 to -1, the other rows must remain at 0.
I will then apply this same logic to create a momentum10_signal column and a chalkin_money_flow_signal column. Therefore I want a solution that can be applied to different columns and not manually.
Thanks in advance for the help.
This is what the full data looks like:
Upvotes: 0
Views: 170
Reputation: 150785
You can use np.sign
to extract the signs. Something like this:
signs = np.sign(price_data.ROC_9)
price_data['signal'] = np.sign(signs.diff()).fillna(0)
Output:
ROC_9 signal
0 0.006250 0.0
1 0.087230 0.0
2 0.045028 0.0
3 0.165738 0.0
4 -0.006993 -1.0
5 -0.432736 0.0
6 -0.111620 0.0
7 0.057466 1.0
8 0.203138 0.0
9 -0.008234 -1.0
Upvotes: 1