0
点赞
收藏
分享

微信扫一扫

python第11天:基于QMT系统的算法学习

Spinach菠菜 2022-04-07 阅读 68
python

QMT模型1:

        监控我的自选里的标的,如果死叉且有持仓,卖出,否则,买入

#coding:gbk
#!/usr/bin/python
import time, datetime
import numpy as np


def init(ContextInfo):   #初始化函数
	#取成份股
	s=ContextInfo.get_stock_list_in_sector('我的自选')
	print (s)
	
	#设置股票池
	ContextInfo.set_universe(s)
	
	#设置基准(当前图给基准)
	ContextInfo.benchmark=ContextInfo.stockcode+"."+ContextInfo.market

	#当前图代码.当前图市场
	ContextInfo.tmp = {i:0 for i in s}  #遍历我的自选,存在临时集合里面,去重
	
def handlebar(ContextInfo):   #操作函数
	d = ContextInfo.barpos  #当前运行到K线索引号,只读,索引号从0开始;
    #barpos函数返回当前是第几根K线.对于日线数据就表示从上市到现在总共有多少交易日.

	realtime = ContextInfo.get_bar_timetag(d)  #获取当前K线对应的时间的时间戳
	nowdate = timetag_to_datetime(realtime,'%Y-%m-%d')  #将毫秒时间转换成确定格式日期时间
	#输出当前运行到的日期
	print(nowdate)

	ContextInfo.holdings=get_holdings('账户名称','STOCK') #调用获取账户持仓函数,获取持仓列表
	last20s=ContextInfo.get_history_data(21,'1d','close') 
    #获取股票池中所有股票的最近20日的收盘价

	count=0
	buyNumber = 0
	buyAmount = 0
	sellNumber = 0
	sellAmount = 0
	for k ,closes in list(last20s.items()):
		if len(closes)<21:
			continue
		pre=closes[-1]
		m20=np.mean(closes[:20])   #获取20日均线值
		m5=np.mean(closes[-6:-1])  #获取5日均线值
		
		if ContextInfo.tmp[k] == 0:  #池子里没有标的
			if m5 >= m20:
				ContextInfo.tmp[k] = 0
			else:
				ContextInfo.tmp[k] = 1
		else:   #池子里有票

			#对股票池中满足条件的股票进行买卖
			if m5 <= m20:  #死叉
				if k in ContextInfo.holdings: #有持仓
					sellNumber = sellNumber + 1   #卖出次数+1
					sellAmount += float(ContextInfo.holdings[k]) * pre 
                    #函数返回一个十进制浮点型数值(小数)

					order_shares(k,
/float(ContextInfo.holdings[k]),"FIX",pre,ContextInfo,"testS")   #下单代码数量账号
					del ContextInfo.holdings[k]    #从持仓列表删除
					print('卖出%s'%k)              #输出卖出

				
			else:  #没有死叉的其他情况
				if  k not in ContextInfo.holdings:  #K不在持仓里面,则进行买入操作
					ContextInfo.holdings[k] = 500
					buyNumber += 1
					buyAmount += float(ContextInfo.holdings[k]) * pre
					order_shares(k,/
float(ContextInfo.holdings[k]),"FIX",pre,ContextInfo,"testS")
					print('买入%s'%k)
	ContextInfo.paint("buy_num", buyNumber, -1, 0) #输出buy_num数量,主图曲线显示
	ContextInfo.paint("sell_num", sellNumber, -1, 0)
					
def get_holdings(accountid,datatype):
	holdinglist={}  #创建空集合存放持仓列表
	resultlist=get_trade_detail_data(accountid,datatype,"POSITION") #获取ID,账户类型,持仓
	for obj in resultlist:
		holdinglist[obj.m_strInstrumentID+"."+obj.m_strExchangeID]=obj.m_nVolume
	return holdinglist


举报

相关推荐

0 条评论