手把手教你写一个Python版的K线合成函数

在编写、使用策略时,经常会使用一些不常用的K线周期数据。然而交易所、数据源又没有提供这些周期的数据。只能通过使用已有周期的数据进行合成。合成算法已经有一个JavaScript版本了(链接),其实移植一段JavaScript代码为Python版本很简单。接下来我们一起写一个Python版本的K线合成算法。

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

}

有JavaScript算法,对于Python其实逐行翻译移植就可以了,遇到JavaScript的内置函数,或者固有方法,对应的去Python中查找对应的方法即可,所以移植还是比较容易的。

算法逻辑完全一模一样,只是JavaScript的函数调用var n = d.getTimezoneOffset(),移植到Python时,使用Python的time库中的n = time.altzone代替。其它差异仅仅是语言语法方面的了(例如for循环的使用,布尔值的差别,逻辑与、逻辑非、逻辑或的使用差别等…)。

移植后的Python代码:

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)

测试

火币行情图表

回测合成4小时图表

以上代码仅作为学习参考使用,如果用于具体策略中,请根据需求修改、测试。

如有BUG或者改进建议,欢迎留言,十分感谢 o^_^o

python k线合成_手把手教你写一个Python版的K线合成函数相关推荐

  1. python手势识别控制幻灯片_手把手教你如何实现Python手势识别与控制(含代码及动图)...

    Python手势识别与控制 概述 本文中的手势识别与控制功能主要采用 OpenCV 库实现, OpenCV是一个基于BSD许可(开源)发行的跨平台计算机视觉库, 可以运行在Linux, Windows ...

  2. python做滴滴打车软件_手把手教你写滴滴打车 APP

    /** * 找到图像中的证件区域 * 在RGB色彩空间求取驾驶员证件的图像梯度,之后在此图像上做二值化,从而通过轮廓(contour)发现与面积大小过滤得到证件区域 * author:Tantuo 8 ...

  3. python量化策略代码_手把手教你用三行python 代码做一个动量策略「量化投资系列」...

    动量策略是右侧交易里最常见的,背后的逻辑是就现在涨的,后市还会涨,动量具有惯性的意思. 首先加载原始数据,我们用天的收盘价即可,按统一转为收益率.因为点位本身不重要,我们最后只关心变化率. 以沪深30 ...

  4. 字符动图_手把手教你做一个python+matplotlib的炫酷的数据可视化动图

    1.数据可视化动图,是数据可视化的高级显示,最近很流行. 2.比如下面将告诉你如何制作一个如下的数据可视化动图. 3.例: 3.1 准备一组数据,虚拟的csv资料,对应关系如下 4个项目:namegr ...

  5. python制作数据增长动图_手把手教你做一个python+matplotlib的炫酷的数据可视化动图...

    #第1步:导出模块,固定 importpandas as pdimportmatplotlib.pyplot as pltimportmatplotlib.ticker as tickerimport ...

  6. python量化投资代码_手把手教你用三行python 代码做一个动量策略「量化投资系列」...

    动量策略是右侧交易里最常见的,背后的逻辑是就现在涨的,后市还会涨,动量具有惯性的意思. 首先加载原始数据,我们用天的收盘价即可,按统一转为收益率.因为点位本身不重要,我们最后只关心变化率. 以沪深30 ...

  7. java编写一个框架_手把手教你写一个基于 RxJava 的扩展框架

    背景 现在 RxJava 在 Android 开发中可谓时炽手可热,其受欢迎程度不言而喻,也因此在 github 上出现了一系列的基于 RxJava 的框架,如 RxBinding.RxPermiss ...

  8. python老师 课时费_花10分钟写一个Python脚本,搞定了初中老师一下午的工作

    有个朋友是一个初中老师.嗯,教学行政两手抓的那种初中老师. 一天晚上突然微信问我,怎么把图片转成PDF.懵了一下,这个直接打印成PDF不就可以了? 遂告诉他,结果感觉两个人不是一个世界的: 好不容易教 ...

  9. 软件_手把手教vscode配置c++,python开发环境

    原创:软件_手把手教vscode配置c++,python开发环境 之前主用Python作为项目开发语言,将项目迁移到arm边缘盒子上后发现arm的cpu不给力,软件速度低于预期,所以计划将部分程序改为 ...

最新文章

  1. Linux中errno使用
  2. Windows Vista和XP比较
  3. 操作文件方法简单总结(File,Directory,StreamReader,StreamWrite ) - Zery-zhang
  4. MULE ESB环境搭建和例子(通过装插件的方式)
  5. thinkphp5 composer
  6. 创业者谈:畏惧失败,但也要拥抱失败
  7. Swift - 05 - 数值型字面量
  8. JS学习总结(1)——基础知识
  9. CAN总线知识点梳理
  10. Can‘t connect to any repository: 的解决办法, 在Push代码,提交代码到代码仓库的时候,提示不能连接到该代码仓库
  11. vue 打开一个iframe_vue嵌套iframe一系列问题
  12. #章节四:input()函数
  13. ToB产品如何做好产品推广:找到机会点
  14. 常见的状态码及错误信息提示
  15. 关于720p和1080p观看距离和效果
  16. 视频惠民发布平台助力智慧城市升级
  17. 嵌入式软件工程师岗位,要具备哪些能力??
  18. Java哈希表及其应用
  19. 如何用UE4制作2D游戏文档(二)——资源篇
  20. java基础数据类型和运算符

热门文章

  1. linux 好用的命令积累
  2. 逆序数 UVALive 6508 Permutation Graphs
  3. 用定时中断来接收红外遥控信号
  4. 【DONE】dbeaver不会用,请教!!!
  5. 企业CIO如何让IT部门成为价值中心
  6. 【BUG解决】使用body-parser失效的实例解决
  7. LongestPalindromeSequence
  8. Linux fedora35安装crontab定时任务工具
  9. ansible roles和django项目的整合
  10. flume数据采集:js埋点