如何根据条件创建固定的新 numpy 数组值 - 股票价格
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]])
数组中的每一列都是个股价格,当价格在take_profit和stop_loss之间时,交易开始,价值保持不变。如果价格高于或等于 take_profit,则交易状态为“TP”,当价格低于或等于 stop_loss 时,该列的其余部分的状态为“SL” .
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],])
谁能帮我解决这个问题?该数组有 3000 行长。我的方法如下:
# My approach:
for value in input_array:
if value > take_profit:
value == "TP"
if value < stop_loss:
value == "SL"
else:
value == value
这没用,所以试过了
output_array = np.where(input_array> take_profit , "TP", input_array)
问题是输出将初始更改为“TP”,但随后会在“SL”和价格返回之间的数字之间恢复。一旦价格改变状态,交易就会关闭,因此对于列中下降的其余值,它应该保持固定直到结束!
让我们试试 np.select
,用 mask
和 fillna
pandas
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)