从零开始用Python实现股票量化交易之小白笔记(9)

不废话了,直接上成品的代码:

 

#coding=utf-8
from common import ts
import tushare

ts.set_ts_token()
pro = tushare.pro_api()
data = ''
index_ts_code = '000300.SH' 
start_date = '20091201' 
end_date = '20191130'
try:
    df = pro.index_monthly(ts_code=index_ts_code, start_date=start_date, end_date=end_date,
                           fields='ts_code,trade_date,change')
    df_len = df.shape[0] #长度,120 列数是shape[1]

    hold_list = []
    money = 1
    pre_trade_date = ''
    for i in range(df_len-1, 0, -1): #倒序出现
        obj = df.iloc[i]
        index_change = obj['change']
        trade_date = obj['trade_date'] #后面要用

        if len(hold_list) > 0: #如有持股,卖出,回收资金
            percent_money = money/100
            money = 0
            for stock_info in hold_list: #卖出,暂不考虑停牌的情况
                stock_ts_code = stock_info['stock_ts_code']
                pre_close = stock_info['pre_close']
                this_stock_info = pro.monthly(ts_code=stock_ts_code, trade_date=trade_date)
                if this_stock_info.shape[0] == 0:
                    pct_chg = 1 #如该月无任何交易日,则认为原价卖出
                else:
                    pct_chg = this_stock_info.iloc[0]['pct_chg']
                money = money + percent_money*(1+float(pct_chg))
            hold_list.clear() #卖出,不考虑停牌的情况,每个月清一遍
            print(trade_date, money)

        if obj['change'] > 0: #出现买点,买入
            stock_infoes = pro.monthly(trade_date=trade_date) #通用接口有积分频率限制,且只能选取确定的股票的数据,选用月线行情接口
            stock_infoes = stock_infoes.sort_values(by='pct_chg')
            stock_infoes = stock_infoes[0:100] #前一百个
            for i in range(100):
                info = stock_infoes.iloc[i]
                obj_ele = {
                    'stock_ts_code': info['ts_code'],
                    'pre_close': info['close'],
                    'pct_chg': info['pct_chg']}
                hold_list.append(obj_ele)
except Exception as e:
    print(e)

最后的money值为1.8192770251641979

这个策略,十年的收益率是82%。

相关的代码注释都有,大家可以看,如有问题,可留言,我出后续讲解博客文章。

你可能感兴趣的:(python,量化交易,股票)