Example #1
0
def check_trades(context, data):
    """
    Called every minute.
    """

    longs = context.longs
    #print('NUMBER OF LONGS',len(longs))
    shorts = context.shorts
    longs.temp = zip(pd.Series())
    shorts.temp = zip(pd.Series())
    highs = lows = 0
    highs = data.history(longs, 'high', 20, '1d')
    lows = data.history(longs, 'low', 20, '1d')
    #Shighs , Llows = data.history(context.shorts,('high','low'),20,'1d')
    #print ('longs',len(longs))
    for sec in longs:
        high = highs[sec]
        low = lows[sec]
        sar = talib.SAR(high, low)[-1]
        if (context.output.Close[sec] > sar):
            #new_longs += 1
            longs.temp.append(sec)

    highs = data.history(shorts, 'high', 20, '1d')
    lows = data.history(shorts, 'low', 20, '1d')

    for sec in shorts:
        high = highs[sec]
        low = lows[sec]
        sar = talib.SAR(high, low)[-1]
        if (context.output.Close[sec] < sar):
            shorts.temp.append(sec)

    return longs.temp, shorts.temp
Example #2
0
    def add_stock_index(self, df0, index_list=None):

        close = df0["close"]

        df0['max90'] = mx = ta.MAX(close, timeperiod=self.timePeriods)
        df0['min90'] = min = ta.MIN(close, timeperiod=self.timePeriods)
        df0['miw'] = ta.MININDEX(close, timeperiod=self.timePeriods)
        df0['mid'] = df0.apply(lambda row: self.mid(row, close), axis=1)

        # 穿越
        sar = ta.SAR(df0['high'],
                     df0['low'],
                     acceleration=self.sarStart,
                     maximum=0.2)
        df0['sard'] = sard = close - sar
        df0['sarm'] = sard * sard.shift(1)
        df0['sarm'] = df0.apply(
            lambda row: self.turn(row['sarm'], row['sard'], 1), axis=1)

        sar5 = ta.SAR(df0['high'],
                      df0['low'],
                      acceleration=self.sarEnd,
                      maximum=0.2)
        df0['sard5'] = sard5 = close - sar5
        df0['sarm5'] = sard5 * sard5.shift(1)
        df0['sarm5'] = df0.apply(
            lambda row: self.turn(row['sarm5'], row['sard5'], 1), axis=1)

        return df0
Example #3
0
 def init(self):
     # Calculate the indicators we want to use later (they will be stored in an array)
     self.sma1 = self.I(SMA, self.data.Close, self.n1)
     self.sma2 = self.I(SMA, self.data.Close, self.n2)
     self.sar = talib.SAR(self.data.High, self.data.Low, acceleration=0.02, maximum=0.2)
     self.rsi = talib.RSI(self.data.Close)
     self.index = 0
Example #4
0
 def sar(self, array=False):
     """
     """
     result = talib.SAR(self.high, self.low)
     if array:
         return result
     return result[-1]
Example #5
0
 def prep_sar(self):
     sar = pd.DataFrame(index=self.df.index, columns=['sar'])
     sar['sar'] = talib.SAR(self.arr_ask[:, 1],
                            self.arr_ask[:, 2],
                            acceleration=0.05,
                            maximum=0.2)
     return sar
Example #6
0
def sar(
    client,
    symbol,
    timeframe="6m",
    highcol="high",
    lowcol="low",
    acceleration=0,
    maximum=0,
):
    """This will return a dataframe of parabolic sar
     for the given symbol across the given timeframe

    Args:
        client (pyEX.Client); Client
        symbol (string); Ticker
        timeframe (string); timeframe to use, for pyEX.chart
        highcol (string); high column to use
        lowcol (string); low column to use
        acceleration (int); acceleration
        maximum (int); maximum

    Returns:
        DataFrame: result
    """
    df = client.chartDF(symbol, timeframe)
    sar = t.SAR(
        df[highcol].values,
        df[lowcol].values,
        acceleration=acceleration,
        maximum=maximum,
    )
    return pd.DataFrame(
        {highcol: df[highcol].values, lowcol: df[lowcol].values, "sar": sar}
    )
Example #7
0
 def riskControl_sar(self,
                     open_price,
                     time,
                     SLtype,
                     AF_increse=0.01,
                     AF_max=0.1):
     """
     riskControl_sar(self, open_price, time, type, AF_increse=0.01, AF_max=0.1)
     
     type 0 : short
          1 : long
          
     return: float
     """
     sar = ta.SAR(self.high[:time + 1],
                  self.low[:time + 1],
                  acceleration=AF_increse,
                  maximum=AF_max)
     if SLtype == 1:
         if sar[-1] >= 0:
             return False
         elif sar[-1] < 0:
             return True
     if SLtype == 0:
         if sar[-1] <= 0:
             return False
         elif sar[-1] > 0:
             return True
     return False
Example #8
0
File: tech.py Project: le0l1/ML4T
def get_features(data):
    tech_data = pd.DataFrame(index=data.index);

    for t in periods_list:
        tech_data[f'SMA_{t}'] = talib.SMA(data.close,timeperiod=t)
        tech_data[f'MOM_{t}'] = talib.MOM(data.close, timeperiod=t)
        tech_data[f'RSI_{t}'] = talib.RSI(data.close, timeperiod=t)
        tech_data[f'MA_{t}'] = talib.MA(data.close, timeperiod=t)
        tech_data[f'DX_{t}'] = talib.DX(data.high, data.low, data.close, timeperiod=t)
        tech_data[f'volume_change_{t}'] = data.volume.pct_change(periods=t)
        tech_data[f'volatility_{t}'] = data.close.pct_change(periods=t).std()
        tech_data[f'ADX_{t}'] = talib.ADX(data.high, data.low, data.close, timeperiod=t)
        tech_data[f'ADXR_{t}'] = talib.ADXR(data.high, data.low, data.close, timeperiod=t)
        tech_data[f'AROONOSC_{t}'] = talib.AROONOSC(data.high, data.low, timeperiod=t)
        tech_data[f'ROC_{t}'] = talib.ROC(data.close, timeperiod=t)
        tech_data[f'BIAS_{t}'] = (data['close'] - data['close'].rolling(t, min_periods=1).mean())/ data['close'].rolling(t, min_periods=1).mean()*100
        tech_data[f'BOLL_upper_{t}'], tech_data[f'BOLL_middle_{t}'], tech_data[f'BOLL_lower_{t}'] = talib.BBANDS(
                data.close,
                timeperiod=t,
                nbdevup=2,
                nbdevdn=2,
                matype=0)

    tech_data['SAR'] = talib.SAR(data.high, data.low)
    tech_data['AD'] = talib.AD(data.high, data.low, data.close, data.volume)
    tech_data['OBV'] = talib.OBV(data.close, data.volume)
    tech_data['target'] = data.close.pct_change().shift(-1).apply(lambda x: 1 if x > 0 else -1).fillna(0)
    tech_data['time'] = data.time
    tech_data = tech_data.set_index('time')

    reduce(lambda x, y: cross_over(x, y, tech_data), periods_list)
    
    features = list(set(tech_data.columns) - set(data.columns) - set(['target'])) 
    return tech_data.dropna(), features
Example #9
0
def parabolic_sar(high, low, acceleration=0,
                  maximum=0):  #Acceleration and max 0 by default
    try:
        ps_data = talib.SAR(high, low, acceleration, maximum)
        return ps_data
    except Exception as e:
        raise (e)
Example #10
0
def devfea(df, high, low, close, open, volume):
    df['AD'] = talib.AD(high, low, close, volume)
    df['CCI'] = talib.CCI(high, low, close)
    df['macd'], df['macdsignal'], df['macdhist'] = talib.MACD(close,
                                                              fastperiod=12,
                                                              slowperiod=26,
                                                              signalperiod=9)
    df['ATR'] = talib.ATR(high, low, close, timeperiod=14)
    df['ADOSC'] = talib.ADOSC(high, low, close, volume)
    df['ADX'] = talib.ADX(high, low, close)
    df['BBANDS_upper'], df['BBANDS_mid'], df['BBANDS_lower'] = talib.BBANDS(
        close)
    df['RSI'] = talib.RSI(close)
    df['MA5'] = talib.MA(close, 5)
    df['MA10'] = talib.MA(close, 10)
    df['MA20'] = talib.MA(close, 20)
    df['OBV'] = talib.OBV(close, volume)
    df['SAR'] = talib.SAR(high, low)
    df['lgvol'] = np.log(volume)
    #上影线
    df['upshadow'] = np.abs(high - ((open + close) +
                                    (np.abs(open - close))) / 2)
    #下影线
    df['downshadow'] = np.abs(low - ((open + close) -
                                     (np.abs(open - close))) / 2)
    return df
Example #11
0
    def add_SAR(self, df, acceleration=0, maximum=0):

        df['SAR_'] = ta.SAR(df['high'],
                            df['low'],
                            acceleration=acceleration,
                            maximum=maximum)
        return df
Example #12
0
def SAR(df):
    '''
    增加一列sar

    '''
    df['sar'] = ta.SAR(np.array(df['high']), np.array(df['close']))
    return df
Example #13
0
    def get_signals(self):
        # First Classifier Signals
        rsi_100 = talib.RSI(np.array(self.close), timeperiod=99)[-1]
        sma_101 = talib.SMA(np.array(self.close), timeperiod=10)[-1]
        sma_102 = talib.SMA(np.array(self.close), timeperiod=10)[-2]
        sma_401 = talib.SMA(np.array(self.close), timeperiod=40)[-1]
        sma_402 = talib.SMA(np.array(self.close), timeperiod=40)[-2]

        # Second Classifier Signals
        open_bid = self.open[-1]
        close_bid = self.close[-1]
        volume = self.volume[-1]
        # The volatility of the market within 5-minutes
        spread = self.high[-1] - self.low[-1]

        # Third Classifier Signals
        macd = talib.MACD(np.array(self.close))[-1][-1]

        sar = talib.SAR(np.array(self.high), np.array(self.low))[-1]

        return {
            "rsi(100)": rsi_100,
            "sma(10,40)": self.crossing_graphs(sma_102, sma_101, sma_402,
                                               sma_401),
            "openBid": open_bid,
            "closeBid": close_bid,
            "volume": volume,
            "spread": spread,
            "macd_signal": macd,
            "sar": sar
        }
Example #14
0
def technical_index(context):
    #EMA,RSI指标
    context.var.ts['EMA_5min'] = talib.EMA(np.array(context.var.ts.close),
                                           timeperiod=5)
    context.var.ts['EMA_10min'] = talib.EMA(np.array(context.var.ts.close),
                                            timeperiod=10)
    context.var.ts['EMA_15min'] = talib.EMA(np.array(context.var.ts.close),
                                            timeperiod=15)
    context.var.ts['EMA_20min'] = talib.EMA(np.array(context.var.ts.close),
                                            timeperiod=20)
    context.var.ts['RSI'] = talib.RSI(np.array(context.var.ts.close))
    #STOCHRSI_usual = talib.STOCHRSI(np.array(context.var.ts.close))

    # BOLL-BAND指标
    BBANDS_usual = talib.BBANDS(np.array(context.var.ts.close))
    upperband, middleband, lowerband = BBANDS_usual
    context.var.ts['upperband'] = upperband
    context.var.ts['middleband'] = middleband
    context.var.ts['lowerband'] = lowerband

    arrClose = np.array(context.var.ts.close)
    arrHigh = np.array(context.var.ts.high)
    arrLow = np.array(context.var.ts.low)
    arrVolume = np.array(context.var.ts.volume, dtype=np.float)
    # MACD指标
    MACD_usual = talib.MACD(arrClose)
    macd, macdsignal, macdhist = MACD_usual
    context.var.ts['macd'] = macd
    context.var.ts['macdsignal'] = macdsignal
    context.var.ts['macdhist'] = macdhist

    # KDJ指标
    KDJ_usual = talib.STOCH(arrHigh, arrLow, arrClose)
    slowk, slowd = KDJ_usual
    context.var.ts['slowk'] = slowk
    context.var.ts['slowd'] = slowd

    # ATR指标
    ATR_usual = talib.ATR(arrHigh, arrLow, arrClose)
    context.var.ts['ATR'] = ATR_usual

    # WILLR指标
    WILLR_usual = talib.WILLR(arrHigh, arrLow, arrClose)
    context.var.ts['WILLR'] = WILLR_usual

    # BOV指标
    OBV_usual = talib.OBV(arrClose, arrVolume)
    context.var.ts['OBV'] = OBV_usual

    # SAR指标
    SAR_usual = talib.SAR(arrHigh, arrLow)
    context.var.ts['SAR'] = SAR_usual

    # DEMA指标
    DEMA_usual = talib.DEMA(arrClose)
    context.var.ts['DEMA'] = DEMA_usual

    #MOM指标
    MOM_usual = talib.MOM(arrClose)
    context.var.ts['MOM'] = MOM_usual
Example #15
0
File: item.py Project: asciili/vnpy
 def update_values(self):
     """
     Update value
     """
     self.values = talib.SAR(self.am.high[-self.am.count:],
                             self.am.low[-self.am.count:],
                             self.acceleration, self.maximum)
Example #16
0
def calculate(data):
    timestamp = data[len(data)-1][0]
    nopen = [] 
    nhigh = []
    nlow = [] 
    nclose = []
    nvolume = []
    for entry in data:
        nopen.append(entry[1])
        nhigh.append(entry[2])
        nlow.append(entry[3])
        nclose.append(entry[4])
        nvolume.append(entry[5])
    nc = np.array(nclose)
    hc = np.array(nhigh)
    lc = np.array(nlow)
    cc = np.array(nclose)
    vc = np.array(nvolume)

    rsi = talib.RSI(nc, timeperiod=14)
    macdsignal = talib.MACD(nc, fastperiod=12, slowperiod=26, signalperiod=9)
    sar = talib.SAR(hc, lc, acceleration=0, maximum=0)
    adosc = talib.ADOSC(hc, lc, cc, vc, fastperiod=3, slowperiod=10)
    aroon = talib.AROONOSC(hc, lc, timeperiod=14)
    ult = talib.ULTOSC(hc, lc, cc, timeperiod1=7, timeperiod2=14, timeperiod3=28)
    obj, sent = twitter_api.get_sentiment()

    database.insert_predictions(timestamp, rsi[-1], macdsignal[0][-1], sar[-1], adosc[-1], aroon[-1], ult[-1], sent, obj)
    return timestamp, rsi[-1], macdsignal[0][-1], sar[-1], adosc[-1], aroon[-1], ult[-1], sent, obj
    def check_sar_status_change(self):
        """
        检查sar指标的波动情况
        :return:
        0: sar状态没有变化
        1:向上突破
        -1:向下突破
        """
        # 下载实时数据
        self.down_minute_data(count=20, freq='1m')

        # 计算sar指数
        self.data['sar'] = talib.SAR(self.data.high,
                                     self.data.low,
                                     acceleration=0.05,
                                     maximum=0.2)

        # 获取sar最新状态
        row_tail = self.data.tail(1)
        sar_status_now = row_tail['sar'].values[0] > row_tail['close'].values[0]

        if pd.isnull(self.sar_last):
            self.sar_last = sar_status_now
            return 0

        if sar_status_now != self.sar_last:
            if sar_status_now:
                return 1
            else:
                return -1
        else:
            return 0
Example #18
0
def genTA(data, y, t): #t is timeperiod
    indicators  = {}
    y_ind = copy.deepcopy(y)
   
    for ticker in data:
    ## Overlap
        indicators[ticker] = ta.SMA(data[ticker].iloc[:,3], timeperiod=t).to_frame()        
        indicators[ticker]['EMA'] = ta.EMA(data[ticker].iloc[:,3], timeperiod=t)       
        indicators[ticker]['BBAND_Upper'], indicators[ticker]['BBAND_Middle' ], indicators[ticker]['BBAND_Lower' ] = ta.BBANDS(data[ticker].iloc[:,3], timeperiod=t, nbdevup=2, nbdevdn=2, matype=0)         
        indicators[ticker]['HT_TRENDLINE'] = ta.HT_TRENDLINE(data[ticker].iloc[:,3])
        indicators[ticker]['SAR'] = ta.SAR(data[ticker].iloc[:,1], data[ticker].iloc[:,2], acceleration=0, maximum=0)
        #rename SMA column
        indicators[ticker].rename(columns={indicators[ticker].columns[0]: "SMA"}, inplace=True)
    ## Momentum
        indicators[ticker]['RSI'] = ta.RSI(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['MOM'] = ta.MOM(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['ROC'] = ta.ROC(data[ticker].iloc[:,3], timeperiod=(t-1))
        indicators[ticker]['ROCP']= ta.ROCP(data[ticker].iloc[:,3],timeperiod=(t-1))
        indicators[ticker]['STOCH_SLOWK'], indicators[ticker]['STOCH_SLOWD'] = ta.STOCH(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], fastk_period=t, slowk_period=int(.6*t), slowk_matype=0, slowd_period=int(.6*t), slowd_matype=0)
        indicators[ticker]['MACD'], indicators[ticker]['MACDSIGNAL'], indicators[ticker]['MACDHIST'] = ta.MACD(data[ticker].iloc[:,3], fastperiod=t,slowperiod=2*t,signalperiod=int(.7*t))
        
    ## Volume
        indicators[ticker]['OBV'] = ta.OBV(data[ticker].iloc[:,3], data[ticker].iloc[:,4])
        indicators[ticker]['AD'] = ta.AD(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], data[ticker].iloc[:,4])
        indicators[ticker]['ADOSC'] = ta.ADOSC(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3], data[ticker].iloc[:,4], fastperiod=int(.3*t), slowperiod=t)
        
    ## Cycle
        indicators[ticker]['HT_DCPERIOD'] = ta.HT_DCPERIOD(data[ticker].iloc[:,3])
        indicators[ticker]['HT_TRENDMODE']= ta.HT_TRENDMODE(data[ticker].iloc[:,3])
    
    ## Price
        indicators[ticker]['AVGPRICE'] = ta.AVGPRICE(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['TYPPRICE'] = ta.TYPPRICE(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
    
    ## Volatility
        indicators[ticker]['ATR'] = ta.ATR(data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3],  timeperiod=(t-1))
    
    ## Statistics
        indicators[ticker]['BETA'] = ta.BETA(data[ticker].iloc[:,1], data[ticker].iloc[:,2], timeperiod=(t-1))
        indicators[ticker]['LINEARREG'] = ta.LINEARREG(data[ticker].iloc[:,3], timeperiod=t)
        indicators[ticker]['VAR'] = ta.VAR(data[ticker].iloc[:,3], timeperiod=t, nbdev=1)
    
    ## Math Transform
        indicators[ticker]['EXP'] = ta.EXP(data[ticker].iloc[:,3])
        indicators[ticker]['LN'] = ta.LN(data[ticker].iloc[:,3])
    
    ## Patterns (returns integers - but norming might not really do anything but wondering if they should be normed)
        indicators[ticker]['CDLENGULFING'] = ta.CDLENGULFING(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLDOJI']      = ta.CDLDOJI(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLHAMMER']    = ta.CDLHAMMER(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        indicators[ticker]['CDLHANGINGMAN']= ta.CDLHANGINGMAN(data[ticker].iloc[:,0], data[ticker].iloc[:,1], data[ticker].iloc[:,2], data[ticker].iloc[:,3])
        
    #drop 'nan' values
        indicators[ticker].drop(indicators[ticker].index[np.arange(0,63)], inplace=True)
        y_ind[ticker].drop(y_ind[ticker].index[np.arange(0,63)], inplace=True)
        
    #Normalize Features
    indicators_norm = normData(indicators)
        
    return indicators_norm, indicators, y_ind
Example #19
0
def get_parSAR_advice(chart_data, client_acceleration = 0.02, client_maximum = 0.2):                # Обычно принято брать acceleration = 0.02, maximum = 0.2
    parabolicsar = talib.SAR(numpy.asarray([chart_data[item]['high'] for item in sorted(chart_data)]), \
                                           numpy.asarray([chart_data[item]['low'] for item in sorted(chart_data)]), \
                                                         acceleration=client_acceleration, maximum=client_maximum)

    close = numpy.asarray([chart_data[item]['close'] for item in sorted(chart_data)])
    open = numpy.asarray([chart_data[item]['open'] for item in sorted(chart_data)])

    if parabolicsar[-2] >= max(open[-2], close[-2]):
        print(str(parabolicsar[-2]) + " " + str(open[-2]) + " " + str(close[-2]))
        trand = 'BEAR'
    elif parabolicsar[-2] <= min(open[-2], close[-2]):
        print(str(parabolicsar[-2]) + " " + str(open[-2]) + " " + str(close[-2]))
        trand = 'BULL'

    trandchange = False
    growing = False
    for offset, elem in enumerate(parabolicsar):
        trandchange = False
        growing = False
        if (parabolicsar[offset-1] >= max(open[offset-1], close[offset-1]) and \
            parabolicsar[offset-2] < min(open[offset-2],close[offset-2])) or\
                (parabolicsar[offset-1] <= min(open[offset-1], close[offset-1]) and \
            parabolicsar[offset-2] > max(open[offset-2], close[offset-2]))    :
            trandchange = True                                                                                 # Принимает True, когда парСАР поменял положение относительно цен
        if parabolicsar[offset-1] < min(open[offset-1], close[offset-1]):
            growing = True                                                                                     # Тренд вверх, пока парСАР находится ниже цен
    #print(str(trandchange) + str(trand) + str(growing) + str(offset) + str(open[offset-1]))
    parSARjump = numpy.diff(parabolicsar) * 100000                                                             # Наибольшие и наименьшие скачки соответствуют моментам, когда парСАР поменяло положение относительно цен
    return ({'trand': trand, 'growing': growing, 'trandchange': trandchange, 'parSAR': parabolicsar, 'parSARjump': parSARjump})
Example #20
0
def cal_plot_psar(ticker, step=0.02, max_step=0.2):
    print("Calculating Parabolic SAR...")
    stock_data = stock.stock_preprocess_arr_list(ticker)
    psar = talib.SAR(stock_data[3],
                     stock_data[4],
                     acceleration=step,
                     maximum=max_step)

    ##### plotting
    fig, ax = plt.subplots(1, 1, figsize=(15, 15))
    name = stock.check_all_ticker(ticker)[0]
    plt.suptitle('Parabolic Stop and Reverse of {}({})'.format(name, ticker),
                 fontsize=20,
                 fontweight='bold')

    ax.plot(stock_data[0],
            stock_data[2],
            label='Price - ' + name,
            color='black')
    ax.plot(stock_data[0], psar, '.', label='Parabloic SAR', color='#708EB2')

    ax.grid(True)
    ax.legend()
    ax.minorticks_on()
    ax.tick_params(axis='x', which='minor', bottom='off')

    fig.tight_layout()
    fig.subplots_adjust(top=0.95)
    #plt.show()
    stock.save_plot('PSAR', ticker)
def compute_technical_indicators(df):
    df['EMA5'] = ta.EMA(df['Adj Close'].values, timeperiod=5)
    df['EMA10'] = ta.EMA(df['Adj Close'].values, timeperiod=10)
    df['EMA15'] = ta.EMA(df['Adj Close'].values, timeperiod=15)
    df['EMA20'] = ta.EMA(df['Adj Close'].values, timeperiod=10)
    df['EMA30'] = ta.EMA(df['Adj Close'].values, timeperiod=30)
    df['EMA40'] = ta.EMA(df['Adj Close'].values, timeperiod=40)
    df['EMA50'] = ta.EMA(df['Adj Close'].values, timeperiod=50)

    df['EMA60'] = ta.EMA(df['Adj Close'].values, timeperiod=60)
    df['EMA70'] = ta.EMA(df['Adj Close'].values, timeperiod=70)
    df['EMA80'] = ta.EMA(df['Adj Close'].values, timeperiod=80)
    df['EMA90'] = ta.EMA(df['Adj Close'].values, timeperiod=90)

    df['EMA100'] = ta.EMA(df['Adj Close'].values, timeperiod=100)
    df['EMA150'] = ta.EMA(df['Adj Close'].values, timeperiod=150)
    df['EMA200'] = ta.EMA(df['Adj Close'].values, timeperiod=200)

    df['upperBB'], df['middleBB'], df['lowerBB'] = ta.BBANDS(
        df['Adj Close'].values, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)

    df['SAR'] = ta.SAR(df['High'].values,
                       df['Low'].values,
                       acceleration=0.02,
                       maximum=0.2)

    # we will normalize RSI
    df['RSI'] = ta.RSI(df['Adj Close'].values, timeperiod=14)

    df['normRSI'] = ta.RSI(df['Adj Close'].values, timeperiod=14) / 100.0

    df.tail()

    return df
Example #22
0
def Judge_Sell_Buy(order_book_id):
    bar_count = 15
    frequency = '1d'
    high = []
    low = []
    close = []
    his_inf = history_bars(order_book_id,
                           bar_count,
                           frequency,
                           fields=None,
                           skip_suspended=True,
                           include_now=False)
    for i in range(len(his_inf)):
        high.append(his_inf[i][2])
        low.append(his_inf[i][3])
        close.append(his_inf[i][4])
    high = np.array(high)
    low = np.array(low)
    close = np.array(close)
    SAR_index = ta.SAR(high, low, acceleration=0, maximum=0)
    if SAR_index[-1] > close[-1]:
        signal = 1
    elif SAR_index[-1] < close[-1]:
        signal = -1
    elif SAR_index == close[-1]:
        if SAR_index[-1] > close[-1]:
            signal = -1
        elif SAR_index[-1] < close[-1]:
            signal = 1
    return signal
def sar(High, Low, Close, initial=0.02, maximum=0.2):
    tmp_sar = ta.SAR(High, Low, acceleration=initial, maximum=maximum)
    sar = pd.Series(index=High.index, data=[0] * len(High))
    sar.loc[Close > tmp_sar] = 1
    sar.loc[Close < tmp_sar] = -1

    return sar
Example #24
0
 def add_sar(self, kind):
     """
     向df中增加sar指标
     :param kind:
     :return:
     """
     kind = self.k_kind_format(kind)
     self.data(kind)['SAR'] = talib.SAR(self.data(kind).high, self.data(kind).low, acceleration=0.05, maximum=0.2)
    def sar(self, sym, frequency, *args, **kwargs):
        if not self.kbars_ready(sym, frequency):
            return []

        highs = self.high(sym, frequency)
        lows = self.low(sym, frequency)

        return ta.SAR(highs, lows, *args, **kwargs)
Example #26
0
 def evaluate(self, kite_fetcher, instrument):
     df = self.get_small_data(kite_fetcher=kite_fetcher,
                              instrument=instrument)
     result = talib.SAR(high=df['high'],
                        low=df['low'],
                        acceleration=float(self.acceleration),
                        maximum=float(self.maximum))
     return np.round(result.iloc[-1], 2)
Example #27
0
    def paramCalc(self, tick):
        code = self.procMap.codes[0]
        c0 = tick[code]  # 快照
        c0['close'] = c0['last']
        df0 = copy.deepcopy(self.shareDict[code])
        # 部分修正即时K线
        df0.loc[public.getDatetime()] = pd.Series(
            [c0[key] for key in self.klinecolumns], index=self.klinecolumns)

        close = df0["close"]

        df0['max90'] = mx = ta.MAX(close, timeperiod=60)
        df0['drop'] = (mx - close) / mx

        sar = ta.SAR(df0['high'],
                     df0['low'],
                     acceleration=self.sarStart,
                     maximum=0.2)
        df0['sard'] = sard = close - sar
        df0['sarm'] = sard * sard.shift(1)
        df0['sarm'] = df0.apply(
            lambda row: self.turn(row['sarm'], row['sard'], 1), axis=1)

        sar5 = ta.SAR(df0['high'],
                      df0['low'],
                      acceleration=self.sarEnd,
                      maximum=0.2)
        df0['sard5'] = sard5 = close - sar5
        df0['sarm5'] = sard5 * sard5.shift(1)
        df0['sarm5'] = df0.apply(
            lambda row: self.turn(row['sarm5'], row['sard5'], 1), axis=1)

        df0['createTime'] = df0.index
        df0['mode'] = df0.apply(lambda row: self.point(row), axis=1)

        param = copy.deepcopy(df0.iloc[-1]).to_dict()
        param.update(c0)
        #if param['sarm']==1:  print(df0)
        #print(param)
        param.update({
            "code": code,
            "p_l": c0["asks"][0],
            "p_h": c0["bids"][0]
        })
        return param
 def upCross(self, ltp, data, offset=0):
     sar = talib.SAR(data['High'],
                     data['Low'],
                     acceleration=0.02,
                     maximum=0.2)
     if float(sar[-1:]) > float(data.Close[-1:]):
         if float(sar[-1:]) + float(offset) < ltp:
             return True
     return False
Example #29
0
def getPSAR(ticker):
    df = getCandleStick(ticker, '3m')
    sar = talib.SAR(df['high'], df['low'], acceleration=0.02, maximum=0.2)
    nowSAR = sar.iloc[-1]
    curPirce = getCurrPrice(ticker)
    if float(curPirce) < float(nowSAR):  #현재 가격이 SAR보다 아래에 있으면 매도
        return -1
    else:
        return 0
 def downClose(self, ltp, data):
     sar = talib.SAR(data['High'],
                     data['Low'],
                     acceleration=0.02,
                     maximum=0.2)
     if float(sar[-2:]) < float(data.Close[-2:]):
         if float(sar[-1:]) > float(data.Close[-1:]):
             return True
     return False