golang金融市场技术分析与交易策略开发插件库techan的使用

Golang金融市场技术分析与交易策略开发插件库techan的使用

Techan简介

Techan是一个用于Go语言的技术分析库!它提供了一套工具和框架来分析金融数据并做出交易决策。

主要功能

  • 基础和高级技术分析指标
  • 盈亏和交易分析
  • 策略构建

安装

$ go get github.com/sdcoffey/techan

快速入门

series := techan.NewTimeSeries()

// 从您喜欢的交易所获取这些数据
dataset := [][]string{
    // 时间戳, 开盘价, 收盘价, 最高价, 最低价, 成交量
    {"1234567", "1", "2", "3", "5", "6"},
}

for _, datum := range dataset {
    start, _ := strconv.ParseInt(datum[0], 10, 64)
    period := techan.NewTimePeriod(time.Unix(start, 0), time.Hour*24)

    candle := techan.NewCandle(period)
    candle.OpenPrice = big.NewFromString(datum[1])
    candle.ClosePrice = big.NewFromString(datum[2])
    candle.MaxPrice = big.NewFromString(datum[3])
    candle.MinPrice = big.NewFromString(datum[4])

    series.AddCandle(candle)
}

closePrices := techan.NewClosePriceIndicator(series)
movingAverage := techan.NewEMAIndicator(closePrices, 10) // 创建一个窗口为10的指数移动平均线

fmt.Println(movingAverage.Calculate(0).FormattedString(2))

创建交易策略

indicator := techan.NewClosePriceIndicator(series)

// 在此对象上记录交易
record := techan.NewTradingRecord()

entryConstant := techan.NewConstantIndicator(30)
exitConstant := techan.NewConstantIndicator(10)

// 当价格EMA移动到30以上且当前持仓为新时满足条件
entryRule := techan.And(
    techan.NewCrossUpIndicatorRule(entryConstant, indicator),
    techan.PositionNewRule{})
    
// 当价格EMA移动到10以下且当前持仓为开仓时满足条件
exitRule := techan.And(
    techan.NewCrossDownIndicatorRule(indicator, exitConstant),
    techan.PositionOpenRule{})

strategy := techan.RuleStrategy{
    UnstablePeriod: 10, // 在此周期之前ShouldEnter和ShouldExit将始终返回false
    EntryRule:      entryRule,
    ExitRule:       exitRule,
}

strategy.ShouldEnter(0, record) // 返回false

项目支持

您是否在生产中使用techan?您可以通过给我买杯咖啡来赞助它的开发!☕

ETH: 0x2D9d3A1c16F118A3a59d0e446d574e1F01F62949

致谢

Techan深受优秀的ta4j影响。该库中的许多想法和框架都归功于他们在那里所做的出色工作。

许可证

Techan根据MIT许可证发布。


更多关于golang金融市场技术分析与交易策略开发插件库techan的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang金融市场技术分析与交易策略开发插件库techan的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang金融市场技术分析与交易策略开发:techan库使用指南

techan是一个用于金融市场技术分析和交易策略开发的Go语言库,它提供了丰富的技术指标计算和交易策略构建功能。下面我将详细介绍techan的使用方法,并提供示例代码。

1. 安装techan

首先安装techan库:

go get github.com/sdcoffey/techan

2. 基本数据结构

时间序列(TimeSeries)

package main

import (
	"fmt"
	"time"
	
	"github.com/sdcoffey/techan"
)

func main() {
	// 创建时间序列
	series := techan.NewTimeSeries()
	
	// 添加交易记录
	now := time.Now()
	series.AddCandle(techan.NewCandle(techan.NewTimePeriod(now, time.Minute*5)))
	series.LastCandle().AddTrade(100.0, 1.0)
	series.LastCandle().ClosePrice = 100.5
	series.LastCandle().Volume = 1.0
	
	fmt.Printf("最新收盘价: %.2f\n", series.LastCandle().ClosePrice)
}

3. 常用技术指标计算

移动平均线(MA)

func calculateMA() {
	series := createSampleSeries() // 假设这是一个创建示例数据的方法
	
	// 计算5周期简单移动平均线(SMA)
	closePrices := techan.NewClosePriceIndicator(series)
	sma := techan.NewSimpleMovingAverage(closePrices, 5)
	
	fmt.Printf("5周期SMA: %.2f\n", sma.Calculate(series.LastIndex()))
	
	// 计算指数移动平均线(EMA)
	ema := techan.NewEMAIndicator(closePrices, 5)
	fmt.Printf("5周期EMA: %.2f\n", ema.Calculate(series.LastIndex()))
}

相对强弱指数(RSI)

func calculateRSI() {
	series := createSampleSeries()
	closePrices := techan.NewClosePriceIndicator(series)
	
	// 计算14周期RSI
	rsi := techan.NewRelativeStrengthIndexIndicator(closePrices, 14)
	fmt.Printf("14周期RSI: %.2f\n", rsi.Calculate(series.LastIndex()))
}

布林带(Bollinger Bands)

func calculateBollingerBands() {
	series := createSampleSeries()
	closePrices := techan.NewClosePriceIndicator(series)
	
	// 计算20周期布林带(2倍标准差)
	bb := techan.NewBollingerBandsIndicator(closePrices, 20, 2.0)
	
	fmt.Printf("中轨: %.2f\n", bb.MiddleBand().Calculate(series.LastIndex()))
	fmt.Printf("上轨: %.2f\n", bb.UpperBand().Calculate(series.LastIndex()))
	fmt.Printf("下轨: %.2f\n", bb.LowerBand().Calculate(series.LastIndex()))
}

4. 交易策略开发

简单双均线策略

func dualMAStrategy() {
	series := createSampleSeries()
	closePrices := techan.NewClosePriceIndicator(series)
	
	// 定义短期和长期均线
	shortMA := techan.NewSimpleMovingAverage(closePrices, 5)
	longMA := techan.NewSimpleMovingAverage(closePrices, 20)
	
	// 创建交易规则
	entryRule := techan.And(
		techan.NewCrossUpIndicatorRule(shortMA, longMA),
		techan.PositionNewRule{},
	)
	
	exitRule := techan.And(
		techan.NewCrossDownIndicatorRule(shortMA, longMA),
		techan.PositionOpenRule{},
	)
	
	// 创建策略
	strategy := techan.NewStrategy(entryRule, exitRule)
	
	// 模拟交易
	tradingRecord := techan.NewTradingRecord()
	for i := 0; i < series.LastIndex(); i++ {
		if strategy.ShouldEnter(i, tradingRecord) {
			fmt.Printf("在%d位置买入\n", i)
			tradingRecord.Operate(techan.Order{
				Side:          techan.BUY,
				Security:       "AAPL",
				Price:          closePrices.Calculate(i),
				Amount:         1,
				ExecutionTime:  series.Candles[i].Period.Start,
			})
		} else if strategy.ShouldExit(i, tradingRecord) {
			fmt.Printf("在%d位置卖出\n", i)
			tradingRecord.Operate(techan.Order{
				Side:          techan.SELL,
				Security:       "AAPL",
				Price:          closePrices.Calculate(i),
				Amount:         1,
				ExecutionTime:  series.Candles[i].Period.Start,
			})
		}
	}
}

RSI超买超卖策略

func rsiStrategy() {
	series := createSampleSeries()
	closePrices := techan.NewClosePriceIndicator(series)
	rsi := techan.NewRelativeStrengthIndexIndicator(closePrices, 14)
	
	// 定义规则: RSI < 30买入, RSI > 70卖出
	entryRule := techan.And(
		techan.NewCrossDownIndicatorRule(rsi, techan.NewConstantIndicator(30)),
		techan.PositionNewRule{},
	)
	
	exitRule := techan.And(
		techan.NewCrossUpIndicatorRule(rsi, techan.NewConstantIndicator(70)),
		techan.PositionOpenRule{},
	)
	
	strategy := techan.NewStrategy(entryRule, exitRule)
	// 后续交易逻辑与双均线策略类似
}

5. 策略回测

techan提供了基本的回测功能:

func backtestStrategy() {
	series := createSampleSeries()
	closePrices := techan.NewClosePriceIndicator(series)
	
	// 创建策略
	shortMA := techan.NewSimpleMovingAverage(closePrices, 5)
	longMA := techan.NewSimpleMovingAverage(closePrices, 20)
	entryRule := techan.NewCrossUpIndicatorRule(shortMA, longMA)
	exitRule := techan.NewCrossDownIndicatorRule(shortMA, longMA)
	strategy := techan.NewStrategy(entryRule, exitRule)
	
	// 创建回测器
	record := techan.NewTradingRecord()
	broker := techan.NewCashBacktestBroker(10000) // 初始资金10000
	
	// 运行回测
	for i := 0; i < series.LastIndex(); i++ {
		if strategy.ShouldEnter(i, record) {
			order := techan.Order{
				Side:    techan.BUY,
				Price:   closePrices.Calculate(i),
				Amount:  1,
			}
			broker.PlaceOrder(order)
		} else if strategy.ShouldExit(i, record) {
			order := techan.Order{
				Side:    techan.SELL,
				Price:   closePrices.Calculate(i),
				Amount:  1,
			}
			broker.PlaceOrder(order)
		}
	}
	
	// 输出回测结果
	fmt.Printf("最终资金: %.2f\n", broker.AccountBalance())
	fmt.Printf("总交易次数: %d\n", len(record.Trades))
}

6. 实用技巧

  1. 自定义指标:可以通过实现Indicator接口创建自定义指标
  2. 组合策略:使用AndOrNot等组合多个规则
  3. 性能优化:对于大数据集,考虑预计算指标值
  4. 可视化:虽然techan不提供可视化功能,但可以结合其他库如gonum/plot实现

techan是一个功能强大但轻量级的库,适合用于构建量化交易系统的核心分析模块。在实际应用中,你可能还需要结合数据获取、风险管理和订单执行等模块来构建完整的交易系统。

回到顶部