本篇文章为tushare与talib的学习示例,通过双均线策略演示如何使用talib与tushare。下面我们对代码进行详细解析。
引入3个包,分别是talib,tushare和pandas
import tushare as tsimport pandas as pdimport talib
首先,我们需要获取股票的历史数据行情,这里我们获取格力电器(000651)股票的历史数据行情,我们通过tushare获取。
def get_stock_data(code): # 通过tushare获取数据,前复权后的数据 df_raw = ts.get_k_data(code, autype='qfq') # code数据处理 df_raw["code"] = df_raw.apply(lambda x: add_note(x.code), axis=1) df_raw.to_csv(code + '.csv') return code + '.csv'
获取的股票数据行情,保存到csv,数据格式如下:
接着,我们需要定义一个函数,计算我们要的均线,均线的值我们通过ma1和ma2传入。
def calculate_sma(filename, ma1=5, ma2=10): df = pd.read_csv(filename, index_col='date') # Simple Moving Average SMA 简单移动平均 df['SMA_' + str(ma1)] = talib.MA(df['close'], timeperiod=ma1) df['SMA_' + str(ma2)] = talib.MA(df['close'], timeperiod=ma2) df['compare'] = df.apply(lambda x: compare_diff(x['SMA_' + str(ma1)], x['SMA_' + str(ma2)]), axis=1) df = df[9:] df.to_csv("sma_data.csv") return df
计算结果的文件,存了均线的值,我们示例中的ma1=5日均线,ma2=10日均线。
最后,我们需要根据均线的值做出买卖的决策依据,5日上穿10日均线,买入,5日下穿10日均线,卖出。
def sell_and_buy(df, ma1=5, ma2=10): # 标记均线上穿与下穿 df['match'] = df.compare == df.compare.shift() df.to_csv("sma_change.csv") # 开仓与平仓 df["tag"] = df.apply(lambda row: tag(row.match, row.compare), axis=1) df.to_csv("result.csv")
我们使用tag来标识卖出还是买入,match列表示,本次的5日均线值与10日均线值的比较大小是否改变,如果改变则代表是上穿还是下穿。
我们用定义一个计算盈利。这里我们简单计算下开平仓以及盈利次数,成功率还有最后的总盈亏。
def cal_profit(): df = pd.read_csv("result.csv", index_col='date') df["profit"] = 0 total = 0 win = 0 buyprice = 0 for index, row in df.iterrows(): if row.tag == '买入': buyprice = row.close if row.tag == '卖出' and buyprice != 0: total += 1 # 用这种方式赋值 df.loc[index, 'profit'] = row.close - buyprice if row.close - buyprice > 0: win += 1 percent = round((win / total) * 100, 2) profit = round(df["profit"].sum(),2) print("开平仓次数:", total, "\n盈利次数:", win, "\n成功率:", percent, "%", "\n总共盈亏:", profit) df.to_csv("profit.csv")
最后结果输出如下:
===简单双均线策略====
开平仓次数:34
盈利次数:14
成功率:41.18 %
总共盈亏:4.15
以上,就是我们本次的双均线买卖策略,希望对大家有所帮助。如果觉得有用,希望能帮忙点下【在看】,并且分享到朋友圈哦。
jeevan在这里谢谢大家的支持!
关注我,量化交易工程师,带你一起学习量化交易。后续我会陆续推出一些策略,带大家一起开心的在市场学习如何打开正确盈利的方式。
最后附上完整的源代码:
# encoding:utf-8# !/usr/bin/python"""@Author: jeevan@微信公众号: 大操手量化投资@Site: http://dacaoshou.com@Software: pycharm@File:__init__.py.py@Time:2020/5/31 20:24@Description: 双均线买卖策略,策略源码微信公众号上获取"""import tushare as tsimport pandas as pdimport talibdef add_note(code): return "'" + code# 获取股票数据def get_stock_data(code): # 通过tushare获取数据,前复权后的数据 df_raw = ts.get_k_data(code, autype='qfq') # code数据处理 df_raw["code"] = df_raw.apply(lambda x: add_note(x.code), axis=1) df_raw.to_csv(code + '.csv') return code + '.csv'def compare_diff(param, param1): return 1 if param - param1 >= 0 else -1;def calculate_sma(filename, ma1=5, ma2=10): df = pd.read_csv(filename, index_col='date') # Simple Moving Average SMA 简单移动平均 df['SMA_' + str(ma1)] = talib.MA(df['close'], timeperiod=ma1) df['SMA_' + str(ma2)] = talib.MA(df['close'], timeperiod=ma2) df['compare'] = df.apply(lambda x: compare_diff(x['SMA_' + str(ma1)], x['SMA_' + str(ma2)]), axis=1) df = df[9:] df.to_csv("sma_data.csv") return dfdef tag(match, compare): if match == False and compare == 1: return "买入" if match == False and compare == -1: return "卖出"def sell_and_buy(df, ma1=5, ma2=10): # 标记均线上穿与下穿 df['match'] = df.compare == df.compare.shift() df.to_csv("sma_change.csv") # 开仓与平仓 df["tag"] = df.apply(lambda row: tag(row.match, row.compare), axis=1) df.to_csv("result.csv")def cal_profit(): df = pd.read_csv("result.csv", index_col='date') df["profit"] = 0 total = 0 win = 0 buyprice = 0 for index, row in df.iterrows(): if row.tag == '买入': buyprice = row.close if row.tag == '卖出' and buyprice != 0: total += 1 # 用这种方式赋值 df.loc[index, 'profit'] = row.close - buyprice if row.close - buyprice > 0: win += 1 percent = round((win / total) * 100, 2) profit = round(df["profit"].sum(),2) print("开平仓次数:", total, "\n盈利次数:", win, "\n成功率:", percent, "%", "\n总共盈亏:", profit) df.to_csv("profit.csv")if __name__ == '__main__': print("===简单双均线策略====") code = '000651' # 配置双均线 ma1 = 5 ma2 = 10 # 获取数据并保存到csv文件 filename = get_stock_data(code) # 计算双均线数据并保存 df = calculate_sma(filename, ma1, ma2) # 买入开仓,卖出平仓 sell_and_buy(df, ma1, ma2) # 计算盈利 cal_profit()