import talib
def initialize(account):
get_iwencai("PE小于40,PE大于35,ROE大于20%")
account.n=5
def macd_cal(stk, data):
# 获取智能选股股票列表
values = data.attribute_history(stk, ['close'], 40, '1d', False, None)
# 计算MACD值
DIFF, DEA, MACD = talib.MACD(values['close'].values,
fastperiod=12, slowperiod=26, signalperiod=9)
# 将MACD值以局部变量形式返回
return MACD
--- 4. 盘中设置买卖条件,每个交易频率(日/分钟)调用一次-------------
def handle_data(account, data):
# 买入股票
for stock in account.iwencai_securities:
# 获取股票过去30日的收盘价数据
close = data.attribute_history( stock, ['close'], 30, '1d')
# 计算股票过去2日的收盘价平均値
MA2 = close.values[-2:].mean()
#计算股票过去30日的收盘价平均値
MA30 = close.values.mean()
if MA2 > MA5:
a=1
else :
a=0
# 若股票数量到达限制,则跳出
if len(account.positions) >= account.n:
break
if stock not in account.positions:
# 若出现MACD金叉,则买入1/n仓位的股票
MACD = macd_cal(stock, data)
if MACD[-1] > 0 and MACD[-2] < 0 and a==1:
order_target_percent(stock, 1/account.n)
# 卖出股票
for stock in list(account.positions):
# 获取股票收盘价数据
MACD = macd_cal(stock, data)
# 若出现MACD死叉(MACD为负值),则卖出股票
if MACD[-1] < 0 and MACD[-2]>0 :
order_target(stock, 0)