def run():
    codes = list(get_all_stock_codes())
    codes.reverse()
    codes = ['000725']
    result_list = []
    for code in tqdm(codes):
        df = get_stock_k_line(code, date_start='2016-01-01')

        code_dict = line_hammer_and_hang(code, df)
        result_list.append(code_dict)

        code_dict = shape_dark_cloud_cover_top(code, df)
        result_list.append(code_dict)

        code_dict = shape_devour(code, df)
        result_list.append(code_dict)

        code_dict = shape_morning_and_evening_star(code, df)
        result_list.append(code_dict)

        code_dict = shape_meteor_and_invertedhammer_star(code, df)
        result_list.append(code_dict)

    for result in result_list:
        for code, d in result.items():
            if d['up']:
                print code, " up:", d['up']

    for result in result_list:
        for code, d in result.items():
            if d['down']:
                print code, " down:", d['down']

    print 'end'
示例#2
0
def run():
    codes = list(get_all_stock_codes())
    codes.reverse()
    #codes = ['603999']
    result_list = []
    for code in tqdm(codes):
        df = get_stock_k_line(code, date_start='2016-01-01')
        #code_dict = line_hammer_and_hang(code, df)
        #code_dict = shape_devour(code, df)
        #code_dict = shape_morning_and_evening_star(code, df)
        code_dict = shape_meteor_and_invertedhammer_star(code, df)


        result_list.append(code_dict)

    for result in result_list:
        for code, d in result.items():
            if d['up']:
                print code, " up:", d['up']

    for result in result_list:
        for code, d in result.items():
            if d['down']:
                print code, " down:", d['down']

    print 'end'
示例#3
0
def fibonacci():
    df_gem = ts.get_gem_classified() #创业板

    for ix, row in df_gem.iterrows():
        code = row['code']
        df_price = dg.get_stock_k_line(code, date_start='2015-01-04')
        print df_price.head()
        returns = df_price['close'].pct_change()
        returns[0] = 0
        print returns
示例#4
0
def tread_track_live_trading(code, price_now, df=None):

    # 分析某个时间段的股票
    #dateS = datetime.datetime.today().date() + datetime.timedelta(-100)
    #date_start = dateS.strftime("%Y-%m-%d")
    #df = df[df.index > date_start]

    try:
        df = get_stock_k_line(code)
        #df = df.reindex(df.index[::-1])
    except Exception as e:
        print str(e)
        return
    #print df

    close_price = df['close'].get_values()
    close_price = np.append(close_price, float(price_now))
    ma_short = pd.rolling_mean(close_price, prama_ma_short)
    ma_long = pd.rolling_mean(close_price, prama_ma_long)
    #print ma_short

    signal = SIGNAL_SALE

    print '交易开始'

    plt.figure(figsize=(16, 8))
    #plt.plot(range(len(ma_short)), ma_short.get_values(), label=code, color="b", linewidth=1)

    plt.xlabel("Time")
    plt.ylabel("Price")

    # 过滤微小波动
    extreIndex = -1  #极值点的索引
    for i in range(prama_ma_short + 1, len(ma_short) - 1):
        bMax = ma_short[i] > ma_short[i - 1] and ma_short[i] > ma_short[
            i + 1]  # 极大值的条件
        bMin = ma_short[i] < ma_short[i - 1] and ma_short[i] < ma_short[
            i + 1]  # 极小值的条件
        if bMax or bMin:
            extreIndex = i
        elif extreIndex > 0:
            if ma_short[i] > ma_short[extreIndex]*(1-filter_range) and \
                    ma_short[i] < ma_short[extreIndex]*(1+filter_range):
                ma_short[i] = ma_short[extreIndex]
                #print i,ma_short[i]

    #plt.plot(range(len(ma_short.get_values())), ma_short.get_values(), label=code, color="r", linewidth=1)

    # 交易次数
    count_sale = 0
    count_buy = 0

    min_index_pre = 0  #前一个极小值
    max_index_pre = 0  #前一个极大值

    # 止损位
    keep_stop_price = 0
    keep_stop_index = 0

    # 止赢位
    keep_win_price = 0
    keep_win_index = 0

    total = 0
    price_buy = 0
    price_init = 0
    money_init = 50000
    stock_money = money_init
    stock_count = 0

    #for i in range(prama_ma_short+1, len(ma_short)-1):
    for i in range(len(ma_short) - 30, len(ma_short) - 1):

        #滤波后的均线走平时(即处于滤波区间内),将其识别为一个点
        index_post = i + 1

        try:
            while (ma_short[index_post] == ma_short[i]
                   and index_post < len(ma_short) - 1):
                index_post += 1
        except Exception as e:
            print str(e)

        # 长均线保护策略
        bLongMA_protect_close = True
        try:
            bLongMA_protect_close = ma_short[i] > ma_long[i]  # 长均线保护是否关闭
        except Exception as e:
            print str(e)
        #if bLongMA_protect_close == False:
        #print "长均线保护打开", i

        # 高低点比较策略
        if ma_short[i] > ma_short[i -
                                  1] and ma_short[i] > ma_short[index_post]:
            #print '极大值:', ma_short[i], 'pos:', i
            if bLongMA_protect_close and max_index_pre > 0 and ma_short[
                    i] < ma_short[max_index_pre] + drift * (
                        i - max_index_pre) and signal == SIGNAL_BUY:
                signal = SIGNAL_SALE
                print '卖出:', close_price[i], 'pos:', i
                count_sale += 1
                total += close_price[i] - price_buy

                stock_money += stock_count * close_price[i]
                stock_count = 0

            max_index_pre = i
        elif ma_short[i] < ma_short[i -
                                    1] and ma_short[i] < ma_short[index_post]:
            #print '极小值:', ma_short[i], 'pos:', i
            if bLongMA_protect_close and min_index_pre > 0 and ma_short[
                    i] > ma_short[min_index_pre] + drift * (
                        i - min_index_pre) and signal == SIGNAL_SALE:
                signal = SIGNAL_BUY
                print '买入:', close_price[i], 'pos:', i
                count_buy += 1
                price_buy = close_price[i]
                if price_init == 0:
                    price_init = price_buy

                stock_count = (stock_money / 100) / close_price[i] * 100
                stock_money = stock_money - stock_count * close_price[i]
            min_index_pre = i

        # 高低点突破策略
        # 股价突破前一个低点加漂移项,则卖出
        elif bLongMA_protect_close and signal == SIGNAL_BUY and min_index_pre > 0 and \
                ma_short[i] < ma_short[min_index_pre] + drift*(i-min_index_pre):
            signal = SIGNAL_SALE
            print '卖出:', close_price[i], 'pos:', i
            count_sale += 1
            total += close_price[i] - price_buy

            stock_money += stock_count * close_price[i]
            stock_count = 0

        # 股价突破前一个高点加漂移项,则买入
        elif bLongMA_protect_close and signal == SIGNAL_SALE and max_index_pre > 0 and \
                ma_short[i] > ma_short[max_index_pre] + drift*(i-max_index_pre):
            signal = SIGNAL_BUY
            print '买入:', close_price[i], 'pos:', i
            count_buy += 1
            price_buy = close_price[i]

            stock_count = (stock_money / 100) / close_price[i] * 100
            stock_money = stock_money - stock_count * close_price[i]

        # 大波段保护策略
        elif min_index_pre > 0 and ma_short[i] >= ma_short[min_index_pre] * (
                1 + param_big_band):
            keep_stop_price = ma_short[i] * (1 - protect_big_band)  #止损位
            keep_stop_index = i
        elif bLongMA_protect_close and signal == SIGNAL_BUY and keep_stop_price > 0 and \
                 ma_short[i] < keep_stop_price + drift*(i-keep_stop_index):
            signal = SIGNAL_SALE
            print '卖出:', close_price[i], 'pos:', i
            count_sale += 1
            total += close_price[i] - price_buy

            stock_money += stock_count * close_price[i]
            stock_count = 0

    print "buy count:", count_buy
    print "sale count:", count_sale

    if stock_count > 0:
        stock_money += stock_count * close_price[-1]
        total += close_price[-1] - price_buy

    print "每股盈利:", total, "收益率:", (stock_money -
                                   money_init) / money_init * 100, "%\n"

    print '交易结束'

    plt.grid()
    #plt.legend()
    #plt.show()
    return (stock_money - money_init) / money_init * 100
示例#5
0
def tread_track_backtest(code, df=None):

    df = get_stock_k_line(code, date_start='2015-12-30', date_end='2016-05-05')
    if len(df) == 0:
        return None

    print df.head(2)
    # 分析某个时间段的股票
    #dateS = datetime.datetime.today().date() + datetime.timedelta(-100)
    #date_start = dateS.strftime("%Y-%m-%d")
    #df = df[df.index > date_start]
    #print df

    # try:
    #     df = df.reindex(df.index[::-1])
    # except Exception as e:
    #     print str(e)
    #     return
    #print df

    close_price = df['close'].get_values()
    ma_short = pd.rolling_mean(df['close'], prama_ma_short)
    ma_long = pd.rolling_mean(df['close'], prama_ma_long)
    #print ma_short

    signal = SIGNAL_SALE

    print '交易开始'

    #plt.figure(figsize=(16,8))
    #plt.plot(range(len(ma_short)), ma_short.get_values(), label=code, color="b", linewidth=1)

    # plt.xlabel("Time")
    # plt.ylabel("Price")

    # 判断极点
    #     for i in range(prama_ma_short+1, len(ma_short)-1):
    #         if ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[i+1]:
    #             print '极大值:', ma_short[i], 'pos:', i
    #
    #         elif ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[i+1]:
    #             print '极小值:', ma_short[i], 'pos:', i

    # 过滤微小波动
    extreIndex = -1  #极值点的索引
    for i in range(prama_ma_short + 1, len(ma_short) - 1):
        bMax = ma_short[i] > ma_short[i - 1] and ma_short[i] > ma_short[
            i + 1]  # 极大值的条件
        bMin = ma_short[i] < ma_short[i - 1] and ma_short[i] < ma_short[
            i + 1]  # 极小值的条件
        if bMax or bMin:
            extreIndex = i
        elif extreIndex > 0:
            if ma_short[i] > ma_short[extreIndex]*(1-filter_range) and \
                    ma_short[i] < ma_short[extreIndex]*(1+filter_range):
                ma_short[i] = ma_short[extreIndex]
                #print i,ma_short[i]

    xticklabels = df['date'].apply(lambda x: str(x)).get_values()

    # print xticklabels[:5]
    # print xticklabels[-5:]

    #plt.plot(df['date'].get_values(), ma_short.get_values(), label=code, color="r", linewidth=1)
    #plt.plot(df['date'].get_values(), ma_short.get_values(), color="r")

    def wavlet_plt():
        # trick to get the axes
        fig, ax = plt.subplots()

        xValues = close_price[-200:]
        ax.plot(xValues, label=code, color="r", linewidth=1)
        zValues = cwavelet.getWaveletData(xValues, 'db2', 2, 'sqtwolog')
        zxValue = np.arange(0, len(zValues), 1)
        #plt.figure(figsize=(16,8))

        ax.plot(zxValue, zValues, color="b", linewidth=2)
        ax.grid()

        # make ticks and tick labels
        xticks = range(0, len(xValues) + 1, 10)
        #xticklabels=['2000-01-0'+str(n) for n in range(1,len(xValues)+1)]
        xticklabels = df['date'].apply(lambda x: str(x)).get_values()

        # set ticks and tick labels
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticklabels, rotation=15)

        #plt.legend()
        plt.show()

    min_index_pre = 0  #前一个极小值
    max_index_pre = 0  #前一个极大值

    keep_stop_up_price = 0
    keep_stop_down_price = 0

    stockPos = StockPosition(50000, code)

    #for i in range(prama_ma_short+1, len(ma_short)-1):
    for i in range(prama_ma_long - 1, len(ma_short) - 1):
        # print prama_ma_long, len(ma_short)-1
        # print ma_short[prama_ma_long]
        # print ma_long[prama_ma_long]

        #滤波后的均线走平时(即处于滤波区间内),将其识别为一个点
        index_post = i + 1
        while (ma_short[index_post] == ma_short[i]
               and index_post < len(ma_short) - 1):
            index_post += 1

        # 长均线保护策略:
        # bLongMA_forbid_buy = ma_short[i] < ma_long[i] # 买入保护
        # bLongMA_forbid_sale = not bLongMA_forbid_buy      # 卖出保护
        #
        # if bLongMA_forbid_buy and signal == SIGNAL_BUY:
        #     signal = SIGNAL_SALE
        #     stockPos.sale(close_price[i], str(df.ix[i, 'date']))
        #     min_index_pre = 0
        #     max_index_pre = 0
        #     keep_stop_up_price = 0
        #     keep_stop_down_price = 0
        #     continue
        # if bLongMA_forbid_buy and signal == SIGNAL_SALE:
        #     continue

        #     if len(stockPos.transaction_records): # 有交易以后才考虑此情况
        #         signal = SIGNAL_BUY
        #         stockPos.buy(close_price[i], str(df.ix[i, 'date']))
        #         #print '买入:', close_price[i], '  ', str(df.ix[i, 'date'])
        #         continue

        # 高低点比较策略
        if ma_short[i] > ma_short[
                i - 1] and ma_short[i] > ma_short[index_post]:  # 极大值
            # <卖出> 如果当前高点比前一个高点的向下漂移项低,则空头开仓或持有空头;
            # <买入> 如果当前高点比前一个高点的向上漂移项高,则多头开仓或持有多头;
            if max_index_pre > 0 and i > max_index_pre:

                if signal == SIGNAL_BUY and ma_short[i] < ma_short[
                        max_index_pre] - drift * (i - max_index_pre):
                    signal = SIGNAL_SALE
                    stockPos.sale(close_price[i], str(df.ix[i, 'date']))
                    min_index_pre = 0
                    max_index_pre = 0
                    keep_stop_up_price = 0
                    keep_stop_down_price = 0
                    continue
                elif signal == SIGNAL_SALE and ma_short[i] > ma_short[
                        max_index_pre] + drift * (i - max_index_pre):
                    signal = SIGNAL_BUY
                    stockPos.buy(close_price[i], str(df.ix[i, 'date']))
                    keep_stop_up_price = 0
                    keep_stop_down_price = 0
                    continue

            max_index_pre = i
        elif ma_short[i] < ma_short[
                i - 1] and ma_short[i] < ma_short[index_post]:  # 极小值
            # < 买入 > 如果当前低点比前一个低点的向上漂移项高,则多头开仓或持有多头;
            # < 卖出 > 如果当前低点比前一个低点的向下漂移项低,则空头开仓或持有空头
            if min_index_pre > 0 and i > min_index_pre:
                if signal == SIGNAL_SALE and ma_short[i] > ma_short[
                        min_index_pre] + drift * (i - min_index_pre):
                    signal = SIGNAL_BUY
                    stockPos.buy(close_price[i], str(df.ix[i, 'date']))
                    keep_stop_up_price = 0
                    keep_stop_down_price = 0
                    continue
                elif signal == SIGNAL_BUY and ma_short[i] > ma_short[
                        min_index_pre] - drift * (i - min_index_pre):
                    signal = SIGNAL_SALE
                    stockPos.sale(close_price[i], str(df.ix[i, 'date']))
                    min_index_pre = 0
                    max_index_pre = 0
                    keep_stop_up_price = 0
                    keep_stop_down_price = 0
                    continue

            min_index_pre = i

        # 高低点突破策略
        # <卖出>如果滤波后的均线比前一个低点的向下漂移项低,则空头开仓或持有空头。
        elif signal == SIGNAL_BUY and min_index_pre > 0 and ma_short[
                i] < ma_short[min_index_pre] - drift * (i - min_index_pre):
            signal = SIGNAL_SALE
            stockPos.sale(close_price[i], str(df.ix[i, 'date']))
            min_index_pre = 0
            max_index_pre = 0
            keep_stop_up_price = 0
            keep_stop_down_price = 0
            continue

        # <买入>如果滤波后的均线比前一个高点的向上漂移项高,则多头开仓或持有多头。
        elif signal == SIGNAL_SALE and max_index_pre > 0 and ma_short[
                i] > ma_short[max_index_pre] + drift * (i - max_index_pre):
            signal = SIGNAL_BUY
            stockPos.buy(close_price[i], str(df.ix[i, 'date']))
            keep_stop_up_price = 0
            keep_stop_down_price = 0
            continue

        # 大波段保护策略
        ## 向上的大波段
        if min_index_pre > 0 and close_price[i] >= ma_short[min_index_pre] * (
                1 + param_big_band):
            if close_price[i] * (1 - protect_big_band) > keep_stop_up_price:
                keep_stop_up_price = close_price[i] * (1 - protect_big_band
                                                       )  # 止盈位
                keep_stop_up_index = i
        if signal == SIGNAL_BUY and keep_stop_up_price > 0 and \
                 close_price[i] < keep_stop_up_price + drift*(i-keep_stop_up_index):
            signal = SIGNAL_SALE
            stockPos.sale(close_price[i], str(df.ix[i, 'date']))
            min_index_pre = 0
            max_index_pre = 0
            keep_stop_up_price = 0
            keep_stop_down_price = 0
            continue

        ## 向下的大波段
        if max_index_pre > 0 and close_price[i] <= ma_short[max_index_pre] * (
                1 - param_big_band):
            if keep_stop_down_price == 0 or close_price[i] * (
                    1 + protect_big_band) < keep_stop_down_price:
                keep_stop_down_price = close_price[i] * (1 + protect_big_band
                                                         )  # 止损位
                keep_stop_down_index = i
        if signal == SIGNAL_SALE and keep_stop_down_price > 0 and \
                        close_price[i] > keep_stop_down_price + drift * (i + keep_stop_down_index):

            signal = SIGNAL_BUY
            keep_stop_up_price = 0
            keep_stop_down_price = 0
            stockPos.buy(close_price[i], str(df.ix[i, 'date']))
            continue

    stockPos.current_price = close_price[-1]
    stockPos.summary()

    print '交易结束'

    #plt.grid()
    #plt.legend()
    #plt.show()
    return stockPos
示例#6
0
def tread_track_live_trading(code, price_now, df=None):
    
    # 分析某个时间段的股票
    #dateS = datetime.datetime.today().date() + datetime.timedelta(-100)
    #date_start = dateS.strftime("%Y-%m-%d")
    #df = df[df.index > date_start]
    
    try:
        df = get_stock_k_line(code)
        df = df.reindex(df.index[::-1])
    except Exception as e:
        print str(e)
        return    
    #print df
    
    close_price = df['close'].get_values()
    close_price = np.append(close_price, float(price_now))
    ma_short = pd.rolling_mean(close_price, prama_ma_short)
    ma_long  = pd.rolling_mean(close_price, prama_ma_long)
    #print ma_short
    
    
    signal = SIGNAL_SALE
        
    print '交易开始'
    
    plt.figure(figsize=(16,8))
    #plt.plot(range(len(ma_short)), ma_short.get_values(), label=code, color="b", linewidth=1)
    
    plt.xlabel("Time")
    plt.ylabel("Price")
    
    # 过滤微小波动
    extreIndex = -1 #极值点的索引        
    for i in range(prama_ma_short+1, len(ma_short)-1):
        bMax = ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[i+1] # 极大值的条件
        bMin = ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[i+1] # 极小值的条件
        if bMax or bMin:
            extreIndex = i
        elif extreIndex > 0:
            if ma_short[i] > ma_short[extreIndex]*(1-filter_range) and \
                    ma_short[i] < ma_short[extreIndex]*(1+filter_range):
                ma_short[i] = ma_short[extreIndex]
                #print i,ma_short[i]
    
    #plt.plot(range(len(ma_short.get_values())), ma_short.get_values(), label=code, color="r", linewidth=1)
    
    # 交易次数
    count_sale = 0 
    count_buy = 0
    
    min_index_pre = 0 #前一个极小值
    max_index_pre = 0 #前一个极大值
    
    # 止损位
    keep_stop_price = 0 
    keep_stop_index = 0
    
    # 止赢位
    keep_win_price = 0 
    keep_win_index = 0
    
    total = 0
    price_buy = 0
    price_init = 0
    money_init = 50000
    stock_money = money_init
    stock_count = 0
    
    
    #for i in range(prama_ma_short+1, len(ma_short)-1):
    for i in range(len(ma_short)-30, len(ma_short)-1):    
        
        #滤波后的均线走平时(即处于滤波区间内),将其识别为一个点
        index_post = i+1
        
        try:
            while(ma_short[index_post] == ma_short[i] and index_post < len(ma_short)-1):
                index_post += 1
        except Exception as e:
            print str(e)
            
        # 长均线保护策略
        bLongMA_protect_close = True
        try:
            bLongMA_protect_close = ma_short[i] > ma_long[i] # 长均线保护是否关闭
        except Exception as e:
            print str(e)    
        #if bLongMA_protect_close == False:
            #print "长均线保护打开", i    
        
        # 高低点比较策略
        if ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[index_post]:
            #print '极大值:', ma_short[i], 'pos:', i
            if bLongMA_protect_close and max_index_pre > 0 and ma_short[i] < ma_short[max_index_pre] + drift*(i-max_index_pre) and signal == SIGNAL_BUY:
                signal = SIGNAL_SALE
                print '卖出:', close_price[i], 'pos:', i
                count_sale += 1
                total += close_price[i] - price_buy
                
                stock_money += stock_count * close_price[i]
                stock_count = 0
                
            max_index_pre = i
        elif ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[index_post]: 
            #print '极小值:', ma_short[i], 'pos:', i
            if bLongMA_protect_close and min_index_pre > 0 and ma_short[i] > ma_short[min_index_pre] + drift*(i-min_index_pre)  and signal == SIGNAL_SALE:
                signal = SIGNAL_BUY
                print '买入:', close_price[i], 'pos:', i
                count_buy += 1
                price_buy = close_price[i]
                if price_init == 0:
                    price_init = price_buy
                
                stock_count = (stock_money/100)/close_price[i]*100
                stock_money = stock_money - stock_count*close_price[i]
            min_index_pre = i
        
        # 高低点突破策略    
        # 股价突破前一个低点加漂移项,则卖出
        elif bLongMA_protect_close and signal == SIGNAL_BUY and min_index_pre > 0 and \
                ma_short[i] < ma_short[min_index_pre] + drift*(i-min_index_pre):
            signal = SIGNAL_SALE
            print '卖出:', close_price[i], 'pos:', i
            count_sale += 1
            total += close_price[i] - price_buy
            
            stock_money += stock_count * close_price[i]
            stock_count = 0
                
        # 股价突破前一个高点加漂移项,则买入    
        elif bLongMA_protect_close and signal == SIGNAL_SALE and max_index_pre > 0 and \
                ma_short[i] > ma_short[max_index_pre] + drift*(i-max_index_pre):    
            signal = SIGNAL_BUY
            print '买入:', close_price[i], 'pos:', i
            count_buy += 1
            price_buy = close_price[i]
            
            stock_count = (stock_money/100)/close_price[i]*100
            stock_money = stock_money - stock_count*close_price[i]

        # 大波段保护策略
        elif min_index_pre > 0 and ma_short[i] >= ma_short[min_index_pre]*(1+param_big_band):
            keep_stop_price = ma_short[i] * (1-protect_big_band) #止损位
            keep_stop_index = i
        elif bLongMA_protect_close and signal == SIGNAL_BUY and keep_stop_price > 0 and \
                 ma_short[i] < keep_stop_price + drift*(i-keep_stop_index):    
            signal = SIGNAL_SALE
            print '卖出:', close_price[i], 'pos:', i
            count_sale += 1
            total += close_price[i] - price_buy
            
            stock_money += stock_count * close_price[i]
            stock_count = 0
        
        
            
            
    print "buy count:", count_buy
    print "sale count:", count_sale
    
    if stock_count > 0:
        stock_money += stock_count * close_price[-1]
        total += close_price[-1] - price_buy
    
    print "每股盈利:", total, "收益率:", (stock_money-money_init)/money_init*100,"%\n"
    
    print '交易结束'        
            
    plt.grid()
    #plt.legend()
    #plt.show()
    return (stock_money-money_init)/money_init*100 
示例#7
0
def tread_track_backtest(code, df=None):

    df = get_stock_k_line(code, date_start='2015-12-30', date_end='2016-05-05')
    if len(df) == 0:
        return None

    print df.head(2)
    # 分析某个时间段的股票
    #dateS = datetime.datetime.today().date() + datetime.timedelta(-100)
    #date_start = dateS.strftime("%Y-%m-%d")
    #df = df[df.index > date_start]
    #print df
    
    # try:
    #     df = df.reindex(df.index[::-1])
    # except Exception as e:
    #     print str(e)
    #     return
    #print df
    
    close_price = df['close'].get_values()
    ma_short = pd.rolling_mean(df['close'], prama_ma_short)
    ma_long  = pd.rolling_mean(df['close'], prama_ma_long)
    #print ma_short
    
    signal = SIGNAL_SALE
        
    print '交易开始'
    
    #plt.figure(figsize=(16,8))
    #plt.plot(range(len(ma_short)), ma_short.get_values(), label=code, color="b", linewidth=1)
    
    # plt.xlabel("Time")
    # plt.ylabel("Price")
    
    
        
    # 判断极点
#     for i in range(prama_ma_short+1, len(ma_short)-1):
#         if ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[i+1]:
#             print '极大值:', ma_short[i], 'pos:', i
#            
#         elif ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[i+1]: 
#             print '极小值:', ma_short[i], 'pos:', i
    
    # 过滤微小波动
    extreIndex = -1 #极值点的索引        
    for i in range(prama_ma_short+1, len(ma_short)-1):
        bMax = ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[i+1] # 极大值的条件
        bMin = ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[i+1] # 极小值的条件
        if bMax or bMin:
            extreIndex = i
        elif extreIndex > 0:
            if ma_short[i] > ma_short[extreIndex]*(1-filter_range) and \
                    ma_short[i] < ma_short[extreIndex]*(1+filter_range):
                ma_short[i] = ma_short[extreIndex]
                #print i,ma_short[i]

    xticklabels = df['date'].apply(lambda x : str(x)).get_values()
    # print xticklabels[:5]
    # print xticklabels[-5:]

    #plt.plot(df['date'].get_values(), ma_short.get_values(), label=code, color="r", linewidth=1)
    #plt.plot(df['date'].get_values(), ma_short.get_values(), color="r")

    def wavlet_plt():
        # trick to get the axes
        fig,ax = plt.subplots()

        xValues = close_price[-200:]
        ax.plot(xValues, label=code, color="r", linewidth=1)
        zValues = cwavelet.getWaveletData(xValues, 'db2', 2, 'sqtwolog')
        zxValue = np.arange(0,len(zValues),1)
        #plt.figure(figsize=(16,8))

        ax.plot(zxValue, zValues, color="b", linewidth=2)
        ax.grid()

        # make ticks and tick labels
        xticks=range(0, len(xValues)+1,10)
        #xticklabels=['2000-01-0'+str(n) for n in range(1,len(xValues)+1)]
        xticklabels = df['date'].apply(lambda x : str(x)).get_values()


        # set ticks and tick labels
        ax.set_xticks(xticks)
        ax.set_xticklabels(xticklabels,rotation=15)

        #plt.legend()
        plt.show()

    min_index_pre = 0 #前一个极小值
    max_index_pre = 0 #前一个极大值

    keep_stop_up_price = 0
    keep_stop_down_price = 0

    stockPos = StockPosition(50000, code)
    
    #for i in range(prama_ma_short+1, len(ma_short)-1):
    for i in range(prama_ma_long-1, len(ma_short)-1):
        # print prama_ma_long, len(ma_short)-1
        # print ma_short[prama_ma_long]
        # print ma_long[prama_ma_long]

        #滤波后的均线走平时(即处于滤波区间内),将其识别为一个点
        index_post = i+1
        while (ma_short[index_post] == ma_short[i] and index_post < len(ma_short) - 1):
            index_post += 1
            
        # 长均线保护策略:
        # bLongMA_forbid_buy = ma_short[i] < ma_long[i] # 买入保护
        # bLongMA_forbid_sale = not bLongMA_forbid_buy      # 卖出保护
        #
        # if bLongMA_forbid_buy and signal == SIGNAL_BUY:
        #     signal = SIGNAL_SALE
        #     stockPos.sale(close_price[i], str(df.ix[i, 'date']))
        #     min_index_pre = 0
        #     max_index_pre = 0
        #     keep_stop_up_price = 0
        #     keep_stop_down_price = 0
        #     continue
        # if bLongMA_forbid_buy and signal == SIGNAL_SALE:
        #     continue

        #     if len(stockPos.transaction_records): # 有交易以后才考虑此情况
        #         signal = SIGNAL_BUY
        #         stockPos.buy(close_price[i], str(df.ix[i, 'date']))
        #         #print '买入:', close_price[i], '  ', str(df.ix[i, 'date'])
        #         continue

        # 高低点比较策略
        if ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[index_post]: # 极大值
            # <卖出> 如果当前高点比前一个高点的向下漂移项低,则空头开仓或持有空头;
            # <买入> 如果当前高点比前一个高点的向上漂移项高,则多头开仓或持有多头;
            if max_index_pre > 0 and i > max_index_pre:

                if signal == SIGNAL_BUY and ma_short[i] < ma_short[max_index_pre] - drift*(i-max_index_pre):
                    signal = SIGNAL_SALE
                    stockPos.sale(close_price[i], str(df.ix[i, 'date']))
                    min_index_pre = 0
                    max_index_pre = 0
                    keep_stop_up_price = 0
                    keep_stop_down_price = 0
                    continue
                elif signal == SIGNAL_SALE and ma_short[i] > ma_short[max_index_pre] + drift*(i-max_index_pre):
                    signal = SIGNAL_BUY
                    stockPos.buy(close_price[i], str(df.ix[i, 'date']))
                    keep_stop_up_price = 0
                    keep_stop_down_price = 0
                    continue
                
            max_index_pre = i
        elif ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[index_post]:  # 极小值
            # < 买入 > 如果当前低点比前一个低点的向上漂移项高,则多头开仓或持有多头;
            # < 卖出 > 如果当前低点比前一个低点的向下漂移项低,则空头开仓或持有空头
            if min_index_pre > 0 and i > min_index_pre:
                if signal == SIGNAL_SALE and ma_short[i] > ma_short[min_index_pre] + drift*(i-min_index_pre):
                    signal = SIGNAL_BUY
                    stockPos.buy(close_price[i], str(df.ix[i, 'date']))
                    keep_stop_up_price = 0
                    keep_stop_down_price = 0
                    continue
                elif signal == SIGNAL_BUY and ma_short[i] > ma_short[min_index_pre] - drift*(i-min_index_pre):
                    signal = SIGNAL_SALE
                    stockPos.sale(close_price[i], str(df.ix[i, 'date']))
                    min_index_pre = 0
                    max_index_pre = 0
                    keep_stop_up_price = 0
                    keep_stop_down_price = 0
                    continue

            min_index_pre = i
        
        # 高低点突破策略    
        # <卖出>如果滤波后的均线比前一个低点的向下漂移项低,则空头开仓或持有空头。
        elif signal == SIGNAL_BUY and min_index_pre > 0 and ma_short[i] < ma_short[min_index_pre] - drift*(i-min_index_pre):
            signal = SIGNAL_SALE
            stockPos.sale(close_price[i], str(df.ix[i, 'date']))
            min_index_pre = 0
            max_index_pre = 0
            keep_stop_up_price = 0
            keep_stop_down_price = 0
            continue
                
        # <买入>如果滤波后的均线比前一个高点的向上漂移项高,则多头开仓或持有多头。
        elif signal == SIGNAL_SALE and max_index_pre > 0 and ma_short[i] > ma_short[max_index_pre] + drift*(i-max_index_pre):
            signal = SIGNAL_BUY
            stockPos.buy(close_price[i], str(df.ix[i, 'date']))
            keep_stop_up_price = 0
            keep_stop_down_price = 0
            continue

        # 大波段保护策略
        ## 向上的大波段
        if min_index_pre > 0 and close_price[i] >= ma_short[min_index_pre] * (1 + param_big_band):
            if close_price[i] * (1 - protect_big_band) > keep_stop_up_price:
                keep_stop_up_price = close_price[i] * (1 - protect_big_band)  # 止盈位
                keep_stop_up_index = i
        if signal == SIGNAL_BUY and keep_stop_up_price > 0 and \
                 close_price[i] < keep_stop_up_price + drift*(i-keep_stop_up_index):
            signal = SIGNAL_SALE
            stockPos.sale(close_price[i], str(df.ix[i, 'date']))
            min_index_pre = 0
            max_index_pre = 0
            keep_stop_up_price = 0
            keep_stop_down_price = 0
            continue
        
        ## 向下的大波段
        if max_index_pre > 0 and close_price[i] <= ma_short[max_index_pre] * (1 - param_big_band):
            if keep_stop_down_price == 0 or close_price[i] * (1 + protect_big_band) < keep_stop_down_price:
                keep_stop_down_price = close_price[i] * (1 + protect_big_band)  # 止损位
                keep_stop_down_index = i
        if signal == SIGNAL_SALE and keep_stop_down_price > 0 and \
                        close_price[i] > keep_stop_down_price + drift * (i + keep_stop_down_index):

            signal = SIGNAL_BUY
            keep_stop_up_price = 0
            keep_stop_down_price = 0
            stockPos.buy(close_price[i], str(df.ix[i, 'date']))
            continue

    stockPos.current_price = close_price[-1]
    stockPos.summary()
    
    print '交易结束'        
            
    #plt.grid()
    #plt.legend()
    #plt.show()
    return stockPos
示例#8
0
def tread_track_backtest(code, df=None):

    df = get_stock_k_line(code)
    
    # 分析某个时间段的股票
    #dateS = datetime.datetime.today().date() + datetime.timedelta(-100)
    #date_start = dateS.strftime("%Y-%m-%d")
    #df = df[df.index > date_start]
    #print df
    
    # try:
    #     df = df.reindex(df.index[::-1])
    # except Exception as e:
    #     print str(e)
    #     return
    #print df
    
    close_price = df['close'].get_values()
    ma_short = pd.rolling_mean(df['close'], prama_ma_short)
    ma_long  = pd.rolling_mean(df['close'], prama_ma_long)
    #print ma_short
    
    signal = SIGNAL_SALE
        
    print '交易开始'
    
    plt.figure(figsize=(16,8))
    #plt.plot(range(len(ma_short)), ma_short.get_values(), label=code, color="b", linewidth=1)
    
    plt.xlabel("Time")
    plt.ylabel("Price")
    
    
        
    # 判断极点
#     for i in range(prama_ma_short+1, len(ma_short)-1):
#         if ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[i+1]:
#             print '极大值:', ma_short[i], 'pos:', i
#            
#         elif ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[i+1]: 
#             print '极小值:', ma_short[i], 'pos:', i
    
    # 过滤微小波动
    extreIndex = -1 #极值点的索引        
    for i in range(prama_ma_short+1, len(ma_short)-1):
        bMax = ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[i+1] # 极大值的条件
        bMin = ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[i+1] # 极小值的条件
        if bMax or bMin:
            extreIndex = i
        elif extreIndex > 0:
            if ma_short[i] > ma_short[extreIndex]*(1-filter_range) and \
                    ma_short[i] < ma_short[extreIndex]*(1+filter_range):
                ma_short[i] = ma_short[extreIndex]
                #print i,ma_short[i]
    
    #plt.plot(df.index, ma_short.get_values(), label=code, color="r", linewidth=1)

    # trick to get the axes
    fig,ax = plt.subplots()

    xValues = close_price[-200:]
    ax.plot(xValues, label=code, color="r", linewidth=1)
    zValues = cwavelet.getWaveletData(xValues, 'db2', 2, 'sqtwolog')
    zxValue = np.arange(0,len(zValues),1)
    #plt.figure(figsize=(16,8))

    ax.plot(zxValue, zValues, color="b", linewidth=2)
    ax.grid()

    # make ticks and tick labels
    xticks=range(0, len(xValues)+1,10)
    xticklabels=['2000-01-0'+str(n) for n in range(1,len(xValues)+1)]

    # set ticks and tick labels
    ax.set_xticks(xticks)
    ax.set_xticklabels(xticklabels,rotation=15)

    #plt.legend()
    plt.show()

    # 交易次数    count_sale = 0
    count_buy = 0
    
    min_index_pre = 0 #前一个极小值
    max_index_pre = 0 #前一个极大值
    
    # 止损位
    keep_stop_price = 0 
    keep_stop_index = 0
    
    # 止赢位
    keep_win_price = 0 
    keep_win_index = 0
    
    total = 0
    price_buy = 0
    price_init = 0
    money_init = 50000
    stock_money = money_init
    stock_count = 0
    
    
    #for i in range(prama_ma_short+1, len(ma_short)-1):
    for i in range(len(ma_short)-180, len(ma_short)-1):    
        
        #滤波后的均线走平时(即处于滤波区间内),将其识别为一个点
        index_post = i+1
        
        try:
            while(ma_short[index_post] == ma_short[i] and index_post < len(ma_short)-1):
                index_post += 1
        except Exception as e:
            print str(e)
            
        # 长均线保护策略
        bLongMA_protect_close = True
        try:
            bLongMA_protect_close = ma_short[i] > ma_long[i] # 长均线保护是否关闭
        except Exception as e:
            print str(e)    
        #if bLongMA_protect_close == False:
            #print "长均线保护打开", i    
        
        # 高低点比较策略
        if ma_short[i] > ma_short[i-1] and ma_short[i] > ma_short[index_post]:
            #print '极大值:', ma_short[i], 'pos:', i
            if bLongMA_protect_close and max_index_pre > 0 and ma_short[i] < ma_short[max_index_pre] + drift*(i-max_index_pre) and signal == SIGNAL_BUY:
                signal = SIGNAL_SALE
                print '卖出:', close_price[i], 'pos:', i
                #count_sale += 1
                total += close_price[i] - price_buy
                
                stock_money += stock_count * close_price[i]
                stock_count = 0
                
            max_index_pre = i
        elif ma_short[i] < ma_short[i-1] and ma_short[i] < ma_short[index_post]: 
            #print '极小值:', ma_short[i], 'pos:', i
            if bLongMA_protect_close and min_index_pre > 0 and ma_short[i] > ma_short[min_index_pre] + drift*(i-min_index_pre)  and signal == SIGNAL_SALE:
                signal = SIGNAL_BUY
                print '买入:', close_price[i], 'pos:', i
                count_buy += 1
                price_buy = close_price[i]
                if price_init == 0:
                    price_init = price_buy
                
                stock_count = (stock_money/100)/close_price[i]*100
                stock_money = stock_money - stock_count*close_price[i]
            min_index_pre = i
        
        # 高低点突破策略    
        # 股价突破前一个低点加漂移项,则卖出
        elif bLongMA_protect_close and signal == SIGNAL_BUY and min_index_pre > 0 and \
                ma_short[i] < ma_short[min_index_pre] + drift*(i-min_index_pre):
            signal = SIGNAL_SALE
            print '卖出:', close_price[i], 'pos:', i
            #count_sale += 1
            total += close_price[i] - price_buy
            
            stock_money += stock_count * close_price[i]
            stock_count = 0
                
        # 股价突破前一个高点加漂移项,则买入    
        elif bLongMA_protect_close and signal == SIGNAL_SALE and max_index_pre > 0 and \
                ma_short[i] > ma_short[max_index_pre] + drift*(i-max_index_pre):    
            signal = SIGNAL_BUY
            print '买入:', close_price[i], 'pos:', i
            count_buy += 1
            price_buy = close_price[i]
            
            stock_count = (stock_money/100)/close_price[i]*100
            stock_money = stock_money - stock_count*close_price[i]

        # 大波段保护策略
        elif min_index_pre > 0 and ma_short[i] >= ma_short[min_index_pre]*(1+param_big_band):
            keep_stop_price = ma_short[i] * (1-protect_big_band) #止损位
            keep_stop_index = i
        elif bLongMA_protect_close and signal == SIGNAL_BUY and keep_stop_price > 0 and \
                 ma_short[i] < keep_stop_price + drift*(i-keep_stop_index):    
            signal = SIGNAL_SALE
            print '卖出:', close_price[i], 'pos:', i
            #count_sale += 1
            total += close_price[i] - price_buy
            
            stock_money += stock_count * close_price[i]
            stock_count = 0
        
        
            
            
    print "buy count:", count_buy
    #print "sale count:", count_sale
    
    if stock_count > 0:
        stock_money += stock_count * close_price[-1]
        total += close_price[-1] - price_buy
    
    print "每股盈利:", total, "收益率:", (stock_money-money_init)/money_init*100,"%\n"
    
    print '交易结束'        
            
    plt.grid()
    #plt.legend()
    #plt.show()
    return (stock_money-money_init)/money_init*100