Một tay dạy bạn viết một hàm tổng hợp K-line trong Python

Tác giả:Giấc mơ nhỏ, Tạo: 2019-12-21 09:38:26, Cập nhật: 2023-10-17 21:24:05

img

Một tay dạy bạn viết một hàm tổng hợp K-line trong Python

Trong việc viết, sử dụng các chính sách, thường sử dụng một số dữ liệu chu kỳ K không phổ biến. Tuy nhiên, các sàn giao dịch, nguồn dữ liệu không cung cấp dữ liệu về các chu kỳ này. Chỉ có thể tổng hợp bằng cách sử dụng dữ liệu đã có chu kỳ.Liên kếtSau đó, chúng ta cùng nhau viết một thuật toán tổng hợp K-line cho phiên bản Python.

Phiên bản JavaScript

  function GetNewCycleRecords (sourceRecords, targetCycle) {    // K线合成函数
      var ret = []
      
      // 首先获取源K线数据的周期
      if (!sourceRecords || sourceRecords.length < 2) {
          return null
      }
      var sourceLen = sourceRecords.length
      var sourceCycle = sourceRecords[sourceLen - 1].Time - sourceRecords[sourceLen - 2].Time

      if (targetCycle % sourceCycle != 0) {
          Log("targetCycle:", targetCycle)
          Log("sourceCycle:", sourceCycle)
          throw "targetCycle is not an integral multiple of sourceCycle."
      }

      if ((1000 * 60 * 60) % targetCycle != 0 && (1000 * 60 * 60 * 24) % targetCycle != 0) {
          Log("targetCycle:", targetCycle)
          Log("sourceCycle:", sourceCycle)
          Log((1000 * 60 * 60) % targetCycle, (1000 * 60 * 60 * 24) % targetCycle)
          throw "targetCycle cannot complete the cycle."
      }

      var multiple = targetCycle / sourceCycle


      var isBegin = false 
      var count = 0
      var high = 0 
      var low = 0 
      var open = 0
      var close = 0 
      var time = 0
      var vol = 0
      for (var i = 0 ; i < sourceLen ; i++) {
          // 获取 时区偏移数值
          var d = new Date()
          var n = d.getTimezoneOffset()

          if (((1000 * 60 * 60 * 24) - sourceRecords[i].Time % (1000 * 60 * 60 * 24) + (n * 1000 * 60)) % targetCycle == 0) {
              isBegin = true
          }

          if (isBegin) {
              if (count == 0) {
                  high = sourceRecords[i].High
                  low = sourceRecords[i].Low
                  open = sourceRecords[i].Open
                  close = sourceRecords[i].Close
                  time = sourceRecords[i].Time
                  vol = sourceRecords[i].Volume

                  count++
              } else if (count < multiple) {
                  high = Math.max(high, sourceRecords[i].High)
                  low = Math.min(low, sourceRecords[i].Low)
                  close = sourceRecords[i].Close
                  vol += sourceRecords[i].Volume

                  count++
              }

              if (count == multiple || i == sourceLen - 1) {
                  ret.push({
                      High : high,
                      Low : low,
                      Open : open,
                      Close : close,
                      Time : time,
                      Volume : vol,
                  })
                  count = 0
              }
          }
      }

      return ret 
  }

Có các thuật toán JavaScript, cho Python thực sự có thể được chuyển dịch theo dòng, gặp phải các hàm tích hợp của JavaScript, hoặc phương pháp vốn có, tương ứng để tìm kiếm phương pháp tương ứng trong Python, vì vậy việc chuyển đổi vẫn còn dễ dàng hơn. Các thuật toán logic là hoàn toàn giống nhau, chỉ cần gọi hàm trong JavaScriptvar n = d.getTimezoneOffset()Khi chuyển sang Python, sử dụng Python time library.n = time.altzoneThay vào đó. Những khác biệt khác chỉ là về ngữ pháp ngôn ngữ (ví dụ: sử dụng vòng lặp for, sự khác biệt của giá trị boolean, sự khác biệt giữa logic và, logic không, logic hoặc sử dụng của...)

Mã Python sau khi được chuyển:

import time

def GetNewCycleRecords(sourceRecords, targetCycle):
    ret = []

    # 首先获取源K线数据的周期
    if not sourceRecords or len(sourceRecords) < 2 : 
        return None

    sourceLen = len(sourceRecords)
    sourceCycle = sourceRecords[-1]["Time"] - sourceRecords[-2]["Time"]

    if targetCycle % sourceCycle != 0 :
        Log("targetCycle:", targetCycle)
        Log("sourceCycle:", sourceCycle)
        raise "targetCycle is not an integral multiple of sourceCycle."

    if (1000 * 60 * 60) % targetCycle != 0 and (1000 * 60 * 60 * 24) % targetCycle != 0 : 
        Log("targetCycle:", targetCycle)
        Log("sourceCycle:", sourceCycle)
        Log((1000 * 60 * 60) % targetCycle, (1000 * 60 * 60 * 24) % targetCycle)
        raise "targetCycle cannot complete the cycle."
    
    multiple = targetCycle / sourceCycle

    isBegin = False
    count = 0 
    barHigh = 0 
    barLow = 0 
    barOpen = 0
    barClose = 0 
    barTime = 0 
    barVol = 0 

    for i in range(sourceLen) : 
        # 获取时区偏移数值
        n = time.altzone        

        if ((1000 * 60 * 60 * 24) - (sourceRecords[i]["Time"] * 1000) % (1000 * 60 * 60 * 24) + (n * 1000)) % targetCycle == 0 :
            isBegin = True

        if isBegin : 
            if count == 0 : 
                barHigh = sourceRecords[i]["High"]
                barLow = sourceRecords[i]["Low"]
                barOpen = sourceRecords[i]["Open"]
                barClose = sourceRecords[i]["Close"]
                barTime = sourceRecords[i]["Time"]
                barVol = sourceRecords[i]["Volume"]
                count += 1
            elif count < multiple : 
                barHigh = max(barHigh, sourceRecords[i]["High"])
                barLow = min(barLow, sourceRecords[i]["Low"])
                barClose = sourceRecords[i]["Close"]
                barVol += sourceRecords[i]["Volume"]
                count += 1

            if count == multiple or i == sourceLen - 1 :
                ret.append({
                    "High" : barHigh,
                    "Low" : barLow,
                    "Open" : barOpen,
                    "Close" : barClose,
                    "Time" : barTime,
                    "Volume" : barVol,
                })
                count = 0
    
    return ret 

# 测试
def main():
    while True:
        r = exchange.GetRecords()
        r2 = GetNewCycleRecords(r, 1000 * 60 * 60 * 4)      

        ext.PlotRecords(r2, "r2")                                 
        Sleep(1000)                                             

Kiểm tra

Biểu đồ thị trường đồng xuimg

Phân tích lại biểu đồ 4 giờimg

Mã trên chỉ được sử dụng như một tài liệu tham khảo học tập, nếu được sử dụng trong một chiến lược cụ thể, hãy sửa đổi, thử nghiệm theo nhu cầu. Nếu bạn có bất kỳ lỗi hoặc đề xuất cải tiến nào, vui lòng để ý, cảm ơn rất nhiều o^_^o


Có liên quan

Thêm nữa

bài giảng/upload/asset/30da6ebb64b8003b1686.jpg Ồ, giáo viên Dream Dream có kỹ thuật cao hơn tôi.

bài giảngMột dòng được thực hiện bằng hàm pyresample.

Giấc mơ nhỏNhìn chung, tôi không biết Python, tôi chỉ là một học viên mới.

Giấc mơ nhỏ666 đang học.