2

Team, I have a huge pandas data frame of historical stock OHLC data. I want to compare a particular column value , for e.g. I want to compare today's open with yesterdays open or today's low with yesterdays low ( I have almost 5000 rows to compare )

I tried something like followed, but it gives me just one constant value..

#calculate Low Travel point
df['1back'] = df['low'].iloc[-1] 

any suggestion plese??

2 Answers 2

2

This code:

import pandas as pd


df = pd.DataFrame([
    [10, 102],
    [12, 98],
    [13, 99],
    [15, 94]
],
    columns=['p1', 'p2']
)

print(df.head(10))

df['p1_diff'] = df['p1'].diff(1)
df['p2_diff'] = df['p2'].diff(1)

print(df.head(10))

Should provide the following output:

   p1   p2
0  10  102
1  12   98
2  13   99
3  15   94
   p1   p2  p1_diff  p2_diff
0  10  102      NaN      NaN
1  12   98      2.0     -4.0
2  13   99      1.0      1.0
3  15   94      2.0     -5.0

Process finished with exit code 0

What you look for is diff. Reference here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Rikki! This solves half of my problem. I also need to print the value also... to be clear like this .... p1 p2 0 10 102 1 12 98 2 13 99 3 15 94 p1 p2 p1_last p2_last 0 10 102 NaN NaN 1 12 98 10 102 2 13 99 12 98 3 15 94 13 99
Thanks Rikki! I checked the link you mentioned in reference. The SHIFT works like a charm!!... Thank you very much...
0

calculate EMA/SMA togllers

filter_EMA_TOGGLER_Steady = df['EMA_CROSS'] ==  df['EMA_CROSS'].shift(-1)
filter_EMA_TOGGLER_BUY = (df['EMA_CROSS'] == 'SELL') &  (df['EMA_CROSS'].shift(-1) == 'BUY')
filter_EMA_TOGGLER_SELL = (df['EMA_CROSS'] == 'BUY') &  (df['EMA_CROSS'].shift(-1) == 'SELL')
#SMA 
filter_SMA_TOGGLER_Steady = df['SMA_CROSS'] ==  df['SMA_CROSS'].shift(-1)
filter_SMA_TOGGLER_BUY = (df['SMA_CROSS'] == 'SELL') &  (df['SMA_CROSS'].shift(-1) == 'BUY')
filter_SMA_TOGGLER_SELL = (df['SMA_CROSS'] == 'BUY') &  (df['SMA_CROSS'].shift(-1) == 'SELL')

1 Comment

Please put a data snippet in the question, otherwise it isn't reproducible (minimal reproducible example) and how could anyone other than you answer it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.