Skip to content

Commit

Permalink
增加QMT实盘相关代码,简单验证
Browse files Browse the repository at this point in the history
  • Loading branch information
woldy committed Mar 14, 2024
1 parent 24f0316 commit e96450d
Show file tree
Hide file tree
Showing 40 changed files with 3,770 additions and 8 deletions.
183 changes: 182 additions & 1 deletion database/finhack_structure.sql
Original file line number Diff line number Diff line change
@@ -1 +1,182 @@
mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: NO) when trying to connect
-- MySQL dump 10.13 Distrib 8.0.30, for Linux (x86_64)
--
-- Host: localhost Database: finhack
-- ------------------------------------------------------
-- Server version 8.0.30

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `auto_train`
--

DROP TABLE IF EXISTS `auto_train`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `auto_train` (
`id` int NOT NULL AUTO_INCREMENT,
`start_date` varchar(10) DEFAULT NULL,
`valid_date` varchar(10) DEFAULT NULL,
`end_date` varchar(10) DEFAULT NULL,
`features` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`label` varchar(255) DEFAULT NULL,
`shift` int DEFAULT NULL,
`param` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`hash` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`loss` varchar(255) DEFAULT NULL,
`algorithm` varchar(255) DEFAULT NULL,
`filter` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT '',
`score` double(10,10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12753 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `backtest`
--

DROP TABLE IF EXISTS `backtest`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `backtest` (
`id` int NOT NULL AUTO_INCREMENT,
`instance_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
`features_list` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`train` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`model` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`strategy` varchar(255) DEFAULT NULL,
`start_date` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`end_date` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`init_cash` double(100,5) DEFAULT NULL,
`args` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`history` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`returns` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`logs` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`total_value` double(100,5) DEFAULT NULL,
`alpha` double(100,5) DEFAULT NULL,
`beta` double(100,5) DEFAULT NULL,
`annual_return` double(100,5) DEFAULT NULL,
`cagr` double(100,5) DEFAULT NULL,
`annual_volatility` double(100,5) DEFAULT NULL,
`info_ratio` double(100,5) DEFAULT NULL,
`downside_risk` double(100,5) DEFAULT NULL,
`R2` double(100,5) DEFAULT NULL,
`sharpe` double(100,5) DEFAULT NULL,
`sortino` double(100,5) DEFAULT NULL,
`calmar` double(100,5) DEFAULT NULL,
`omega` double(100,5) DEFAULT NULL,
`max_down` double(100,5) DEFAULT NULL,
`SQN` double(100,5) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`filter` varchar(255) DEFAULT '',
`win` double(100,5) DEFAULT NULL,
`server` varchar(255) DEFAULT NULL,
`trade_num` int DEFAULT NULL,
`runtime` varchar(255) DEFAULT NULL,
`starttime` varchar(100) DEFAULT NULL,
`endtime` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`benchReturns` mediumtext,
`roto` double(100,5) DEFAULT NULL,
`simulate` int DEFAULT '0',
`benchmark` varchar(255) DEFAULT NULL,
`strategy_code` text,
PRIMARY KEY (`id`),
UNIQUE KEY `instence_id` (`instance_id`)
) ENGINE=InnoDB AUTO_INCREMENT=389449 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `factors_analysis`
--

DROP TABLE IF EXISTS `factors_analysis`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `factors_analysis` (
`id` int NOT NULL AUTO_INCREMENT,
`factor_name` varchar(255) DEFAULT NULL,
`days` varchar(255) DEFAULT NULL,
`source` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`start_date` varchar(10) DEFAULT NULL,
`end_date` varchar(10) DEFAULT NULL,
`formula` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`IC` float(10,5) DEFAULT NULL,
`IR` float(10,5) DEFAULT NULL,
`Sharpe` float(10,5) DEFAULT NULL,
`score` float(10,5) DEFAULT NULL,
`max_up_corr` float(10,7) DEFAULT NULL,
`hash` varchar(255) DEFAULT NULL,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3035 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `factors_list`
--

DROP TABLE IF EXISTS `factors_list`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `factors_list` (
`id` int NOT NULL AUTO_INCREMENT,
`factor_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`indicators` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`func_name` varchar(255) DEFAULT NULL,
`code` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`return_fileds` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`md5` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`check_type` int DEFAULT '0',
`status` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT 'activate',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2406 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `factors_mining`
--

DROP TABLE IF EXISTS `factors_mining`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `factors_mining` (
`id` int NOT NULL AUTO_INCREMENT,
`factor_name` varchar(255) DEFAULT NULL,
`days` varchar(255) DEFAULT NULL,
`source` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`start_date` varchar(10) DEFAULT NULL,
`end_date` varchar(10) DEFAULT NULL,
`formula` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
`IC` float(20,5) DEFAULT NULL,
`IR` float(20,5) DEFAULT NULL,
`Sharpe` float(20,5) DEFAULT NULL,
`score` float(10,5) DEFAULT NULL,
`hash` varchar(255) DEFAULT NULL,
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `hash` (`hash`(32)) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=31635 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2024-03-14 17:16:23
Empty file added examples/__init__.py
Empty file.
64 changes: 64 additions & 0 deletions examples/demo-project/strategy/QMTStrategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'''
finhack trader run --vendor=qmt --strategy=QMTStrategy
'''
import datetime
import os
import random

from finhack.market.astock.astock import AStock
## 初始化函数,设定要操作的股票、基准等等
def initialize(context):
# 设定沪深300作为基准
set_benchmark('000001.SH')
# True为开启动态复权模式,使用真实价格交易
set_option('use_real_price', True)
# 设定成交量比例
set_option('order_volume_ratio', 1)
# # 股票类交易手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱
set_order_cost(OrderCost(open_tax=0, close_tax=0.001, \
open_commission=0.0003, close_commission=0.0003,\
close_today_commission=0, min_commission=5), type='stock')

# 为股票设定滑点为百分比滑点
set_slippage(PriceRelatedSlippage(0.00246),type='stock')
# 持仓数量
g.stocknum = 10
# 交易日计时器
g.days = 0
# 调仓频率
g.refresh_rate = 3
# 运行函数
inout_cash(100000)

run_daily(trade, time="19:56")
# run_daily(trade, time="8:05")
log.info('get code list')
g.stock_list=AStock.getStockCodeList(strict=False)

## 交易函数
def trade(context):
print(context.portfolio.cash)
if g.days%g.refresh_rate == 0:
#print(context.portfolio.cash)
sell_list = list(context.portfolio.positions.keys())
if len(sell_list) > 0 :
for stock in sell_list:
order_target_value(stock, 0)

if len(context.portfolio.positions) < g.stocknum :
Num = g.stocknum - len(context.portfolio.positions)
Cash = context.portfolio.cash/Num
else:
Cash = 0

## 选股
stock_list = random.sample(g.stock_list['ts_code'].tolist(), 10)
## 买入股票
for stock in stock_list:
if len(context.portfolio.positions.keys()) < g.stocknum:
order_value(stock, Cash)

# 天计数加一
g.days = 1
else:
g.days += 1
Empty file.
Empty file.
19 changes: 19 additions & 0 deletions examples/demo-project/trader/qmt/calendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from finhack.library.mydb import mydb
class Calendar:
def get_calendar(start_time,end_time,market):
start_time=start_time.replace('-','')[0:8]
end_time=end_time.replace('-','')[0:8]
calendar={}

if market=='astock':
calendar=Calendar.get_astock_calendar(start_time,end_time)
calendar = [f"{date[:4]}-{date[4:6]}-{date[6:]}" for date in calendar]
return calendar


#获取A股交易日历
def get_astock_calendar(start_time,end_time):
cal=mydb.selectToDf(f"select cal_date from astock_trade_cal where is_open=1 \
and exchange='SSE' and cal_date>={start_time} and cal_date<={end_time} \
order by cal_date asc",'tushare')
return cal['cal_date'].tolist()
119 changes: 119 additions & 0 deletions examples/demo-project/trader/qmt/context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
from trader.qmt.dictobj import DictObj




g=DictObj()


context_attr= {
'id':'',
'universe':[],
'previous_date':None,
'current_dt':None,
'args':None,
'trade':DictObj({
'market':'',
'model_id':'',
'start_time':'',
'end_time':'',
'benchmark':'000001',
'log_type':'',
'record_type':'',
'strategy':'',
'order_volume_ratio':1,
'slip':0,
'sliptype':'pricerelated',
'rule_list':''
}),

'account':DictObj({
'username':'',
'password':'',
'account_id':'',
'open_tax':0,
'close_tax':0.001,
'open_commission':0.0003,
'close_commission':0.0003,
'close_today_commission':0,
'min_commission':5

}),

'portfolio':DictObj({
'inout_cash':0,
'cash':0,
'transferable_cash':0,
'locked_cash':0,
'margin':0,
'total_value':0,
'previous_value':0,
'returns':0,
'starting_cash':0,
'positions_value':0,
'portfolio_value':0,
'locked_cash_by_purchase':0,
'locked_cash_by_redeem':0,
'locked_amound_by_redeen':0,
'positions':{

}
}),

'data':DictObj({
'calendar':[],
'event_list':[],
'data_source':'file',
'daily_info':None,
'dividend':{},
'quote':None,
'client':None
}),

'logs':DictObj({
'trade_list':[],
'order_list':[],
'position_list':[],
'return_list':[],
'trade_returns':[],
'history':{}
}),
'performance':DictObj({
'returns':[],
'bench_returns':[],
'turnover':[],
'win':0,
'win_ratio':0,
'trade_num':0,
'indicators':{}
})

}
context=DictObj(context_attr)




#'position':{
# 'xxx':sid 标的代码
# enable_amount 可用数量
# amount 总持仓数量
# last_sale_price 最新价格
# cost_basis 持仓成本价格(期货不支持)
# today_amount 今日开仓数量(期货不支持,且仅回测有效)
# 期货专用字段:
# delivery_date 交割日,期货使用
# today_short_amount 空头今仓数量
# today_long_amount 多头今仓数量
# long_cost_basis 多头持仓成本
# short_cost_basis 空头持仓成本
# margin_rate 保证金比例
# contract_multiplier 合约乘数
# long_amount 多头总持仓量
# short_amount 空头总持仓量
# long_pnl 多头浮动盈亏
# short_pnl 空头浮动盈亏
# long_enable_amount 多头可用数量
# short_enable_amount 多空头可用数量
# business_type 业务类型
# },
Loading

0 comments on commit e96450d

Please sign in to comment.