Skip to content

Commit

Permalink
暂存
Browse files Browse the repository at this point in the history
  • Loading branch information
woldy committed Jul 9, 2024
1 parent 4a2a3fb commit a82c9b9
Show file tree
Hide file tree
Showing 252 changed files with 1,967 additions and 279 deletions.
Empty file modified COMMERCIAL_LICENSE.txt
100644 → 100755
Empty file.
Empty file modified Dockerfile
100644 → 100755
Empty file.
Empty file modified LICENSE.txt
100644 → 100755
Empty file.
Empty file modified MANIFEST.in
100644 → 100755
Empty file.
Empty file modified README.md
100644 → 100755
Empty file.
6 changes: 3 additions & 3 deletions database/finhack_structure.sql
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ CREATE TABLE `auto_train` (
`score` double(10,10) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `hash` (`hash`)
) ENGINE=InnoDB AUTO_INCREMENT=14227 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
) ENGINE=InnoDB AUTO_INCREMENT=14397 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
Expand Down Expand Up @@ -93,7 +93,7 @@ CREATE TABLE `backtest` (
`strategy_code` text,
PRIMARY KEY (`id`),
UNIQUE KEY `instence_id` (`instance_id`)
) ENGINE=InnoDB AUTO_INCREMENT=443191 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
) ENGINE=InnoDB AUTO_INCREMENT=447981 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
Expand Down Expand Up @@ -255,4 +255,4 @@ CREATE TABLE `rqalpha` (
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2024-04-09 14:04:21
-- Dump completed on 2024-06-28 13:29:27
Empty file modified examples/__init__.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/.proj
100644 → 100755
Empty file.
Empty file modified examples/demo-project/auto/__init__.py
100644 → 100755
Empty file.
11 changes: 9 additions & 2 deletions examples/demo-project/backtest/default/default_backtest.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,15 @@ def rqalpha(self):
entry_file_path = os.path.realpath(sys.executable)
else:
entry_file_path = os.path.realpath(sys.argv[0])

bt_list=mydb.selectToList(f"SELECT id, instance_id, features_list, train, model, strategy, start_date, end_date, init_cash, params, total_value, alpha, beta, annual_return, cagr, annual_volatility, info_ratio, downside_risk, R2, sharpe, sortino, calmar, omega, max_down, SQN, created_at, filter, win, server, trade_num, runtime, starttime, endtime, roto, simulate, benchmark, strategy_code FROM `finhack`.`backtest` order by sharpe desc LIMIT 1000",'finhack')

sql=""
path=f"{BASE_DIR}/data/config/sqllist/backtest/bt_list.sql"
if os.path.exists(path):
with open(path, 'r', encoding='utf-8') as file:
sql= file.read()
else:
sql="SELECT id, instance_id, features_list, train, model, strategy, start_date, end_date, init_cash, params, total_value, alpha, beta, annual_return, cagr, annual_volatility, info_ratio, downside_risk, R2, sharpe, sortino, calmar, omega, max_down, SQN, created_at, filter, win, server, trade_num, runtime, starttime, endtime, roto, simulate, benchmark, strategy_code FROM `finhack`.`backtest` order by sharpe desc LIMIT 1000"
bt_list=mydb.selectToList(sql,'finhack')

def to_json(s):
dict_str = re.sub(r"DictObj\((.*?)\)", r"{\1}", s)
Expand Down
Empty file modified examples/demo-project/indicators/QIML365.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/indicators/member.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/loader/testmodule_loader.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/prompt/autoalpha
100644 → 100755
Empty file.
6 changes: 3 additions & 3 deletions examples/demo-project/script/qmt.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
cd /data/code/demo_project
/root/anaconda3/envs/finhack/bin/python -u /root/anaconda3/envs/finhack/bin/finhack trader run \
--project_path=/data/code/demo_project/ \
--vendor=qmt --id=r_ad6709f1d13f642e16d74a40190d06c5 \
--strategy=QMTStrategy --model_id=929526e7c5f8807a04205c17cc95b742 \
--params='{"stocknum": "5", "refresh_rate": "5", "stop_loss_threshold": "0.95", "stop_gain_threshold": "1.2"}' >>/tmp/finhack_qmt.log
--vendor=qmt --id=r_golden \
--strategy=QMTStrategy --model_id=97b190dd39d86b464dd76597cef2dc48 \
--params='{"stocknum": "30", "refresh_rate": "3", "stop_loss_threshold": "0.9", "stop_gain_threshold": "1.3"}' >>/tmp/finhack_qmt.log
Empty file modified examples/demo-project/strategy/AITopNStrategy.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/strategy/AITopNStrategy2.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/strategy/ChatGPTStrategy.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/strategy/ChatGPTStrategy1.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/strategy/ChatGPTStrategy3.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/strategy/ChatgptAIStrategy.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/strategy/DemoStrategy.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/strategy/IndexPlus.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/strategy/IndexPlus2.py
100644 → 100755
Empty file.
2 changes: 1 addition & 1 deletion examples/demo-project/strategy/QMTStrategy.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def trade_open(context):

# 盘尾逻辑
def trade_close(context):
# sync(context)
sync(context)
g=context.g
adjust_dynamic_parameters(context)

Expand Down
Empty file modified examples/demo-project/strategy/SmallCapStrategy.py
100644 → 100755
Empty file.
55 changes: 41 additions & 14 deletions examples/demo-project/strategy/testStrategy.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ def initialize(context):
# 设定滑点
set_slippage(PriceRelatedSlippage(0.00246), type='stock')

model_id = context.trade.model_id
preds_cache=context.get('params', {}).get('preds_cache', 'False')
if preds_cache.lower()[0:1]=='t':
preds_data = load_preds_data(model_id,True)
else:
preds_data = load_preds_data(model_id)
g.preds=preds_data
# model_id = context.trade.model_id
# preds_cache=context.get('params', {}).get('preds_cache', 'False')
# if preds_cache.lower()[0:1]=='t':
# preds_data = load_preds_data(model_id,True)
# else:
# preds_data = load_preds_data(model_id)
# g.preds=preds_data
# 全局变量初始化
g.stock_num = int(context.get('params', {}).get('stocknum', 10)) # 持仓股票数量
g.refresh_rate = int(context.get('params', {}).get('refresh_rate', 10)) # 调仓频率,动态调整
Expand All @@ -39,11 +39,34 @@ def initialize(context):
g.days = 0 # 交易日计时器

# 每日运行
run_daily(trade_open, time="09:30")
run_daily(trade_open, time="09:30")
run_daily(trade_open, time="09:30")
run_daily(trade_close, time="15:00")
run_daily(trade_open, time="09:20:10")
run_daily(trade_close, time="14:57:10")

# # 当前时间
# now = datetime.now()



# # 10分钟后的时间
# ten_minutes_later = now + timedelta(minutes=60*24)

# # 当前时间加上10秒,用于第一次调度
# next_call_time = now + timedelta(seconds=10)



# # 循环,直到达到10分钟后的时间
# while next_call_time <= ten_minutes_later:
# print(next_call_time.strftime("%H:%M:%S"))
# # 计划函数调用
# run_daily(test, next_call_time.strftime("%H:%M:%S"))

# # 更新下一次调用时间(增加10秒)
# next_call_time += timedelta(seconds=10)


def days_inc(context):
g.days += 1


# 动态调整策略参数
Expand All @@ -55,11 +78,13 @@ def adjust_dynamic_parameters(context):
def select_stocks(context):
# 加载AI模型预测数据
g=context.g
print(g)
now_date = context.current_dt.strftime('%Y%m%d')
preds_data=g.preds
# 筛选今日预测数据,并排序
pred_today = preds_data[preds_data['trade_date'] == now_date]
pred_today_sorted = pred_today.sort_values(by='pred', ascending=False)
print(pred_today_sorted)
# 返回股票列表
return pred_today_sorted['ts_code'].tolist()

Expand All @@ -71,7 +96,9 @@ def should_sell(stock, context):
if current_price==None:
return False
cost_price = context.portfolio.positions[stock].cost_basis
print(f"{stock}的当前价为{current_price},均价为{cost_price},止损价为{cost_price * g.stop_loss_threshold},止盈价为{cost_price * g.stop_gain_threshold}")
if current_price <= cost_price * g.stop_loss_threshold or current_price >= cost_price * g.stop_gain_threshold:
print('触发卖出条件')
return True
return False

Expand Down Expand Up @@ -106,17 +133,17 @@ def trade_open(context):
successed=successed+1
if successed>=num_stocks_to_buy:
break
g.days += 1



# 盘尾逻辑
def trade_close(context):
# sync(context)
sync(context)
g=context.g
adjust_dynamic_parameters(context)

# 卖出逻辑
for stock in list(context.portfolio.positions.keys()):
if should_sell(stock, context):
order_target_value(stock, 0)
order_target_value(stock, 0)
g.days += 1
Empty file modified examples/demo-project/testmodule/default/default_testmodule.py
100644 → 100755
Empty file.
Empty file modified examples/demo-project/trader/__init__.py
100644 → 100755
Empty file.
Empty file.
19 changes: 19 additions & 0 deletions examples/demo-project/trader/miniqmt/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()
120 changes: 120 additions & 0 deletions examples/demo-project/trader/miniqmt/context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
from trader.miniqmt.dictobj import DictObj


g=DictObj({
'preds':None
})


context_attr= {
'id':'',
'universe':[],
'previous_date':None,
'current_dt':None,
'params':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':''
}),
'g':g,
'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_interval_list':[],
'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 业务类型
# },
24 changes: 24 additions & 0 deletions examples/demo-project/trader/miniqmt/data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from finhack.library.config import Config
from runtime.constant import *
from finhack.market.astock.astock import AStock
import json
import pickle
import pandas as pd
import os
import time
from datetime import datetime
import trader.miniqmt.calendar
import finhack.library.log as Log
from finhack.core.classes.dictobj import DictObj
from trader.miniqmt.qmtClient import qclient


class Data:
def get_daily_info(code,context,date=None):
return qclient.getInfo(code)

#根据当前时间获取价格
def get_price(code,context=None):
return qclient.getPrice(code)


Loading

0 comments on commit a82c9b9

Please sign in to comment.