在编写、使用策略时,经常会使用一些不常用的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.