コード例 #1
0
ファイル: macd_live_test.py プロジェクト: hbwzhsh/stock
 def __init__(self, stockCsvPath = '', stockData='', df=''):
     
     self.AVR_SHORT = 12
     self.AVR_LONG = 40
         
     if len(stockCsvPath) > 0:
         #方式一
         df_stockHistory = get_stock_k_line(stockData.code)
         if len(df_stockHistory) == 0:
             return
         #df_stockHistory = pd.read_csv(stockCsvPath)
         # 将数据按照交易日期从远到近排序
         df_stockHistory.sort('date', inplace=True)
         self.close_price = df_stockHistory['close'].get_values()
         
         needWrite2Csv = False
         try:
             self.ma_12 = df_stockHistory['ma_12'].get_values()
             self.ma_40 = df_stockHistory['ma_40'].get_values()
         except Exception as e:  
             print '重新计算 ma'   
             self.ma_12 = pd.rolling_mean(self.close_price, self.AVR_SHORT)
             self.ma_40 = pd.rolling_mean(self.close_price, self.AVR_LONG)
             needWrite2Csv = True
             df_stockHistory['ma_12'] = self.ma_12
             df_stockHistory['ma_40'] = self.ma_40
             
         try:
             self.ema_12 = df_stockHistory['ema_12'].get_values()
             self.ema_40 = df_stockHistory['ema_40'].get_values()
         except Exception as e:
             print '重新计算 ema'
             self.ema_12 = pd.ewma(self.close_price, span=self.AVR_SHORT)
             self.ema_40 = pd.ewma(self.close_price, span=self.AVR_LONG)  
             needWrite2Csv = True
             df_stockHistory['ema_12'] = self.ema_12
             df_stockHistory['ema_40'] = self.ema_40
             
         if needWrite2Csv:
             # 将数据按照交易日期从近到远排序
             df_stockHistory.sort('date', ascending = False, inplace=True)
             df_stockHistory.to_csv(stockCsvPath)
             print '保存至'+stockCsvPath
         
         self.close_price = np.append(self.close_price, float(stockData.current))
         
         # 计算当前的ma
         last_ma_12 = sum(self.close_price[-self.AVR_SHORT:])/self.AVR_SHORT;
         last_ma_40 = sum(self.close_price[-self.AVR_LONG:])/self.AVR_LONG;
         self.ma_12 = np.append(self.ema_12, last_ma_12)
         self.ma_40 = np.append(self.ema_40, last_ma_40)
         
         
         # 计算当前价的ema
         last_ema_12 = self.ema_12[-2] * (self.AVR_SHORT-1)/(self.AVR_SHORT+1) + stockData.current * 2/(self.AVR_SHORT+1)
         last_ema_40 = self.ema_40[-2] * (self.AVR_LONG-1)/(self.AVR_LONG+1) + stockData.current * 2/(self.AVR_LONG+1) 
         
         #self.close_price = np.append(self.close_price, float(stockData.current))
         self.ema_12 = np.append(self.ema_12, last_ema_12)
         self.ema_40 = np.append(self.ema_40, last_ema_40)
            
     
     else:
         #方式二
         # 将数据按照交易日期从远到近排序
         df.sort('date', inplace=True)
         self.close_price = df['close'].get_values()
     
         self.ma_12 = pd.rolling_mean(self.close_price, self.AVR_SHORT)
         self.ma_40 = pd.rolling_mean(self.close_price, self.AVR_LONG)
       
         self.ema_12 = pd.ewma(self.close_price, span=self.AVR_SHORT)
         self.ema_40 = pd.ewma(self.close_price, span=self.AVR_LONG)  
コード例 #2
0
ファイル: tread_tracking.py プロジェクト: hbwzhsh/stock
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