Search code examples
pythonpandasmatplotlibquantitative-financealgorithmic-trading

Developing trading strategy using Pandas and Matplotlib


I am trying to identify a bullish point, based upon the following formula:

Bullish  Bar  =  Today’s  Low  <  Lowest  (Low  ,  13  Days)  AND  Today’s  Close  >  (((Todays  High  –  Todays  Low)  /  2)  +  Today  Low) 

Additionally, I want to calculate the average 2 day returns of a stock for a given time period ( say, 2010 to 2017 ). For example:

( Close ( Day 2 ) - Open ( Day 1 ) )/ Open ( Day1 ) 

I am using Pandas to source the data. This is how the data frame looks like:

              Date   Close      High       Low    Open     Volume
Symbol                                                           
SPY     2010-01-01  111.44  112.8000  111.3900  112.77          0
SPY     2010-01-04  113.33  113.3900  111.5100  112.37  118944600
SPY     2010-01-05  113.63  113.6800  112.8500  113.26  111579900

My objective is to create a separate column where, along side the date, the bullish point is indicated, so that I can plot it with a green arrow.

Currently, I am converting everything to lists, and am using the indices of the lists to calculate the returns; however, it is pretty tedious.

Is there a way to get this done in a simpler way?


Solution

  • If your dataframe is called df, and you want your result to be in a new column Return, you can use the following code to calculate the return:

    df['Return'] = (df.Close.shift(2) - df.Open.shift(1)) / df.Open.shift(1)
    

    To calculate the bullish signal, you can use the following method:

        df['bullishSignal'] = (df.Low < df.Low.shift(1).rolling(13).min()) & 
                                  (df.Close > ((df.High - df.Low) / 2 + df.Low))