mardi 28 mai 2019

return values from an elif statement

I am attempting to back test a stock market trading strategy. I would like to buy 100 shares every time cf_net > 0 and close the position when cf_net < 0. This cycle is every 5 min.

I have a pandas data frame called cf_slice which contains ('1. open', cf_now, cf_then, cf_net, long). The data set is 100 length. When cf_net > 0 I would like to add 100 shares to a new data frame called 'current_pos'. Also, I would like to calculate the ('1. open' x current_pos) and insert into a data frame called 'value'. Ideally I would like to count up 100 shares for every true and close the entire position when false. I would like to set this up on the short side but if you can help me with the long side, I can manage the short side.

Open = 282.91, 282.95, 282.87, 282.90, 283.02

cf_net = 1047, -1894, -2214, 3122, 3649

long = True, False, False, True, True

I have tried numpy arrays and iterating through pandas using a for loop. I am able to isolate the long/short data but what I am struggling with is adding to and closing the entire position.

cf_slice = (data.loc[:, ['1. open', 'cf_now', 'cf_then', 'cf_net', 'long']])

current_pos = 0
shares = 0
long_cost = 0
long_credit = 0
short_cost = 0
short_credit = 0
net_profit = 0

for cf in cf_slice.cf_net:
    # open long
    if cf > 0 and current_pos >= 0:
        current_pos += 1
        shares += 100
    # close long
    elif cf < 0 and current_pos > 0:
        current_pos = 0
        shares = 0
    # open short
    elif cf < 0 and current_pos <= 0:
        current_pos -= 1
        shares -= 100
    # close short
    elif cf > 0 and current_pos < 0:
        current_pos = 0
        shares = 0
    print(cf, current_pos, shares)

This code appears to count up and down correctly for the shares and current position. However, how do I incorporate calculating '1. open' x current position?

I need to know the value of the position as the position increases and ultimately closes.data

Aucun commentaire:

Enregistrer un commentaire