Pairs Trading Strategy Pandas Update Position and Quantity Based on Price

by Transcending   Last Updated June 30, 2020 03:26 AM - source

I am trying to run a trading pairs trading strategy and I am having trouble indicating updating some columns to generate. Let's say I have 2 price columns (Stock A Price, Stock B price) of 2 different stocks. Let the strategy be long Stock A if Stock A is trading less than B and vice versa (and hold if they are the same or they do not cross). I want to build two other columns: Stock A position, Stock B position,

I want to update the first row for the positions column as follows as an initial step:

if df['Stock A Price'][0] > df['Stock B Price'][0]:
    # update df['Stock A Price'][0] == 'LONG'
    # update df['Stock B Price'][0] == 'SHORT'

Next, I'd like keep the rest of the df['Stock A Position'] and df['Stock A Position'] columns to be HOLD only until the prices cross each other. For instance, if the first 5 rows of Stock A are 5,6,7,8,10 and the first 5 rows of Stock B are 7,7,7,6,4 then the first 5 rows of df['Stock A Position'] should read LONG, HOLD, HOLD, SHORT, HOLD and the first 5 rows of df['Stock B Position'] should read SHORT, HOLD, HOLD, LONG, HOLD.

I guess if I have the first columns of positions, such as df['Stock A Position'] the other can be easily retrieved by a simple if statement:

for row in df['Stock A Position']:

    if row == 'LONG':
        df['Stock B Position'][row] = 'SHORT'
    elif row == 'SHORT':
        df['Stock B Position'][row] = 'LONG'
        df['Stock B Position'][row] = 'HOLD

Please let me how to do this efficiently and be able to handle a large DataFrame. Thanks for the help.

Related Questions

Stop loss and Take profit question in Quantopian

Updated June 04, 2019 21:26 PM

Couldn't understand the role of vars() in the code

Updated April 02, 2019 04:26 AM

Duplicate the rows in pandas data frame

Updated January 29, 2018 01:26 AM