基于MACD指标的股票交易策略
import numpy as np
import pandas as pd
import talib
def init(ContextInfo):
MarketPosition = {}
ContextInfo.MarketPosition = MarketPosition # 初始化持仓
ContextInfo.set_universe([ContextInfo.stockcode + '.' + ContextInfo.market])
ContextInfo.first = 0
ContextInfo.Lots = 100 # 设定交易手数
ContextInfo.day = [0, 0]
ContextInfo.ending = 0
ContextInfo.total = 10000
ContextInfo.accountID = 'testS'
def handlebar(ContextInfo):
d = ContextInfo.barpos
if d < 35:
return
startdate = timetag_to_datetime(ContextInfo.get_bar_timetag(d - 35), '%Y%m%d%H%M%S')
enddate = timetag_to_datetime(ContextInfo.get_bar_timetag(d), '%Y%m%d%H%M%S')
##print startdate,enddate
date = timetag_to_datetime(ContextInfo.get_bar_timetag(d), '%Y-%m-%d %H:%M:%S')
print('日期', date)
flage = False
singleemited = False
df = ContextInfo.get_market_data(['close'], stock_code=ContextInfo.get_universe(), start_time=startdate,
end_time=enddate, period=ContextInfo.period)
# print df
if df.empty:
return
# print df
if ContextInfo.first == 0:
order_shares(ContextInfo.get_universe()[0], ContextInfo.total, 'fix', df.iloc[-1, 0], ContextInfo,
ContextInfo.accountID)
flage = True
singleemited = True
ContextInfo.first = 1
ContextInfo.day[-1] = date[8:10]
ContextInfo.turnaround = [0, 0]
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] = ContextInfo.total
return
ContextInfo.day[0] = date
# 14:55:00之后不再交易
if int(date[-8:-6] + date[-5:-3]) > 1455:
return
avaliable = get_avaliable(ContextInfo.accountID, 'STOCK')
holding = get_holdings(ContextInfo.accountID, 'STOCK')
if ContextInfo.get_universe()[0] not in list(holding.keys()):
holding[ContextInfo.get_universe()[0]] = 0
# 计算MACD线
if ContextInfo.total >= 0:
recent_date = np.array(df.iloc[-35:, 0])
macd = talib.MACD(recent_date)[0][-1]
macd_pre = talib.MACD(recent_date)[0][-2]
# 根据MACD>0则开仓,小于0则平仓
if date[-8:-3] != '14:55':
if macd > 0 and macd_pre < 0:
# 根据MACD>0则开仓,小于0则平仓
if avaliable > df.iloc[-1, 0] * ContextInfo.Lots * 100:
order_shares(ContextInfo.get_universe()[0], ContextInfo.Lots, 'fix', df.iloc[-1, 0], ContextInfo,
ContextInfo.accountID)
flage = True
singleemited = True
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] += ContextInfo.Lots
print (ContextInfo.get_universe()[0], 'open position at market price', ContextInfo.Lots, '股')
elif macd < 0 and macd_pre > 0 and holding[ContextInfo.get_universe()[0]] >= ContextInfo.Lots:
order_shares(ContextInfo.get_universe()[0], -ContextInfo.Lots, 'fix', df.iloc[-1, 0], ContextInfo,
ContextInfo.accountID)
flage = False
singleemited = True
print(ContextInfo.get_universe()[0], 'close position at market price', ContextInfo.Lots, '股')
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] -= ContextInfo.Lots
# 临近收盘时若仓位数不等于昨仓则回转所有仓位
else:
if ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] > ContextInfo.total:
order_shares(ContextInfo.get_universe()[0],
-(ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] - ContextInfo.total), 'fix',
df.iloc[-1, 0], ContextInfo, ContextInfo.accountID)
flage = False
singleemited = True
# print ContextInfo.get_universe()[0], '回转操作市价单平多仓', ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] - ContextInfo.total, '股'
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] = ContextInfo.total
if ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] < ContextInfo.total:
order_shares(ContextInfo.get_universe()[0],
(ContextInfo.total - ContextInfo.MarketPosition[ContextInfo.get_universe()[0]]), 'fix',
df.iloc[-1, 0], ContextInfo, ContextInfo.accountID)
flage = True
singleemited = True
# print ContextInfo.get_universe()[0], '回转操作市价单开多仓', ContextInfo.total - ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] , '股'
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] = ContextInfo.total
# 更新过去的日期数据
'''ContextInfo.day[-1] = ContextInfo.day[0]
if singleemited:
if flage:
ContextInfo.paint('do_buy',1,-1,0,'yellow','noaxis')
ContextInfo.paint('do_sell',0,-1,0,'red','noaxis')
else:
ContextInfo.paint('do_buy',0,-1,0,'yellow','noaxis')
ContextInfo.paint('do_sell',1,-1,0,'red','noaxis')'''
# ContextInfo.paint('holding',ContextInfo.MarketPosition[ContextInfo.get_universe()[0]],-1,0)
def get_avaliable(accountid, datatype):
result = 0
resultlist = get_trade_detail_data(accountid, datatype, 'ACCOUNT')
for obj in resultlist:
result = obj.m_dAvailable
return result
def get_holdings(accountid, datatype):
holdinglist = {}
resultlist = get_trade_detail_data(accountid, datatype, 'POSITION')
for obj in resultlist:
holdinglist[obj.m_strInstrumentID + '.' + obj.m_strExchangeID] = obj.m_nCanUseVolume
return holdinglist
检查是否有误内容:本代码需要在聚宽平台运行,需要调用聚宽的API接口,无法在其他环境下运行。
以下是代码中可能存在的问题:
1. 缺少必要的API调用,如get_market_data、order_shares、get_avaliable等,需要在聚宽平台中调用聚宽提供的API接口才能正常运行。
2. 代码中的一些参数或变量未定义或未赋值,如ContextInfo.stockcode、ContextInfo.market、ContextInfo.period等,需要根据实际情况进行定义和赋值。
3. 代码中的一些逻辑可能存在问题,如持仓数量的计算、回转操作的处理等,需要根据实际情况进行调整和优化。
4. 代码中缺少必要的注释和说明,需要添加注释和说明,方便其他人理解和修改代码。
', 'content_zh': '```python import numpy as np import pandas as pd import talib
def init(ContextInfo): MarketPosition = {} ContextInfo.MarketPosition = MarketPosition # 初始化持仓 ContextInfo.set_universe([ContextInfo.stockcode + '.' + ContextInfo.market]) ContextInfo.first = 0 ContextInfo.Lots = 100 # 设定交易手数 ContextInfo.day = [0, 0] ContextInfo.ending = 0 ContextInfo.total = 10000 ContextInfo.accountID = 'testS'
def handlebar(ContextInfo): d = ContextInfo.barpos if d < 35: return startdate = timetag_to_datetime(ContextInfo.get_bar_timetag(d - 35), '%Y%m%d%H%M%S') enddate = timetag_to_datetime(ContextInfo.get_bar_timetag(d), '%Y%m%d%H%M%S') ##print startdate,enddate date = timetag_to_datetime(ContextInfo.get_bar_timetag(d), '%Y-%m-%d %H:%M:%S') print('日期', date) flage = False singleemited = False
df = ContextInfo.get_market_data(['close'], stock_code=ContextInfo.get_universe(), start_time=startdate,
end_time=enddate, period=ContextInfo.period)
# print df
if df.empty:
return
# print df
if ContextInfo.first == 0:
order_shares(ContextInfo.get_universe()[0], ContextInfo.total, 'fix', df.iloc[-1, 0], ContextInfo,
ContextInfo.accountID)
flage = True
singleemited = True
ContextInfo.first = 1
ContextInfo.day[-1] = date[8:10]
ContextInfo.turnaround = [0, 0]
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] = ContextInfo.total
return
ContextInfo.day[0] = date
# 14:55:00之后不再交易
if int(date[-8:-6] + date[-5:-3]) > 1455:
return
avaliable = get_avaliable(ContextInfo.accountID, 'STOCK')
holding = get_holdings(ContextInfo.accountID, 'STOCK')
if ContextInfo.get_universe()[0] not in list(holding.keys()):
holding[ContextInfo.get_universe()[0]] = 0
# 计算MACD线
if ContextInfo.total >= 0:
recent_date = np.array(df.iloc[-35:, 0])
macd = talib.MACD(recent_date)[0][-1]
macd_pre = talib.MACD(recent_date)[0][-2]
# 根据MACD>0则开仓,小于0则平仓
if date[-8:-3] != '14:55':
if macd > 0 and macd_pre < 0:
# 根据MACD>0则开仓,小于0则平仓
if avaliable > df.iloc[-1, 0] * ContextInfo.Lots * 100:
order_shares(ContextInfo.get_universe()[0], ContextInfo.Lots, 'fix', df.iloc[-1, 0], ContextInfo,
ContextInfo.accountID)
flage = True
singleemited = True
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] += ContextInfo.Lots
print (ContextInfo.get_universe()[0], 'open position at market price', ContextInfo.Lots, '股')
elif macd < 0 and macd_pre > 0 and holding[ContextInfo.get_universe()[0]] >= ContextInfo.Lots:
order_shares(ContextInfo.get_universe()[0], -ContextInfo.Lots, 'fix', df.iloc[-1, 0], ContextInfo,
ContextInfo.accountID)
flage = False
singleemited = True
print(ContextInfo.get_universe()[0], 'close position at market price', ContextInfo.Lots, '股')
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] -= ContextInfo.Lots
# 临近收盘时若仓位数不等于昨仓则回转所有仓位
else:
if ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] > ContextInfo.total:
order_shares(ContextInfo.get_universe()[0],
-(ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] - ContextInfo.total), 'fix',
df.iloc[-1, 0], ContextInfo, ContextInfo.accountID)
flage = False
singleemited = True
# print ContextInfo.get_universe()[0], '回转操作市价单平多仓', ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] - ContextInfo.total, '股'
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] = ContextInfo.total
if ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] < ContextInfo.total:
order_shares(ContextInfo.get_universe()[0],
(ContextInfo.total - ContextInfo.MarketPosition[ContextInfo.get_universe()[0]]), 'fix',
df.iloc[-1, 0], ContextInfo, ContextInfo.accountID)
flage = True
singleemited = True
# print ContextInfo.get_universe()[0], '回转操作市价单开多仓', ContextInfo.total - ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] , '股'
ContextInfo.MarketPosition[ContextInfo.get_universe()[0]] = ContextInfo.total
# 更新过去的日期数据
'''ContextInfo.day[-1] = ContextInfo.day[0]
if singleemited:
if flage:
ContextInfo.paint('do_buy',1,-1,0,'yellow','noaxis')
ContextInfo.paint('do_sell',0,-1,0,'red','noaxis')
else:
ContextInfo.paint('do_buy',0,-1,0,'yellow','noaxis')
ContextInfo.paint('do_sell',1,-1,0,'red','noaxis')'''
ContextInfo.paint('holding',ContextInfo.MarketPosition[ContextInfo.get_universe()[0]],-1,0)
def get_avaliable(accountid, datatype): result = 0 resultlist = get_trade_detail_data(accountid, datatype, 'ACCOUNT') for obj in resultlist: result = obj.m_dAvailable return result
def get_holdings(accountid, datatype): holdinglist = {} resultlist = get_trade_detail_data(accountid, datatype, 'POSITION') for obj in resultlist: holdinglist[obj.m_strInstrumentID + '.' + obj.m_strExchangeID] = obj.m_nCanUseVolume return holdinglist
检查是否有误内容:本代码需要在聚宽平台运行,需要调用聚宽的API接口,无法在其他环境下运行。
以下是代码中可能存在的问题:
-
缺少必要的API调用,如get_market_data、order_shares、get_avaliable等,需要在聚宽平台中调用聚宽提供的API接口才能正常运行。
-
代码中的一些参数或变量未定义或未赋值,如ContextInfo.stockcode、ContextInfo.market、ContextInfo.period等,需要根据实际情况进行定义和赋值。
-
代码中的一些逻辑可能存在问题,如持仓数量的计算、回转操作的处理等,需要根据实际情况进行调整和优化。
-
代码中缺少必要的注释和说明,需要添加注释和说明,方便其他人理解和修改代码。
原文地址: https://www.cveoy.top/t/topic/mQBK 著作权归作者所有。请勿转载和采集!