簡體   English   中英

大於或等於當前值 1.2 倍的前一個值的索引

[英]Index of the previous value that is greater than or equal 1.2 times the current value

對於任何給定日期,我試圖找到比當前close價高 1.2 倍的前一個close價。 我做了一個循環來檢查每一行。 但是,它效率不高。 運行時間為 45 秒。 如何使我的代碼更有效地處理比這大得多的數據集?

數據集 - TSLATSLA Daily 5Y Stock Yahoo

df = pd.read_csv(os.getcwd()+"\\TSLA.csv")

# Slicing the dataset
df2 = df[['Date', 'Close']]

irange = np.arange(1, len(df))

for i in irange:
      # Dicing first i rows
      df3 = df2.head(i)
      # Set the target close value that is 1.2x the current close value
      targetValue = 1.2 * df3['Close'].tail(1).values[0]

      # Check the last 200 days
      df4 = df3.tail(200)
      df4.set_index('Date', inplace=True)

      # Save all the target values in a list
      req = df4[df4['Close'] > targetValue]
      try:
          lent = (req.index.tolist()[-1])
      except:
          lent = str(9999999)

      # Save the last value to the main dataframe
      df.at[i,'last_time'] = lent

df.tail(20)

你正在做 O(N^3) 和一些不必要的數據副本。 試試這個 O(NlogN) 方式

df = pd.read_csv("D:\\TSLA.csv")
stack,cnt=[],0
def OnePointTwoTimesLarger(row):
    #cnt is not really needed by what you aksed. But it is usually a better to return the data row you need, instead of just returning the value
    global stack,cnt
    c=row['Close']
    while stack and stack[-1][1]<=c:
        stack.pop()
    stack.append([row['Date'],c])
    cnt+=1
    left,right=0,len(stack)-1
    while left<right-3:
        mid=(left+right)//2
        if stack[mid][1]>1.2*c:
            left=mid
        else:
            right=mid
    for e in stack[left:right+1][::-1]:
        if e[1]>1.2*c:
            return e[0]
    return 999999
df['last_time']=df.apply(OnePointTwoTimesLarger, axis=1)
df.tail(60)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM