我有一个带有标准库存数据(开盘,高,低,收盘,成交量)的数据框
我正在尝试模拟尾随止损,而不使用循环。
现在的代码如下:
# i is the index at which we take a trade in
# and I want to go through the rest of the data frame to see if it would
# hit a trailing stop
if direction == +1: # only long trades in this example
peg_price = entry_price * (1 - peg_offset) # peg_offset is the gap between the trade and the stop (0.2 in testing)
for j in range(i + 1, len(df)):
low = df['low'][j]
if low <= peg_price:
date = df['date'][i]
trade_date.append(df['date'][i])
trade_exit_date.append(df['date'][j])
trade_price.append(entry_price)
trade_exit.append(peg_price)
trade_profit.append(peg_price - entry_price)
skip_to = j + 1
else:
low = df['high'][j]
peg_price = max(high * (1 - peg_offset), peg_price)
因此,以伪代码表示的逻辑流为:
// we have a trade at index 'i'
stop_value = df['stop'][i] * stop_offset (for example set the stop 20% lower)
for j in df[i+1:]:
// did we hit the stop
if value['low'][j] <= stop_value:
break, recover value of j and stop_value
else:
stop_value = max(value['high'][j] * stop_offset, stop_value)
如何在没有循环的情况下实现熊猫式的操作?