Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

pandas - How to create fixed new numpy array values based on conditions - stock prices

input_array =
       ([[13,  93,  47,  857],
         [16,  91,  55,  800], 
         [18, 105,  85,  821],
         [17, 106,  89,  890],
         [19, 105,  60,  961],
         [20, 106,  41,  988],
         [21, 107,  45,  999],])

take_profit =
       ([[15,  105,  90,  960]])

stop_loss =
       ([[10,   92,  45,  750]])

The each column in array are individual stock prices, when price exists between take_profit and stop_loss the trade is open and the value remains unchanged. If the price goes above or equal to the take_profit the status of the trade is "TP" and when the price is below or equal to the stop_loss the status is "SL" for the remainder of the column.

desired_output_array = 
        ([[13,  93,  47,  857],
         [TP,   SL,  55,  800],
         [TP,   SL,  85,  821],
         [TP,   SL,  89,  890],
         [TP,   SL,  60,  TP],
         [TP,   SL,  SL,  TP],
         [TP,   SL,  SL,  TP],])

Can anyone help me solve this problem? The array is 3000 rows long. My approach was the following:

# My approach:

for value in input_array:
    if value > take_profit:
        value == "TP"
    if value < stop_loss:
        value == "SL"
    else:
        value == value

This didn't work, so tried

output_array = np.where(input_array> take_profit , "TP", input_array)

The problem with this is that the output will initial change to "TP" but then revert between "SL" and the numbers between should price come back. Once the price changes status the trade is closed so for the rest of the values going down in the column it should remain fixed till the end!

question from:https://stackoverflow.com/questions/65878539/how-to-create-fixed-new-numpy-array-values-based-on-conditions-stock-prices

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let us try np.select , the pass to pandas with mask and fillna

cond1 = (input_array > take_profit)
cond2 = (input_array < stop_loss)
s = pd.DataFrame(np.select([cond1,cond2],['TP',"SL"],default=input_array))

out_putary = s.mask(s.isin(['TP',"SL"]).cumsum()>0).fillna(s.where(s.isin(['TP',"SL"]).cumsum()>0).bfill().iloc[0]).values


out_putary
Out[65]: 
array([['13', '93', '47', '857'],
       ['TP', 'SL', '55', '800'],
       ['TP', 'SL', '85', '821'],
       ['TP', 'SL', '89', '890'],
       ['TP', 'SL', '60', 'TP'],
       ['TP', 'SL', 'SL', 'TP'],
       ['TP', 'SL', 'SL', 'TP']], dtype=object)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...