Esempio n. 1
0
def calc_standard_deviation(data, interval):
    if len(data) < interval:
        raise TalibIntervalException

    data = data[-interval:]
    data = np.asarray(data)
    stdev = talib.STDDEV(data, timeperiod=interval)
    return stdev[-1]
Esempio n. 2
0
 def std(self, n, array=False):
     """
     Standard deviation
     """
     result = talib.STDDEV(self.close, n)
     if array:
         return result
     return result[-1]
Esempio n. 3
0
 def std(self, n: int, nbdev: int = 1, array: bool = False) -> Union[float, np.ndarray]:
     """
     Standard deviation.
     """
     result = talib.STDDEV(self.close, n, nbdev)
     if array:
         return result
     return result[-1]
Esempio n. 4
0
def calcFeatures(df,indx):
    
    df1 = pd.DataFrame({'A' : []})

    #for i in range(0,7):
    for i in range(len(indx)):
        
        if (indx[i] and i==0):
            s1 = df['Open'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==1):
            s1 = df['High'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==2):
            s1 = df['Low'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==3):
            s1 = df['Close'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==4):
            s1 = df['Adj Close'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==5):
            s1 = df['Volume'] 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==6):
            s1 = pd.DataFrame( {'RSI': talib.RSI(np.array(df['Close'].values),timeperiod=14) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==7):
            s1 = pd.DataFrame( {'ROC': talib.ROC(np.array(df['Close'].values), timeperiod=10) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==8):
            s1 = pd.DataFrame( {'BETA': talib.BETA(np.array(df['High'].values), \
                np.array(df['Low'].values), timeperiod=5) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==9):
            s1 = pd.DataFrame( {'STDDEV': talib.STDDEV(np.array(df['Close'].values), \
                timeperiod=5, nbdev=1) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==10):
            s1 = pd.DataFrame( {'WILLR': talib.WILLR(np.array(df['Open'].values), \
                np.array(df['High'].values),np.array(df['Close'].values),timeperiod=40) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==11):
            s1 = pd.DataFrame( {'SMA1': talib.SMA(np.array(df['Close'].values), timeperiod=30) }) 
            df1 = pd.concat([df1, s1], axis=1)
        elif (indx[i] and i==12):
            s1 = pd.DataFrame( {'SMA2': talib.SMA(np.array(df['Close'].values), timeperiod=60) }) 
            df1 = pd.concat([df1, s1], axis=1)

    #Delete 'A' column
    df1=df1.drop(columns=['A'])
    
    #Numpy array
    out=np.array(df1.values)
    out=out[~np.any(np.isnan(out), axis=1)]
    
    return out
Esempio n. 5
0
    def calculate_signals(self, df: pd.DataFrame, drop_extra_columns=True):
        m = self.m
        n = self.n
        # 计算均线
        df[COL_MEDIAN] = ta.MA(df[COL_CLOSE], timeperiod=n)

        # 计算上轨、下轨道
        df[COL_STD] = ta.STDDEV(df[COL_CLOSE], timeperiod=n,
                                nbdev=1)  # ddof代表标准差自由度
        df[COL_UPPER] = df[COL_MEDIAN] + m * df[COL_STD]
        df[COL_LOWER] = df[COL_MEDIAN] - m * df[COL_STD]

        # ===找出做多平仓信号
        condition1 = df[COL_CLOSE] < df[COL_MEDIAN]  # 当前K线的收盘价 < 中轨
        condition2 = df[COL_CLOSE].shift(1) >= df[COL_MEDIAN].shift(
            1)  # 之前K线的收盘价 >= 中轨
        df.loc[condition1 & condition2,
               COL_SIGNAL_LONG] = 0  # 将产生平仓信号当天的signal设置为0,0代表平仓

        # ===找出做多信号
        condition1 = df[COL_CLOSE] > df[COL_UPPER]  # 当前K线的收盘价 > 上轨
        condition2 = df[COL_CLOSE].shift(1) <= df[COL_UPPER].shift(
            1)  # 之前K线的收盘价 <= 上轨
        df.loc[condition1 & condition2,
               COL_SIGNAL_LONG] = 1  # 将产生做多信号的那根K线的signal设置为1,1代表做多

        # ===找出做空平仓信号
        condition1 = df[COL_CLOSE] > df[COL_MEDIAN]  # 当前K线的收盘价 > 中轨
        condition2 = df[COL_CLOSE].shift(1) <= df[COL_MEDIAN].shift(
            1)  # 之前K线的收盘价 <= 中轨
        df.loc[condition1 & condition2,
               COL_SIGNAL_SHORT] = 0  # 将产生平仓信号当天的signal设置为0,0代表平仓

        # ===找出做空信号
        condition1 = df[COL_CLOSE] < df[COL_LOWER]  # 当前K线的收盘价 < 下轨
        condition2 = df[COL_CLOSE].shift(1) >= df[COL_LOWER].shift(
            1)  # 之前K线的收盘价 >= 下轨
        df.loc[condition1 & condition2,
               COL_SIGNAL_SHORT] = -1  # 将产生做空信号的那根K线的signal设置为-1,-1代表做空

        # ===合并做多做空信号,去除重复信号
        df['signal'] = df[['signal_long', 'signal_short'
                           ]].sum(axis=1, min_count=1,
                                  skipna=True)  # 若你的pandas版本是最新的,请使用本行代码代替上面一行
        temp = df[df['signal'].notnull()][['signal']]
        # # === 去除重复信号
        temp = temp[temp['signal'] != temp['signal'].shift(1)]
        df['signal'] = temp['signal']

        if drop_extra_columns:
            df.drop([
                COL_MEDIAN, COL_STD, COL_UPPER, COL_LOWER, COL_SIGNAL_LONG,
                COL_SIGNAL_SHORT
            ],
                    axis=1,
                    inplace=True)

        return df
def market_open(context):
    
    # 以下是主循环
    for ins in g.instruments:
        # 过滤空主力合约品种
        if g.MappingReal[ins] != '':
            IndexFuture = g.MappingIndex[ins]
            RealFuture = g.MappingReal[ins]
            # 获取当月合约交割日期
            end_date = get_CCFX_end_date(RealFuture)
            # 当月合约交割日当天不开仓
            if (context.current_dt.date() == end_date):
                return
            else:
                g.LastRealPrice[RealFuture] = attribute_history(RealFuture,1,'1d',['close'])['close'][-1]
                # 获取价格list
                g.PriceArray[IndexFuture] = attribute_history(IndexFuture,50,'1d',['close','open','high','low'])
                g.CurrentPrice = g.PriceArray[IndexFuture]['close'][-1]
                g.ClosePrice = g.PriceArray[IndexFuture]['close']
                # 如果没有数据,返回
                if len(g.PriceArray[IndexFuture]) < 50:
                    return
                else:
                    close = np.array(g.PriceArray[IndexFuture]['close'])
                    high = np.array(g.PriceArray[IndexFuture]['high'])
                    low = np.array(g.PriceArray[IndexFuture]['low'])
                    # 计算AMA,仅传入一个参数g.Window
                    g.AMA[IndexFuture] = talib.KAMA(close,g.Window)
                    # 计算ATR
                    g.ATR[IndexFuture] = talib.ATR(high,low,close, g.Window)[-1]
                    if not isnan(g.AMA[IndexFuture][-1]) :
                        g.Filter[IndexFuture] = talib.STDDEV(g.AMA[IndexFuture][-g.Window:],g.Window)[-1]
                
                        #判断AMA两日差值,是否大于标准差过滤器
                        if g.AMA[IndexFuture][-1]-g.AMA[IndexFuture][-2] > g.Filter[IndexFuture]*g.FilterTimes:
                            g.Cross = 1
                        elif g.AMA[IndexFuture][-2]-g.AMA[IndexFuture][-1] > g.Filter[IndexFuture]*g.FilterTimes:
                            g.Cross = -1
                        else:
                            g.Cross = 0
        
                        #判断交易信号:均线交叉+可二次入场条件成立
                        if  g.Cross == 1 and g.Reentry_long == False:
                            g.Signal = 1
                        elif g.Cross == -1 and g.Reentry_short == False:
                            g.Signal = -1
                        else:
                            g.Signal = 0
    
                    # 执行交易
                    Trade(context,RealFuture,IndexFuture)
                    # 运行防止充入模块
                    Re_entry(context,RealFuture)
                    # 计数器+1
                    if RealFuture in g.Times.keys():
                        g.Times[RealFuture] += 1 
                    else:
                        g.Times[RealFuture] = 0
Esempio n. 7
0
def std_zdf_tp2(df0, n, m, l):
    df = df0.copy()
    df['tp'] = 0
    df['bd'] = df['close'] - df['open']
    df['std'] = talib.STDDEV(df['bd'], n) * m
    df['std_mean'] = talib.MA(df['std'], n)
    df.loc[df['bd'] > (df['std_mean'] + df['std']), 'tp'] = 1
    df['tp'] = df['tp'].rolling(l).sum()
    return df["tp"]
Esempio n. 8
0
 def STD(
         close: List[float],
         time_period: int = 7,
 ):
     return talib.STDDEV(
         np.array([float(c) for c in close]),
         timeperiod=time_period,
         nbdev=1,
     )
def standard_deviation(df, n):
	"""
	Add standard deviation indicator as a column in dataframe df
	:param df: dataframe with historical prices
	:param n: standard deviation period
	:return: dataframe with standard deviation of n period added as a column
	"""
	df['STD_' + str(n)] = ta.STDDEV(df['Close'], timeperiod=n)
	return df
Esempio n. 10
0
    def k_ma(self, d, p, close, period, m):
        df = close[close.index < d][-period - 1:]
        df = df.append(pd.Series([p], index=[d]))
        if m == 0:
            res = ta.MA(df, timeperiod=period)
        else:
            res = ta.STDDEV(df, timeperiod=period, nbdev=1)

        return res.values[-1]
Esempio n. 11
0
def boll(close, n, dev, array=False):
    """布林通道"""
    mid = talib.SMA(close, n)
    std = talib.STDDEV(close, n)

    up = mid + std * dev
    down = mid - std * dev

    return up, down
Esempio n. 12
0
    def onMarketDataUpdate(self, market, code, md):

        stock_info = self.stock_info[code]

        # The following time is not allowed to trade. Only trade from 9:30 am to 12:00 am, and from 13:00 to 16:00
        time_info = md.timestamp.split('_')
        if int(time_info[1][:4]) not in (range(930, 1201) + range(1300, 1601)) or \
                (stock_info[MA] and md.lastPrice < 1 < stock_info[MA]):
            return

        # For open price record last day close price
        if time_info[0] != stock_info[LAST_DATE]:
            stock_info[LAST_DATE] = time_info[0]

            if len(stock_info[CLOSE_PRICE]) > max(
                    self.rsi_period, self.ma_period, self.ppo_slow_period) + 1:
                stock_info[CLOSE_PRICE].pop(0)

            if stock_info[LAST_PRICE]:
                stock_info[CLOSE_PRICE].append(stock_info[LAST_PRICE])

            if len(stock_info[CLOSE_PRICE]) < max(
                    self.rsi_period, self.ma_period, self.ppo_slow_period):
                stock_info[LAST_PRICE] = md.lastPrice
                self.stock_info[code].update(stock_info)
                return

            stock_info[MA] = talib.MA(numpy.array(stock_info[CLOSE_PRICE]),
                                      self.ma_period)[-1]
            stock_info[STD] = talib.STDDEV(
                numpy.array(stock_info[CLOSE_PRICE]), self.ma_period)[-1]
            stock_info[PPO] = talib.PPO(numpy.array(stock_info[CLOSE_PRICE]),
                                        fastperiod=self.ppo_fast_period,
                                        slowperiod=self.ppo_slow_period)[-1]

            if stock_info[
                    HOLD_VOLUME] and stock_info[PPO] < self.ppo_sell_threshold:
                self.short_security(md.timestamp, code, md.bidPrice1)

        stock_info[RSI] = talib.RSI(numpy.array(stock_info[CLOSE_PRICE] +
                                                [md.lastPrice]),
                                    timeperiod=self.rsi_period)[-1]
        if stock_info[RSI] < self.rsi_buy_bound:
            std_factor = 2
        else:
            std_factor = 1.2

        if md.askPrice1 + std_factor * stock_info[STD] < stock_info[MA] and \
                        stock_info[PPO] > self.ppo_buy_threshold:
            self.long_security(md.timestamp, code, md.askPrice1)

        elif stock_info[HOLD_VOLUME] and md.bidPrice1 >= stock_info[MA]:
            self.short_security(md.timestamp, code, md.bidPrice1)

        stock_info[LAST_PRICE] = md.lastPrice
        self.stock_info[code].update(stock_info)
Esempio n. 13
0
 def std(self, n, array=False):
     """
     Standard deviation
     标准差 n是窗口
     array  False 返回最后一个数据, True 返回数组
     """
     result = talib.STDDEV(self.close, n)
     if array:
         return result
     return result[-1]
def get_boll(close_list):
    """
    BOLL:MA(CLOSE,20);
    UB:BOLL+2*STD(CLOSE,20);
    LB:BOLL-2*STD(CLOSE,20);
    1.股价上升穿越布林线上限时,回档机率大;
    2.股价下跌穿越布林线下限时,反弹机率大;
    3.布林线震动波带变窄时,表示变盘在即;
    4.BOLL可配合BB、WIDTH使用;
    """
    close_ndarray = np.array(close_list)
    n = 20
    P = 20
    MID = talib.MA(close_ndarray, n)
    UPPER = MID + P / 10 * talib.STDDEV(close_ndarray, n)
    LOWER = MID - P / 10 * talib.STDDEV(close_ndarray, n)
    up = UPPER  # 上轨
    down = LOWER  # 下轨
    return up, down
Esempio n. 15
0
def std_zdf_tp(df0, n, m, l):

    df = df0.copy()
    df['tp'] = 0
    df['bd'] = df['close'] - df['open']
    df['std'] = talib.STDDEV(df['bd'], n) * m
    df.loc[df['bd'] > df['std'], 'tp'] = 1
    df['tp'] = talib.SUM(df['tp'], l)

    return df['tp']
Esempio n. 16
0
 def fliterVol(self, am, paraDict):
     volPeriod = paraDict['volPeriod']
     lowVolThreshold = paraDict['lowVolThreshold']
     std = ta.STDDEV(am.close, volPeriod)
     atr = ta.ATR(am.high, am.low, am.close, volPeriod)
     rangeHL = (ta.MAX(am.high, volPeriod) - ta.MIN(am.low, volPeriod)) / 2
     minVol = min(std[-1], atr[-1], rangeHL[-1])
     lowFilterRange = am.close[-1] * lowVolThreshold
     filterCanTrade = 1 if (minVol >= lowFilterRange) else 0
     return filterCanTrade
Esempio n. 17
0
    def boll_low(self, n: int, dev: float, array: bool = False):
        mid = talib.SMA(self.low, n)
        std = talib.STDDEV(self.low, n)

        up = mid + std * dev
        down = mid - std * dev

        if array:
            return up, down
        return up[-1], down[-1]
Esempio n. 18
0
    def _draw_bar_picture(self, ix: int, bar: BarData) -> QtGui.QPicture:
        """"""
        # Create objects
        if ix <= self.last_ix:
            return self.last_picture

        pre_bar = self._manager.get_bar(ix - 1)

        if not pre_bar:
            return self.last_picture

        inc_picture = QtGui.QPicture()
        self._arrayManager.update_bar(pre_bar)
        painter = QtGui.QPainter(inc_picture)

        inc = self._arrayManager.close - self._arrayManager.open
        std = talib.STDDEV(inc, self.INC_PARAMS[0])
        multiple = inc / std

        # diff, dea, macd = self._arrayManager.macd(*self.MACD_PARAMS, array=True)
        self.br_max = max(self.br_max, std[-1], inc[-1])
        self.br_min = min(self.br_min, -std[-1], inc[-1])
        self.incs['up'][ix - 1] = std[-1]
        self.incs['inc'][ix - 1] = inc[-1]
        self.incs['down'][ix - 1] = -std[-1]
        self.incs['multiple'][ix - 1] = multiple[-1]
        if not (np.isnan(std[-2] * std[-1] * inc[-2] * inc[-1])):
            multiple_bar = QtCore.QRectF(ix - 1 - BAR_WIDTH, 0, BAR_WIDTH * 2,
                                         inc[-1])
            painter.setPen(pg.mkPen(color=(255, 255, 255),
                                    width=PEN_WIDTH / 2))
            if multiple[-1] >= 0:
                ud = 'up'
            else:
                ud = 'down'
            if abs(multiple[-1]) >= self.INC_PARAMS[1]:
                cp = 'gte'
            else:
                cp = 'lt'
            painter.setBrush(self.INC_COLORS['inc'][f'{ud}_{cp}'])
            painter.drawRect(multiple_bar)

            up_sp = QtCore.QPointF(ix - 2, std[-2])
            up_ep = QtCore.QPointF(ix - 1, std[-1])
            drawPath(painter, up_sp, up_ep, self.INC_COLORS['up'])

            down_sp = QtCore.QPointF(ix - 2, -std[-2])
            down_ep = QtCore.QPointF(ix - 1, -std[-1])
            drawPath(painter, down_sp, down_ep, self.INC_COLORS['down'])

        # Finish
        painter.end()
        self.last_ix = ix
        self.last_picture = inc_picture
        return inc_picture
Esempio n. 19
0
    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        # 计算wd_atr
        atr = am.atr(self.boll_window, array=True)
        ma = am.sma(self.boll_window, array=True)
        wd_atr = atr / ma

        # 计算MTM值
        high_shift = shift(am.high, 1)
        low_shift = shift(am.low, 1)
        close_shift = shift(am.close, 1)

        # 补全
        high_shift[0] = high_shift[1]
        low_shift[0] = low_shift[1]
        close_shift[0] = close_shift[1]

        # 计算mtm
        mtm_high = am.high / high_shift - 1
        mtm_low = am.low / low_shift - 1
        mtm_close = am.close / close_shift - 1

        mtm_atr = ta.ATR(mtm_high, mtm_low, mtm_close, self.boll_window)

        # 计算MTM均值
        mtm_high_mean = ta.SMA(mtm_high, self.boll_window)
        mtm_low_mean = ta.SMA(mtm_low, self.boll_window)
        mtm_close_mean = ta.SMA(mtm_close, self.boll_window)
        mtm_mean_atr = ta.ATR(
            mtm_high_mean, mtm_low_mean, mtm_close_mean, self.boll_window
        )

        # 平滑因子
        indicator = mtm_close_mean
        indicator = indicator * wd_atr * mtm_atr * mtm_mean_atr

        print(indicator)

        # 自适应布林带
        median = ta.SMA(indicator, self.boll_window)

        std = ta.STDDEV(indicator, self.boll_window)
        z_score = abs(indicator - median) / std
        m = z_score[-self.boll_window-1:-2].max()
        up = median + std * m
        dn = median - std * m

        print(f"上轨:{up}")
Esempio n. 20
0
def stdev(vm, args, kwargs):
    source, length = _expand_args(args, kwargs, (
        ('source', Series, True),
        ('length', int, True),
    ))
    try:
        return series_np(ta.STDDEV(source, length), source)
    except Exception as e:
        if str(e) == 'inputs are all NaN':
            return source.dup()
        raise
Esempio n. 21
0
def add_technical_indicators(dataframe):

    # Overlap Studies Functions
    dataframe["SMA"] = talib.SMA(dataframe["Close"])
    dataframe["BBANDS_up"], dataframe["BBANDS_md"], dataframe[
        "BBANDS_dw"] = talib.BBANDS(dataframe["Close"],
                                    timeperiod=5,
                                    nbdevup=2,
                                    nbdevdn=2,
                                    matype=0)
    dataframe["EMA"] = talib.EMA(dataframe["Close"], timeperiod=30)
    dataframe["HT_TRENDLINE"] = talib.HT_TRENDLINE(dataframe["Close"])
    dataframe["WMA"] = talib.WMA(dataframe["Close"], timeperiod=30)

    # Momentum Indicator Functions
    dataframe["ADX"] = talib.ADX(dataframe["High"],
                                 dataframe["Low"],
                                 dataframe["Close"],
                                 timeperiod=14)
    dataframe["MACD"], _, _ = talib.MACD(dataframe["Close"],
                                         fastperiod=12,
                                         slowperiod=26,
                                         signalperiod=9)
    dataframe["MOM"] = talib.MOM(dataframe["Close"], timeperiod=5)
    dataframe["RSI"] = talib.RSI(dataframe["Close"], timeperiod=14)

    # Volume Indicator Functions
    # dataframe["OBV"] = talib.OBV(dataframe["Close"], dataframe["Volume"])

    # Volatility Indicator Functions
    dataframe["ATR"] = talib.ATR(dataframe["High"],
                                 dataframe["Low"],
                                 dataframe["Close"],
                                 timeperiod=14)
    dataframe["TRANGE"] = talib.TRANGE(dataframe["High"], dataframe["Low"],
                                       dataframe["Close"])

    # Price Transform Functions
    dataframe["AVGPRICE"] = talib.AVGPRICE(dataframe["Open"],
                                           dataframe["High"], dataframe["Low"],
                                           dataframe["Close"])
    dataframe["MEDPRICE"] = talib.MEDPRICE(dataframe["High"], dataframe["Low"])
    dataframe["WCLPRICE"] = talib.WCLPRICE(dataframe["High"], dataframe["Low"],
                                           dataframe["Close"])

    # Statistic Functions
    dataframe["LINEARREG_SLOPE"] = talib.LINEARREG_SLOPE(dataframe["Close"],
                                                         timeperiod=14)
    dataframe["STDDEV"] = talib.STDDEV(dataframe["Close"],
                                       timeperiod=5,
                                       nbdev=1)

    dataframe = dataframe.dropna()
    return dataframe
Esempio n. 22
0
def get_standard_deviation(closes, timeperiod, nbdev=0):
    """
    :param closes: pd.DataFrame
    :param timeperiod: int
    :param nbdev: int,
    :return: pd.DataFrame
    """
    std = pd.DataFrame(columns=closes.columns, index=closes.index)
    for symbol in closes.columns:
        std[symbol] = talib.STDDEV(closes[symbol], timeperiod, nbdev)
    return std
Esempio n. 23
0
 def fliterVol(self, am, paraDict):
     nDay = paraDict['nDay']
     nFilter = paraDict['nFilter']
     minPct = paraDict['minPct']
     returns = am.close[-1]/am.close[0] - 1
     
     if am.volume<ta.SMA(am.volume, nDay)-nFilter*ta.STDDEV(am.volume, nDay) or returns<minPct:
         filterCanTrade = -1
     else:
         filterCanTrade = 1
     return filterCanTrade
Esempio n. 24
0
def STDDEV(close, timeperiod=5, nbdev=1):
    ''' Standard Deviation 标准偏差

    分组: Statistic Functions 统计函数

    简介: 种量度数据分布的分散程度之标准,用以衡量数据值偏离算术平均值的程度。
    标准偏差越小,这些值偏离平均值就越少,反之亦然。
    标准偏差的大小可通过标准偏差与平均值的倍率关系来衡量。

    real = STDDEV(close, timeperiod=5, nbdev=1)
    '''
    return talib.STDDEV(close, timeperiod, nbdev)
Esempio n. 25
0
def Momentum(data, length=10):
    '''
    Momentum - The price difference in n days, standardized by the volatility
    (close_0 - close_n)/stdev(close, n)
    :param df:
    :param length:
    :return:
    '''
    delta = ta.MOM(data, length)
    stdev = ta.STDDEV(data, length)

    return delta / stdev
Esempio n. 26
0
 def STDDEV(self, length):
     """标准偏差"""
     records = self.platform.get_kline(self.time_frame)
     records.reverse()
     kline_length = len(records)
     close_array = np.zeros(kline_length)
     t = 0
     for item in records:
         close_array[t] = item[4]
         t += 1
     result = (talib.STDDEV(close_array, timeperiod=length, nbdev=1))
     return result
Esempio n. 27
0
    def paramCalc(self, dfs, cur):
        # 分钟线
        if dfs is None or len(dfs) == 0: return None

        c0, c1 = cur[self.mCodes[0]], cur[self.mCodes[1]]
        for key in ["asks", "bids", "ask_vols", "bid_vols"]:
            if (c0[key][0] * c1[key][0] == 0): return None

        # 周期和标准差倍数
        period, scale = self.procMap.period, self.procMap.scale
        size =  period + 10

        # 去掉当前的即时k线
        df0, df1 = dfs[self.mCodes[0]][-size:-1], dfs[self.mCodes[1]][-size:-1]

        # 计算相关参数
        close = (df0["close"] / df1["close"])
        # nan 处理
        close = close.fillna(close[close.notnull()].mean())

        # 添加最新
        close = close.append(pd.Series(c0["last"] / c1["last"]))

        ma = ta.MA(close, timeperiod=period)
        sd = ta.STDDEV(close, timeperiod=period, nbdev=1)
        top, lower = ma + scale * sd, ma - scale * sd
        #
        width = (top - lower) / ma * 100
        #

        widthDelta = ta.MA(width - width.shift(1), timeperiod=3)
        # 即时K线取2点中值

        wd2 = widthDelta - widthDelta.shift(1)
        wd2m = widthDelta * widthDelta.shift(1)

        return {
            "ma": ma.values[-1],
            "top": top.values[-1],
            "lower": lower.values[-1],
            "width": width.values[-1],
            "std": sd.values[-1],
            "close": c0["last"] / c1["last"],
            "widthdelta": widthDelta.values[-1],  # 布林带变化
            "wd2": wd2.values[-1],  # 布林带二阶变化率
            "wd2m": wd2m.values[-1],

            "p_l": c0["asks"][0] / c1["bids"][0],  # 买入铜,卖出铅价格
            "p_h": c0["bids"][0] / c1["asks"][0],  # 买入铅,卖出铜价格
            "delta": (c0["asks"][0] / c1["bids"][0] - c0["bids"][0] / c1["asks"][0]) / sd.values[-1],
            "interval":0,
        }
    def onFiveBar(self, bar):
        #Log( self.currency , bar.close , self.pos , self.orderList)

        for orderID in self.orderList:
            self.cancelOrder(orderID)
        self.orderList = []

        # 保存K线数据
        self.closeArray[0:self.bufferSize -
                        1] = self.closeArray[1:self.bufferSize]
        self.highArray[0:self.bufferSize -
                       1] = self.highArray[1:self.bufferSize]
        self.lowArray[0:self.bufferSize - 1] = self.lowArray[1:self.bufferSize]
        self.buyValue[0:self.bufferSize - 1] = self.buyValue[1:self.bufferSize]

        self.closeArray[-1] = bar.close
        self.highArray[-1] = bar.high
        self.lowArray[-1] = bar.low

        # 计算指标数值
        self.bollMid = talib.MA(self.closeArray, self.bollLength)[-1]
        self.bollStd = talib.STDDEV(self.closeArray, self.bollLength)[-1]
        self.entryUp = self.bollMid + self.bollStd * self.topDev

        self.buyValue[-1] = self.entryUp

        self.bufferCount += 1
        if self.bufferCount < self.bufferSize:
            return

        # 判断是否要进行交易
        cond1 = 0
        for i in range(1, self.use_range + 1):
            if self.highArray[-i] > self.buyValue[-i]:
                cond1 = 1
        cond2 = 0

        # newHigh = [float(x) for x in self.highArray]
        # if bar.high >= max(newHigh[-self.N : ]) and self.highArray[-2] >= max(newHigh[-self.N-1 : -1]):
        #     cond2 = 1
        if self.pos == 0 and cond1 > 0:
            self.intraTradeHigh = bar.high
            newHigh = [float(x) for x in self.highArray]
            entryBuyPrice = max(newHigh[-self.N:])
            orderID = self.buy(entryBuyPrice, self.fixedSize, stop=True)
            self.orderList.append(orderID)

        elif self.pos > 0:
            self.intraTradeHigh = max(bar.high, self.intraTradeHigh)
            exitPrice = self.intraTradeHigh * (1 - self.trailingPrcnt / 100.0)
            orderID = self.sell(exitPrice, self.fixedSize, stop=True)
            self.orderList.append(orderID)
Esempio n. 29
0
    def pctTrailing(self, am, paraDict):
        pctPeriod = paraDict['pctPeriod']
        hourCount = paraDict['hourCount']
        clipPct = paraDict['clipPct']

        closeReturn = (am.close[1:]-am.close[:-1])/am.close[:-1]
        cond1 = np.percentile(closeReturn[1:], clipPct)
        cond2 = np.percentile(closeReturn[1:], 100-clipPct)

        standCloseReturn = np.clip(closeReturn, cond1, cond2)
        pctStd = ta.STDDEV(standCloseReturn, pctPeriod)
        trailingPct = 2*pctStd[-1]*(hourCount**0.5)
        return trailingPct
Esempio n. 30
0
 def test_stddev(self):
     """样本标准偏差
     https://www.cnblogs.com/citycomputing/p/10447657.html
     """
     alist = [3606.86, 3580.15, 3411.49]
     arr = np.array(alist)
     print(arr)
     n = len(arr)
     a = (n / (n - 1))**0.5  # [n/(n-1)]的平方根
     astd = talib.STDDEV(arr, len(arr))
     print(f"talib.STDDEV:{astd}")
     print(f"这个是正确 talib.STDDEV * {a}:{astd*a}")
     astd2 = talib.STDDEV(arr * (n / (n - 1)), n)
     print(f"talib.STDDEV:{astd2}")
     astd3 = talib.STDDEV(arr, n) * (n / (n - 1))
     print(f"talib.STDDEV:{astd3}")
     astd31 = talib.STDDEV(arr, n, nbdev=1)
     print(f"talib.STDDEV nbdev=1:{astd31}")
     astd4 = np.std(arr)
     print(f"np.std也不是样本方差:{astd4}")
     astd5 = np.std(arr, ddof=1)
     print(f"np.std 参数ddof=1是样本方差:{astd5}")