假設我有一個非常大的連續值陣列,表示一段時間內的股票價格。
prices = [22,23,25,23,26,25,28,22] # and so on…
當在任何時間點(在該陣列中的任何索引處)“購買”股票時,我設定了止損和止盈。
buy_index = 2 # buying at 25
stop_loss = 23 # would sell at 23 or below
take_profit = 28 # would sell at 28 or higher
這只是意味著我設定了兩個我要賣出的價格:一個高于買入價,一個低于買入價。
我的問題是:我怎樣才能有效地確定我首先達到的兩個價格中的哪一個?
我嘗試通過以下步驟使用 numpy:
import numpy as np
prices = np.array(prices)
relevant_prices = prices[buy_index:]
stop_loss_index = np.where[relevant_prices < stop_loss][0]
take_profit_index = np.where[relevant_prices < take_profit][0]
…然后比較索引以確定哪個案例首先出現。這很有效,但是在完成數百萬次時非常慢。
我意識到我的代碼每次確定索引時都會遍歷整個資料集 - 必須有更好的方法來做到這一點。
uj5u.com熱心網友回復:
使用np.argmax
因為對于布爾條件,argmax 不會在整個陣列上回圈,即當它找到 True 時會短路。
代碼
使用 argmax:
relevant_prices = prices[buy_index:]
stop_loss_index = np.argmax(relevant_prices <= stop_loss)
take_profit_index = np.argmax(relevant_prices >= take_profit)
…然后比較索引以確定哪個案例先出現
演示布爾陣列上的 argmax 短路
import timeit
print('Million Point Array of False')
arr = np.full(1000000, False, dtype=bool)
%timeit arr.argmax()
print('\nTrue at beginning of Array of False')
arr[0] = True
%timeit arr.argmax()
輸出
注意 52 X 在第 2 種情況下加速,其中 True 位于開頭
Million Point Array of False
56.9 μs ± 1.57 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
True at beginning of Array of False
1.08 μs ± 175 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
?
uj5u.com熱心網友回復:
我不完全確定你想做什么,但我認為以下應該可行:
stop_loss_index = -1
take_profit_index = -1
for i, price in enumerate(prices[buy_index:]):
if price <= stop_loss: stop_loss_index = i
elif price >= take_profit: take_profit_index = i
如果沒有找到,這應該給出索引或 -1。
uj5u.com熱心網友回復:
如果您想快速預先計算答案,以便buy_index高效地運行多個不同的查詢,請從頭到尾遍歷,并保留一棵樹,其中包含您在回溯時(及時)看到的值。使用每個子樹中看到的最低索引和相應值存盤和更新裝飾。(對于右子樹,這將是時間上最近的較高值;對于左子樹,這將是時間上最近的較低值。)
當您遍歷時,對于buy_index您正在預先計算的每個值,在樹中查找為相關值存盤的索引(從您的描述中不清楚您是否想要在時間上也最接近的確切值或最接近的值)并存盤它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/498186.html
