以下是一个基于Python的ETF双底交易策略示例代码:
# 导入必要的库
import pandas as pd
import numpy as np
import tushare as ts
import datetime as dt
import ptrade_api
import time
# 在Ptrade上登录账号并获取Token
username = 'your_username'
password = 'your_password'
twofa = 'your_twofa'
token = ptrade_api.get_token(username, password, twofa)
# 选择操作的目标ETF
target_etf = '510050'
# 设定交易参数
buy_threshold = 2 # 买入阈值,当价格在相对低点上涨N%时进行买入
sell_threshold = 5 # 卖出阈值,当价格上涨N%至第一个低点时进行卖出
stop_loss_threshold = 2 # 止损阈值,当价格下跌N%时进行止损
stop_profit_threshold = 10 # 止盈阈值,当价格上涨N%时进行止盈
# 定义双底交易策略函数
def double_bottom_strategy(etf, buy_threshold, sell_threshold, stop_loss_threshold, stop_profit_threshold):
# 获取目标ETF历史价格数据
etf_hist = ts.get_k_data(etf, index=True, start='20181101')
etf_hist.index = pd.to_datetime(etf_hist.date)
# 初始化交易次数、现金余额以及持仓状态
trades = 0
cash = 100000
holding = False
buy_status= False
buy_price = 0 # 用来记录已经购买的价格
# 开始遍历历史数据
for i in range(1, len(etf_hist)):
# 获取当前价格
cur_price = etf_hist['close'][i]
low_price = etf_hist['low'][i]
# 观察双底形态
if (etf_hist['low'][i] < etf_hist['low'][i-1]) and (etf_hist['low'][i-1] < etf_hist['low'][i-2]):
# 第一个低点形成时不进行操作
continue
elif (etf_hist['low'][i] > etf_hist['low'][i-1]) and (etf_hist['low'][i] < etf_hist['high'][i-1]) and (etf_hist['low'][i] > etf_hist['low'][i-2]):
# 第二个低点形成且价格上涨超过买入阈值时进行买入操作
if not buy_status and cur_price > (1 buy_threshold/100) * buy_price:
buy_price = cur_price
shares = cash / cur_price
cash -= shares * cur_price
trades = 1
holding = True
buy_status = True
print("Buy: {}, price: {}".format(etf_hist.index[i], cur_price))
continue
elif holding and (cur_price > max(etf_hist['low'][i-2], buy_price * (1 sell_threshold/100))):
# 价格上涨超过卖出阈值时进行卖出操作
sell_price = cur_price
cash = shares * cur_price
holding = False
buy_price = 0
print("Sell: {}, price: {}".format(etf_hist.index[i], cur_price))
continue
elif holding and (cur_price < buy_price * (1 - stop_loss_threshold/100)):
# 价格下跌超过止损阈值时进行止损操作
sell_price = cur_price
cash = shares * cur_price
holding = False
buy_price = 0
print("Stop loss: {}, price: {}".format(etf_hist.index[i], cur_price))
continue
elif holding and (cur_price > buy_price * (1 stop_profit_threshold/100)):
# 价格上涨超过止盈阈值时进行止盈操作
sell_price = cur_price
cash = shares * cur_price
holding = False
buy_price = 0
print("Stop profit: {}, price: {}".format(etf_hist.index[i], cur_price))
continue
# 输出交易情况
print("Trades: {}, Final cash balance: {}".format(trades, cash))
# 运行交易策略函数
double_bottom_strategy(target_etf, buy_threshold, sell_threshold, stop_loss_threshold, stop_profit_threshold)
需要说明的是,因为Ptrade API没有提供ETF交易的接口,因此该示例代码中没有涉及到Ptrade API操作。大家要注意这双底交易策略仅仅是个简单学习示例,只是用来抛砖引玉,互相学习交流的,请勿用于实盘中去,如大家有好的交易策略可以在评论区交流或私信于我。
Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved