分享

AI量化交易利器:轻松实现Dual Thrust策略,获得稳定收益!

 伊伊爸 2023-05-23 发布于湖北

使用easytrader库和tushare数据源来实现Dual Thrust策略的方法。

文章图片1

使用Dual Thrust策略计算出买入阈值和卖出阈值后,我们还需要通过easytrader来下单买入或卖出股票。

文章图片2

下面是完整的代码,包括下单操作:

import easytraderfrom datetime import datetimeimport tushare as ts# 创建 easytrader 实例user = easytrader.use('ht')user.prepare('ht.json')# 定义 Dual Thrust 策略def dual_thrust(code, start_date, end_date): high_data = ts.get_k_data(code, start=start_date, end=end_date) # 获取股票历史行情数据 k1 = 0.3 k2 = 0.7 n = 20 HH = high_data['high'].rolling(n).max() # n天内的最高价 LL = high_data['low'].rolling(n).min() # n天内的最低价 HC = high_data['close'].shift(1) # 昨收价 TR = max(high_data['high'] - high_data['low'], abs(high_data['high'] - HC), abs(high_data['low'] - HC)) # 真实波动幅度 ATR = TR.rolling(n).mean() # 平均真实波动幅度 buy_line = HH * (1 + k1 * ATR / high_data['close']) # 买入阈值 sell_line = LL * (1 - k2 * ATR / high_data['close']) # 卖出阈值 return buy_line.iloc[-1], sell_line.iloc[-1]# 获取买入阈值和卖出阈值code = '600519'start_date = '2018-01-01'end_date = datetime.now().strftime('%Y-%m-%d')thresholds = dual_thrust(code, start_date, end_date)print(f'股票{code}当前买入阈值为{thresholds[0]},卖出阈值为{thresholds[1]}')# 获取当前持仓position_info = user.positionprice_dict = {item['证券代码']:item['证券现价'] for item in position_info}position_dict = {item['证券代码']:item['证券数量'] for item in position_info}# 计算购买数量buy_price = thresholds[0]buy_amount = int(user.balance['证券资产'] / buy_price)# 判断是否需要买入if buy_price < price_dict.get(code, 0) and buy_price > 0 and buy_amount > 0: # 买入股票 result = user.buy(code=code, price=buy_price, amount=buy_amount, entrust_prop='limit') print(f'买入{code},数量为{buy_amount},价格为{buy_price},买入结果为{result}')else: # 判断是否需要卖出 sell_price = thresholds[1] sell_amount = position_dict.get(code, 0) if sell_price > price_dict.get(code, 0) and sell_amount > 0: # 卖出股票 result = user.sell(code=code, price=sell_price, amount=sell_amount, entrust_prop='limit') print(f'卖出{code},数量为{sell_amount},价格为{sell_price},卖出结果为{result}') else: print('未触发交易条件')

这就是完整的Dual Thrust策略代码,其中包含了连接和操作券商账户、获取数据、计算买卖阈值、判断购买数量和下单操作等流程。需要注意的是,在实际交易中,我们还需要考虑风险控制、交易费用、跟踪止损等因素。(注意:当K1<K2时,多头相对容易被触发;当K1>K2时,空头相对容易被触发。因此,使用策略时,可参考历史数据测试最优参数,另可根据对后势的研判,或从大周期的技术指标,阶段性地动态调整K1和K2的值。)

文章图片3

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多