分享

用pandas、numpy和ti库实现基于AROON指标的简单趋势交易策略

 禁忌石 2023-06-06 发布于浙江

具体的交易策略代码可以根据不同的交易平台和编程语言进行编写。下面以Python语言为例,用pandas、numpy和ti库实现基于AROON指标的简单趋势交易策略。

文章图片1

首先,导入需要的库:

import pandas as pdimport numpy as npimport talib as taimport tushare as ts from time import sleep

然后,定义获取数据函数,此处以获取tushare上的上证指数为例:

文章图片2
def get_data():    token = '你的token'    ts.set_token(token)     pro = ts.pro_api()    df = pro.index_daily(ts_code='000001.SH', start_date='20150101', end_date='20211231')    df.index = pd.to_datetime(df.trade_date)    df.sort_index(inplace=True)    print('获取数据完毕')    return df

接着,进行数据处理并计算AROON指标:

文章图片3
def process_data(df): df.fillna(method='ffill', inplace=True) high = df.high.values low = df.low.values close = df.close.values aroon_up, aroon_down = ta.AROON(high, low, timeperiod=14) df['aroon_up'] = aroon_up df['aroon_down'] = aroon_down return df

紧接着,编写交易策略函数,该函数通过AROON指标判断市场趋势并进行交易:

文章图片4
def trading_strategy(df):    position = None  # 标记当前持仓情况    cash = 10000.0  # 初始资金    for i in range(10, len(df)):        if df.loc[df.index[i], 'aroon_up'] >= 70 and df.loc[df.index[i-1], 'aroon_up'] < 70:  # 上升趋势开始            if position is not None and position == 'short':                cash += df.loc[df.index[i], 'close'] * 100  # 平空                print('short exit', df.index[i])                position = None            if position is None:                position = 'long'                shares = np.floor(cash / (df.loc[df.index[i], 'close'] * 100))                cash -= shares * (df.loc[df.index[i], 'close'] * 100)                print('long enter', df.index[i])                print('持仓股数:', shares)                print('剩余现金:', cash)        if df.loc[df.index[i], 'aroon_down'] <= 30 and df.loc[df.index[i-1], 'aroon_down'] > 30:  # 下跌趋势开始            if position is not None and position == 'long':                cash += df.loc[df.index[i], 'close'] * 100  # 平多                print('long exit', df.index[i])                position = None            if position is None:                position = 'short'                shares = np.floor(cash / (df.loc[df.index[i], 'close'] * 100))                cash -= shares * (df.loc[df.index[i], 'close'] * 100)                print('short enter', df.index[i])                print('持仓股数:', shares)                print('剩余现金:', cash)

最后,将函数绑定在一起,并运行策略:

文章图片5
if __name__ == '__main__': df = get_data() # 获取数据 df = process_data(df) # 数据预处理,计算AROON指标 trading_strategy(df) # 执行交易策略

需要注意的是,此处的交易策略仅为示例,实际使用时需要根据市场情况和个人风险偏好进行调整。同时,本示例中没有包含手续费、滑点等因素的考虑,实际应用时需要进行相应的补充和修改。

文章图片6

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

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多