【golang】量化开发学习(一)

均值回归策略简介

均值回归(Mean Reversion)假设价格会围绕均值波动,当价格偏离均值一定程度后,会回归到均值。
基本逻辑:

  1. 计算一段时间内的移动均值(如 20 天均线)。
  2. 当当前价格高于均值一定比例 ,做空;当低于均值一定比例,做多。
  3. 持仓等待价格回归后平仓。

官网下载DOLGPHINDB


总结

✅ Docker 运行 DolphinDB

✅ 创建模拟股票数据表

✅ Golang 连接 DolphinDB 进行查询

这样,Golang 代码就可以直接获取数据并进行回测了 🚀!如果需要更复杂的 数据流 或 实时计算 ,可以考虑 DolphinDB 的 流式表(stream table)。

📝 Golang 实现均值回归策略

📌 主要步骤

  • 从 DolphinDB 获取历史数据(收盘价)
  • 计算 n 日移动均值
  • 生成交易信号
  • 计算策略回测收益

🔧 代码

以下 Golang 代码:

  1. 连接 DolphinDB 获取数据
  2. 计算 20 日均线
  3. 执行简单的回测
复制代码
Go 复制代码
package main

import (
	"fmt"
	"log"
	"math"
	"net/http"
	"strings"
	"encoding/json"
	"io/ioutil"
)

// DolphinDB 查询 URL(根据你的服务器 IP 修改)
const ddbURL = "http://your-dolphindb-server:8848/execute"

var (
	n       = 20 // 均线周期
	threshold = 0.02 // 2% 偏差阈值
	capital   = 100000.0 // 初始资金
)

// 查询 DolphinDB 数据
func fetchDolphinDBData(symbol string) ([]float64, error) {
	query := fmt.Sprintf(`select close from stock_data where symbol="%s" order by date;`, symbol)
	resp, err := http.Post(ddbURL, "text/plain", strings.NewReader(query))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	var result map[string]interface{}
	json.Unmarshal(body, &result)

	closePrices := []float64{}
	if values, ok := result["close"].([]interface{}); ok {
		for _, v := range values {
			closePrices = append(closePrices, v.(float64))
		}
	}
	return closePrices, nil
}

// 计算 n 日均线
func movingAverage(prices []float64, period int) []float64 {
	ma := make([]float64, len(prices))
	var sum float64
	for i := range prices {
		if i < period {
			ma[i] = math.NaN()
		} else {
			sum = 0
			for j := 0; j < period; j++ {
				sum += prices[i-j]
			}
			ma[i] = sum / float64(period)
		}
	}
	return ma
}

// 进行回测
func backtest(prices, ma []float64) float64 {
	position := 0
	balance := capital
	for i := n; i < len(prices); i++ {
		price := prices[i]
		if math.IsNaN(ma[i]) {
			continue
		}
		// 交易信号
		if price < ma[i]*(1-threshold) && position == 0 { // 买入
			position = int(balance / price)
			balance -= float64(position) * price
			fmt.Printf("买入 %d 股, 价格: %.2f, 资金: %.2f\n", position, price, balance)
		} else if price > ma[i]*(1+threshold) && position > 0 { // 卖出
			balance += float64(position) * price
			fmt.Printf("卖出 %d 股, 价格: %.2f, 资金: %.2f\n", position, price, balance)
			position = 0
		}
	}
	// 最后清仓
	if position > 0 {
		balance += float64(position) * prices[len(prices)-1]
	}
	return balance
}

func main() {
	symbol := "AAPL"
	prices, err := fetchDolphinDBData(symbol)
	if err != nil {
		log.Fatalf("获取数据失败: %v", err)
	}

	ma := movingAverage(prices, n)
	finalBalance := backtest(prices, ma)
	fmt.Printf("策略最终资金: %.2f\n", finalBalance)
}

📌 代码解析

  1. 连接 DolphinDB
    • fetchDolphinDBData() 发送 HTTP 请求获取数据(你需要修改数据库 IP)
    • DolphinDB 返回 close 价格数据
  2. 计算移动均线
    • movingAverage() 计算 n 天均线
  3. 交易逻辑
    • 当价格比均线低 2%,买入
    • 当价格比均线高 2%,卖出
    • backtest() 模拟资金变化
  4. 打印回测结果
    • 资金增减情况
    • 最终资金
相关推荐
开开心心_Every1 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
chenbingjie_c1 小时前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++
吴卫斌1 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
超级架构师2 小时前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core
叼烟扛炮3 小时前
Linux 学习笔记(四十三):网络编程进阶——自定义协议解决 TCP 粘包与守护进程
linux·开发语言·网络·笔记·tcp/ip
LMT流氓兔4 小时前
第五单元——第十六课:给书店助手加上网页界面
java·开发语言·jvm·人工智能·oracle·langchain·1024程序员节
专注仿真4 小时前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
外收内放4 小时前
Python基础语法练习题(75)
开发语言·python·学习
starzy19905 小时前
Scala循环与判断:一切皆表达式的控制流
开发语言·人工智能·scala
starzy19905 小时前
Scala类和对象:从构造器到样例类的完整指南
开发语言·后端·scala