import talib
# 初始化账户
def initialize(account):
account.n = 4 # 设置交易股票数量
# 使用get_iwencai函数进行智能选股
get_iwencai("净利润增长大于20%;股价位于20日均线上方;市值从小到大排序")
# 设置买卖条件,每个交易频率(日/分钟/tick)调用一次
def handle_data(account, data):
# 卖出股票
for stock in list(account.positions):
# 获取股票收盘价数据
values = data.attribute_history(stock, ["close"], 100, "1d", False, None)
if values.empty:
continue
# 计算MACD值
DIFF, DEA, MACD = talib.MACD(values["close"].values,
fastperiod=12, slowperiod=26, signalperiod=9)
# 若出现MACD死叉(MACD变为负值),则卖出股票
if MACD[-1] < 0:
order_target(stock, 0)
# 买入股票
for stock in account.iwencai_securities:
# 若股票数量到达限制,则跳出
if len(account.positions) >= account.n:
break
if stock not in account.positions:
# 获取股票收盘价数据
values = data.attribute_history(stock, ["close"], 100, "1d", False, None)
if values.empty:
continue
# 计算MACD值
DIFF, DEA, MACD = talib.MACD(values["close"].values,
fastperiod=12, slowperiod=26, signalperiod=9)
# 若出现MACD金叉,则买入1/n仓位的股票
if MACD[-1] > 0 and MACD[-2] < 0:
order_target_percent(stock, 1/account.n)