자, 이제 이 문장에서 K 직선 합성 함수를 Python 버전으로 쓸 수 있는 방법을 알려드리겠습니다.

저자:작은 꿈, 2019-12-21 09:38:26, 업데이트: 2023-10-17 21:24:05

img

자, 이제 이 문장에서 K 직선 합성 함수를 Python 버전으로 쓸 수 있는 방법을 알려드리겠습니다.

문서를 작성하고, 정책을 사용하는 데에는 종종 비정상적인 K 라인 주기 데이터를 사용합니다. 그러나 거래소, 데이터 소스는 이러한 주기의 데이터를 제공하지 않습니다. 이미 주기가있는 데이터를 사용하여만 합성 할 수 있습니다. 합성 알고리즘에는 이미 자바스크립트 버전이 있습니다.링크이 경우, 우리는 K 라인 합성 알고리즘을 함께 작성할 것입니다.

자바스크립트 버전

  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 
  }

자바스크립트 알고리즘은 파이썬에 대해 실제로 순서대로 번역할 수 있고, 자바스크립트의 내장 함수, 또는 고유한 방법을 만나서 Python에서 대응하는 방법을 찾을 수 있기 때문에 이전하는 것이 더 쉽습니다. 알고리즘의 논리는 완전히 동일합니다. 자바스크립트의 함수 호출입니다.var n = d.getTimezoneOffset()이 문서는 파이썬의 타임 라이브러리를 사용해서n = time.altzone다른 차이는 언어 문법적인 측면에 불과하다. 예를 들어 for 루크의 사용, boolean 값의 차이, 논리와, 논리가 아닌 것, 논리 또는 사용의 차이 등이다.

이 배포된 파이썬 코드는:

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)                                             

테스트

동전 시장 그래프img

4시간 차트를 재검토합니다.img

위의 코드는 학습 참고로만 사용되며, 특정 전략에 사용되면 필요에 따라 수정, 테스트하십시오. 버그나 개선 제안이 있다면 댓글을 달아주셔서 감사합니다 o^_^o


관련

더 많은

설교/upload/asset/30da6ebb64b8003b1686.jpg 아하, 드림드림 선생님은 나보다 더 기술력이 높습니다. 스크린샷은 드림드림 선생님이 참고하도록하십시오.

설교pyresample 함수와 함께 한 줄로 처리합니다.

작은 꿈자, 저는 파이썬을 잘하지 않고 초등학생입니다.

작은 꿈666 공부하고 있습니다.