示例#1
0
文件: ohlc.py 项目: minghui/lquant
    def configure(self, config_name):
        """
        Add all feature we need configured by the configure file.
        :param config_name:
        :return:
        """

        # TODO: Test this method.

        def read_config(config_file):
            with codecs.open(config_file, encoding='utf-8') as f:
                config = yaml.load(f)
            return config

        config = read_config(config_name)
        for key in config:
            try:
                method = talib.get_functions(key)
                tmp_result = method(self._inputs)
                tmp_result = np.vstack(tmp_result).T
                assert tmp_result.shape[0] == self.data.shape[0]
                self.data = np.hstack((self.data, tmp_result))
            except Exception as e:
                raise ValueError(e, 'Wrong in configure')
        self.data_frame = pd.DataFrame(self.data, index=self.data_frame.date)
示例#2
0
def get_indicator(data=None, indicator_name):
    """ Compute indicators
    
    Parameters:
    -------
    data: dataframe (optional)
        OHLCVA data
    
    indicator_name: string
        name of indicator, shold be get from list_indicators
    

    Return:
    -------
    if data is none, return the corresponding function object
    otherwise return computed dataframe containing indicators
    
    Notes:
    ------
    if data is None, return function object, so that you can apply 
    it and feed with parameters to gain more control; in the latter case, 
    indicator is applied with default parameters
    """
    if indicator_name.upper() not in talib.get_functions():
        print "ERROR: indicator " + indicator_name + " not in list"
        return
    else:
        if data is not None:
            data.columns = [s.lower() for s in data.columns]
            func = talib.abstract.Function(indicator_name)
            ret = func(data, price='open')
            data.columns = [s.title() for s in data.columns]
            return ret
        else:
            return talib.abstract.Function(indicator_name)
示例#3
0
文件: backta.py 项目: fanbin/backbin
def list_indicator(group=None):
    """ list all available indicators
    
    Parameters:
    -------
    group: string (optional)
        group of indicator; if none, function will list all indicators
    """
    if group is None:
        return talib.get_functions()
    else:
        if group in ["Overlap", "overlap", "over"]:
            return talib.get_function_groups()["Overlap Studies"]
        elif group is ["Momentum", "momentum", "momen", "mom"]:
            return talib.get_function_groups()["Momentum Indicators"]
        elif group is ["Volume", "volume", "volu", "vol"]:
            return talib.get_function_groups()["Volume Indicators"]
        elif group is ["Volatility", "volatility", "vola"]:
            return talib.get_function_groups()["Volatility Indicators"]
        elif group is ["Price", "price", "pri"]:
            return talib.get_function_groups()["Price Transform"]            
        elif group is ["Cycle", "cycle", "cyc"]:
            return talib.get_function_groups()["Cycle Indicators"]
        elif group is ["Pattern", "pattern", "patt", "pat"]:
            return talib.get_function_groups()["Pattern Recognition"]
        else:
            print "ERROR: no matching group "+group+", must be in: "
            print list_indicator_groups()
            print "Or enter no group to get full list of indicators:"
            print "  list_indicator()"
            return  
示例#4
0
 def indicator_help(indicator: str = None):
     if indicator not in ta.get_functions():
         raise ValueError(
             f'{indicator} is not supported\n'
             'https://github.com/mrjbq7/ta-lib#supported-indicators-and-functions'
         )
     help(getattr(ta.func, indicator))
示例#5
0
def all_talib(ohlcv, ta_list=talib.get_functions()):
    # # 確認價量資料表 df 的值都是 float 格式
    ohlcv = ohlcv[[
        'symbol', 'open', 'high', 'low', 'close', 'adj close', 'volume'
    ]].astype('float')
    for x in ta_list:
        try:
            # x 為技術指標的代碼,透過迴圈填入,再透過 eval 計算出 output
            output = eval('abstract.' + x + '(ohlcv)')
            # 如果輸出是一維資料,幫這個指標取名為 x 本身;多維資料則不需命名
            output.name = x.lower() if type(output) == pd.Series else None
            # 原始寫法已過期
            # output.name = x.lower() if type(output) == pd.core.series.Series else None
            # 透過 merge 把輸出結果併入 df DataFrame
            ohlcv = pd.merge(ohlcv,
                             pd.DataFrame(output),
                             left_on=ohlcv.index,
                             right_on=output.index)
            ohlcv.set_index('key_0', inplace=True)
        except:
            print(x + ':Error')
    ohlcv.reset_index(inplace=True)
    ohlcv = ohlcv.rename(columns={'key_0': 'date'})
    ohlcv.set_index('date', inplace=True)
    return ohlcv.iloc[:, 7:]
示例#6
0
    def returnData(self):
        functions = talib.get_functions()
        count = 0
        p = re.compile('CDL.')

        for fun in functions:
            taName = fun
            CDL_Matched = p.match(taName)
            if CDL_Matched: continue
            if taName == 'MAVP': continue

            sliced = self.sliceDic()
            ta = abstract.Function(taName)
            ta.set_input_arrays(sliced)

            if taName == 'MAMA': orgData = ta()
            else: orgData = ta(6)
            if isinstance(orgData, np.ndarray):
                self.taReturnOne(taName)

            elif len(orgData) == 2:
                self.taReturnTwo(taName)

            elif len(orgData) == 3:
                self.taReturnThree(taName)

        print('Usable TA numbers:', self.usable_ta_numbers)
        return self.dataDic, self.taNameList
示例#7
0
文件: talib.py 项目: ueqt/ulib
def get_functions():
    '''
    Returns a list of all the functions supported by TALIB

    返回所有TALIB支持的函数列表
    '''
    return talib.get_functions()
示例#8
0
    def __new__(cls, name, bases, attrs):
        instance = type.__new__(cls, name, bases, attrs)

        for func in talib.get_functions():
            setattr(instance, func, instance.retrieve)  #getattr(talib, func))

        return instance
def input_indicator():
    
    """
    
    Function that allows for a user to input as many technical indicators as
    they would like to plot for the selected stocks
    
    """
    
    indicators = []
    while True:
        user_input = input('Technical Indicator (type "Done" if finished and "Help" for list of indicators): ')
        # The prompt ends when the user is done entering all their desired
        # indicators
        if user_input == 'Done':
            break
        # A list of all possible commands (indicators) pops up when the user
        # asks for "Help"
        elif user_input == 'Help':
            print(talib.get_functions())
            continue
        else:
            if user_input in dir(talib):
                indicators.append(user_input)
            else:
                continue
    return indicators
def build_ta_features(df, freq='1D', ta_list='all'):
    '''
    To build OHLCV (Open High Low Close Volume) features, and advanced features provided by TA-Lib.
    Input:
        df <pd.DataFrame>: A DataFrame object that contains columns ['timestamp', 'prices', 'market_caps', 'total_volumes']. It should be retreived from CoinGecko.
        freq <str>: A string that specifies the frequency of sampling. For different frequency notations, check https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases.
                    If set to None, it will not perform resampling.
        ta_list <list>: A list of techical analysis features to be built. For the whole list of feature names, check TA-Lib website: https://mrjbq7.github.io/ta-lib/funcs.html.
                        If ta_list is set to 'all', it will build all features available in TA-Lib. Otherwise, it will only build features as specified in the feature_list. If ta_list is set to None, it will not build any extra features in TA-Lib. It could be useful when you only want to resample it but not building any extra technical analysis features.
    Return:
        df <pd.DataFrame>: A DataFrame object where each column represents a unique feature (with name), and each row represents a sampled timestamp (with time).
    '''
    df = df.copy()
    if freq is not None:
        # First fill missing close price of the resampled df with previous close price
        df = pd.concat([
            df.resample(freq)['open'].agg('first'),
            df.resample(freq)['high'].agg('max'),
            df.resample(freq)['low'].agg('min'),
            df.resample(freq)['close'].agg('last').ffill(),
            df.resample(freq)['volume'].agg('sum').fillna(0.0)
        ],
                       axis=1)
        # Then fill missing open high low price of the resampled df with the previous close price (copied to the same row)
        df = pd.concat([
            df['open'].fillna(df['close']), df['high'].fillna(df['close']),
            df['low'].fillna(df['close']), df['close'], df['volume']
        ],
                       axis=1)
    else:
        # First fill missing close price of the resampled df with previous close price
        df['close'] = df['close'].ffill()
        df['volume'] = df['volume'].fillna(0.0)

        # Then fill missing open high low price of the resampled df with the previous close price (copied to the same row)
        df = pd.concat([
            df['open'].fillna(df['close']), df['high'].fillna(df['close']),
            df['low'].fillna(df['close']), df['close'], df['volume']
        ],
                       axis=1)

    # Building advanced features using TA-Lib
    # For MAVP, it allows moving average with variable periods specified, we'll just skip this function.
    if ta_list is not None:
        if ta_list == 'all':
            ta_list = talib.get_functions()
        for i, x in enumerate(ta_list):
            try:
                output = eval('abstract.' + x + '(df)')
                output.name = x.lower() if type(
                    output) == pd.core.series.Series else None
                df = pd.merge(df,
                              pd.DataFrame(output),
                              left_on=df.index,
                              right_on=output.index)
                df = df.set_index('key_0')
            except:
                pass
        df.index.names = ['datetime']
    return df
示例#11
0
文件: backta.py 项目: fanbin/backbin
def get_indicator(data = None, indicator_name):
    """ Compute indicators
    
    Parameters:
    -------
    data: dataframe (optional)
        OHLCVA data
    
    indicator_name: string
        name of indicator, shold be get from list_indicators
    

    Return:
    -------
    if data is none, return the corresponding function object
    otherwise return computed dataframe containing indicators
    
    Notes:
    ------
    if data is None, return function object, so that you can apply 
    it and feed with parameters to gain more control; in the latter case, 
    indicator is applied with default parameters
    """
    if indicator_name.upper() not in talib.get_functions():
        print "ERROR: indicator "+indicator_name+" not in list"
        return
    else:
        if data is not None:
            data.columns = [s.lower() for s in data.columns]
            func = talib.abstract.Function(indicator_name)
            ret = func(data, price='open')
            data.columns = [s.title() for s in data.columns]
            return ret
        else:
            return talib.abstract.Function(indicator_name)
示例#12
0
def list_indicator(group=None):
    """ list all available indicators
    
    Parameters:
    -------
    group: string (optional)
        group of indicator; if none, function will list all indicators
    """
    if group is None:
        return talib.get_functions()
    else:
        if group in ["Overlap", "overlap", "over"]:
            return talib.get_function_groups()["Overlap Studies"]
        elif group is ["Momentum", "momentum", "momen", "mom"]:
            return talib.get_function_groups()["Momentum Indicators"]
        elif group is ["Volume", "volume", "volu", "vol"]:
            return talib.get_function_groups()["Volume Indicators"]
        elif group is ["Volatility", "volatility", "vola"]:
            return talib.get_function_groups()["Volatility Indicators"]
        elif group is ["Price", "price", "pri"]:
            return talib.get_function_groups()["Price Transform"]
        elif group is ["Cycle", "cycle", "cyc"]:
            return talib.get_function_groups()["Cycle Indicators"]
        elif group is ["Pattern", "pattern", "patt", "pat"]:
            return talib.get_function_groups()["Pattern Recognition"]
        else:
            print "ERROR: no matching group " + group + ", must be in: "
            print list_indicator_groups()
            print "Or enter no group to get full list of indicators:"
            print "  list_indicator()"
            return
def get_ti_api():
    dic = dict(signal_line=dict(fun_name='signal_line',
                                params=dict(value=0),
                                settings=dict(shift=0),
                                outputs=dict(real=['line', 'solid'])))

    for field_name in fields:
        dic[field_name] = dict(fun_name=field_name.lower(),
                               settings=dict(shift=0),
                               outputs=dict(real=['line', 'solid']))
    dic['Volume']['outputs']['real'][0] = 'column'
    for fun_name in talib.get_functions():
        if fun_name not in Bad_indicators:
            name = fun_name + '(' + talib.abstract.Function(
                fun_name).info['display_name'] + ')'
            dic[name] = dict(fun_name=fun_name, settings=dict(shift=0))
            dic[name]['params'] = get_parameter(fun_name)
            output_dic = dict()
            for li in list(
                    talib.abstract.Function(fun_name).output_flags.items()):
                output_dic[li[0]] = ['line', 'solid']
                if li[1][0] == 'Histogram':
                    output_dic[li[0]][0] = 'column'
                elif li[1][0] == 'Dashed Line':
                    output_dic[li[0]][1] = 'Dash'
                elif li[1][0] == 'star':
                    output_dic[li[0]][1] = 'Dot'
            dic[name]['outputs'] = output_dic
    return dic
def _is_indicator_talib(name):
    try:
        import talib
    except ImportError:
        logging.getLogger(__name__).debug(
            'talib failed to import or does not exist, continuing')
        return False
    return name.upper() in talib.get_functions()
示例#15
0
def talib_get_functions_df():
    lst_info = []
    for f in talib.get_functions():
        absf = talib.abstract.Function(f)
        lst_info.append(absf.info)
    df_absf = pd.DataFrame(lst_info)
    df_absf = df_absf.set_index('name')
    return (df_absf)
示例#16
0
def get_candle_funcs():
    funcs = {}
    for name in talib.get_functions():
        if name.startswith('CDL'):
            funcs[name] = getattr(talib, name)
    return funcs


# sample_data = [
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['2/03/14', 44, 45, 43, 44.09],

#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['1/22/14', 10, 18,  17, 20],
#     ['2/03/14', 44, 45, 43, 44.09], # today
# ]

# indentifyCandles(sample_data)

# def indentifyCandles(historical_data):
#         # convert data to columns
#         numpyData = numpy.column_stack(historical_data)

#         # extract the columns we need, making sure to make them 64-bit floats
#         # print(numpyData)
#         o = numpyData[1].astype(float)
#         h = numpyData[2].astype(float)
#         l = numpyData[3].astype(float)
#         c = numpyData[4].astype(float)

#         function_list = get_candle_funcs()

#         results = {}
#         for f in function_list:
#             res = function_list[f](o, h, l, c)
#             if res[-1] > 0:
#                 results[f] = res

#         # print('')
#         # print('results:',results)
示例#17
0
 def __register_talib_functions():
     """Registers all ta-lib functions in the TaLibService class"""
     if TaLibService.TALIB_FUNCTIONS_REGISTERED:
         return
     TaLibService.exposed_get_function_groups = talib.get_function_groups
     TaLibService.exposed_get_functions = talib.get_functions
     for func in talib.get_functions():
         setattr(TaLibService, "exposed_" + func, getattr(talib, func))
     TaLibService.TALIB_FUNCTIONS_REGISTERED = True
示例#18
0
    def set_factors_labels(self, price=None, ta_list=None, lags=None):
        """
        根据价格数据及选定的指标计算特征
        :return: the factors array DataFrame
        """
        ta_fun_names = ta.get_functions()
        df_price = price if price else self.price_data
        ta_list = ta_list if ta_list else self.dic_factors
        lags = lags if lags else self.ta_lags
        ta_factors = df_price.copy()
        ii = 1
        for j in ta_list:
            if j[0] in ta_fun_names:
                ta_fun = Function(j[0])
                if j[1] == {}:
                    ta_fun = ta_fun
                else:
                    dic_param = dict(ta_fun.parameters)
                    for key1 in dic_param:
                        dic_param[key1] = j[1][key1]
                    ta_fun.parameters = dic_param
                ta_value = ta_fun(df_price)
                if ta_value.size > len(ta_value):
                    ta_factors["%s_%d" % (j[0], ii)] = ta_value.ix[:, 0]
                else:
                    ta_factors["%s_%d" % (j[0], ii)] = ta_value
            ii += 1

        ta_factors['ACC'] = TSSB_TA(df_price).ACC()
        ta_factors['ADOSC'] = TSSB_TA(df_price).ADOSC()

        # 计算lags指标

        if lags > 0:
            ret = pd.DataFrame(index=ta_factors.index)
            columns = ta_factors.columns
            for col in columns:
                for lag in xrange(0, lags):
                    ret[col + "_%s" % str(lag+1)] = ta_factors[col].shift(lag)
        else:
            ret = ta_factors

        # 定义标签: 上涨为1, 下跌为-1
        if self.predict_type == 1:
            labels = df_price['close'].pct_change().shift(-1)  # 预测明收盘与今收盘的涨跌
        else:
            labels = (df_price['close'] - df_price['open']).shift(-1)  # 预测明收盘与明开盘的涨跌

        labels[labels >= 0] = 1
        labels[labels < 0] = 0

        ret = ret.dropna()
        labels = labels[ret.index]
        self.ta_factors, self.labels = ret, labels
        return ret, labels
示例#19
0
 def onFunctionTreeItemDoubleClicked(self, item, column):
     text = item.text(column)
     function_name = ""
     name = "%s()"
     if text in talib.get_functions():
         function_name = text
     if text in functions.functions_name["自定义函数"].keys():
         function_name = text
     if function_name:
         self.code_string.append(name % function_name)
     return
示例#20
0
def testFunctionName():
    funcNames = talib.get_functions();

    fname = funcNames[0];
    print(talib.abstract.Function(sys.argv[1]).input_names);
    print(talib.abstract.Function(sys.argv[1]));
    print(talib.abstract.Function(sys.argv[1]).input_arrays);
    f = talib.abstract.Function(sys.argv[1]);
    print(f.parameters);
    print(f.output_names);
    print(f.input_names.items());
    pass;
示例#21
0
def testFunctionName():
    funcNames = talib.get_functions()

    fname = funcNames[0]
    print(talib.abstract.Function(sys.argv[1]).input_names)
    print(talib.abstract.Function(sys.argv[1]))
    print(talib.abstract.Function(sys.argv[1]).input_arrays)
    f = talib.abstract.Function(sys.argv[1])
    print(f.parameters)
    print(f.output_names)
    print(f.input_names.items())
    pass
示例#22
0
    def onFunctionTreeItemClicked(self, item, column):

        text = item.text(column)
        name = ""
        self.demo.clear()
        if text in talib.get_functions():
            indicator = talib.abstract.Function(text.lower())
            info = indicator.info
            name = info.get("display_name", "")
        if text in functions.functions_name["自定义函数"].keys():
            name = functions.functions_name["自定义函数"][text]["demo_code"]
        self.demo.setText(name)
        return
示例#23
0
def BuildInd(df):
    ListOfFunc = talib.get_functions()
    ListOfFunc = [a for a in ListOfFunc if a not in ['MAVP', 'OBV']]

    my_special_args = {
        'low': df['LOW'],
        'high': df['HIGH'],
        'open': df['OPEN'],
        'close': df['CLOSE'],
        'volume': df['VOLUME']
    }
    Nums = 0
    Inds = pd.DataFrame()
    for func in ListOfFunc:
        func_args = get_builtin_args(getattr(talib, func))
        if isinstance(func_args, list):
            if 'real0' not in func_args:
                try:
                    kwargs = {
                        k: v
                        for k, v in my_special_args.items() if k in func_args
                    }
                    tempfunc = getattr(talib, func)
                    res = tempfunc(**kwargs)
                    Nums += 1
                    if len(res) > 10:
                        Inds[func] = res
                    else:
                        #       if len(res)<10:
                        for i in range(len(res)):
                            Inds[func + str(i)] = res[i]
                            Nums += 1
                except:
                    tempfunc = getattr(talib, func)
                    res = tempfunc(my_special_args['close'])
                    Nums += 1
                    if len(res) > 10:
                        Inds[func] = res
    #       if len(res)<10:
                    else:
                        for i in range(len(res)):
                            Inds[func + str(i)] = res[i]
                            Nums += 1
    Inds = Inds.fillna(method='backfill')
    dell = []
    for i in range(Inds.shape[1]):
        if Inds.iloc[:, i].unique().shape[0] < 2:
            dell.append(list(Inds)[i])
    Inds = Inds.drop(columns=dell)

    return Inds
示例#24
0
 def _get_info(self, indicator_name: str) -> Dict:
     """ Get the relavent indicator parameters and inputs """
     if indicator_name is None:
         print("Usage: help_indicator(symbol), symbol is indicator name")
         return {"parameters": {}, "inputs": []}
     else:
         upper_code = indicator_name.upper()
         if upper_code not in talib.get_functions():
             print(f"ERROR: indicator {upper_code} not in list")
             return {"parameters": {}, "inputs": []}
         else:
             func = Function(upper_code)
             parameters = dict(func.parameters)
             inputs = list(func.input_names.values())
             return {"parameters": parameters, "inputs": inputs}
示例#25
0
def help_indicator(code):
    """ list all available indicators
    
    Parameters:
    -------
    code: code of symbol (required)
        get help information of a symbol
    """
    if code is None:
        print "Usage: help_indicator(symbol), symbol is indicator name"
    else:
        if code.upper() not in talib.get_functions():
            print "ERROR: indicator " + code + " not in list"
            return
        else:
            func = talib.abstract.Function(code)
            print func
示例#26
0
文件: backta.py 项目: fanbin/backbin
def help_indicator(code):
    """ list all available indicators
    
    Parameters:
    -------
    code: code of symbol (required)
        get help information of a symbol
    """
    if code is None:
        print "Usage: help_indicator(symbol), symbol is indicator name"
    else:
        if code.upper() not in talib.get_functions():
            print "ERROR: indicator "+code+" not in list"
            return
        else:
            func = talib.abstract.Function(code)
            print func
示例#27
0
def run():
    all_ta = ta.get_functions()

    field_names = [
        'TA_INDICATOR', 'start_date', 'end_date', 'backtest_minutes',
        'backtest_days', 'backtest_weeks', 'number_of_trades',
        'average_trades_per_week_avg', 'average_trade_amount_usd',
        'initial_capital', 'ending_capital', 'net_profit', 'net_profit_pct',
        'average_daily_profit', 'average_daily_profit_pct', 'average_exposure',
        'average_exposure_pct', 'net_risk_adjusted_return_pct',
        'max_drawdown_pct_catalyst', 'max_daily_drawdown_pct',
        'max_weekly_drawdown_pct', 'sharpe_ratio_avg',
        'std_rolling_10_day_pct_avg', 'std_rolling_100_day_pct_avg',
        'number_of_simulations'
    ]

    best_profit_pct = 0
    best_indicator = None

    if not os.path.exists(RESULT_FILE):
        os.makedirs(PERF_DIR, exist_ok=True)

    with open(RESULT_FILE, 'a') as f:
        writer = csv.DictWriter(f, fieldnames=field_names)
        writer.writeheader()
        for i in all_ta:
            strat = run_indicator(i)
            result_dict = strat.quant_results.to_dict()

            profit_pct = result_dict['net_profit_pct']['Backtest']
            if profit_pct > best_profit_pct:
                best_profit_pct, best_indicator = profit_pct, i

            row = {'TA_INDICATOR': i}
            for k, v in result_dict.items():
                row[k] = v['Backtest']

                # nested dict with trading type as key
            writer.writerow(row)

        # df_results.append(strat.quant_results)

    click.secho('Best peforming indicator: {}'.format(best_indicator),
                fg='cyan')
    click.secho('Net Profit Percent: {}'.format(best_profit_pct), fg='cyan')
示例#28
0
    def onTecFunctionSearched(self, function_ui):

        text = self.search_tec_function.text().strip().lower()
        self.tec_tree.clear()
        self.tec_tree = function_ui.findChild(QTreeWidget, "tec_tree")
        if text != "":
            talib_functions = talib.get_functions()
            for i in talib_functions:
                if text in i.lower():
                    node = QTreeWidgetItem(self.tec_tree)
                    node.setText(0, i)
        else:
            talib_groups = talib.get_function_groups()
            for key in talib_groups.keys():
                node = QTreeWidgetItem(self.tec_tree)
                node.setText(0, key)
                for value in talib_groups[key]:
                    sub_node = QTreeWidgetItem(node)
                    sub_node.setText(0, value)
示例#29
0
文件: ohlc.py 项目: squall1988/lquant
 def add_specified_feature(self, feature_name, column_name, parameters=None):
     """
     Use this method to extract all the feature we can get from talib.
     :param feature_name:
     :param column_name:
     :param parameters:
     :return:
     """
     # TODO: Test if this method work.
     extract_method = talib.get_functions(feature_name)
     if parameters is not None and isinstance(parameters, dict):
         feature = extract_method(self._inputs, parameters)
     else:
         feature = extract_method(self._inputs)
     feature = np.vstack(feature).T
     self.data = np.hstack((self.data, feature))
     self.columns = self.columns + column_name
     self.data_frame = pd.DataFrame(data=self.data,
                                    columns=self.columns,
                                    index=self.data_frame.date)
     return True
示例#30
0
 def __init__(self, *args, **kwargs):
     super(MainWindow,self).__init__(*args,**kwargs)
     self.setupUi(self)
     Indicator_Manager.load_indicators()
     InstanceHolder.add_instance(self, 'MainWindow')
     self.queueTimer = QtCore.QTimer()
     self.queueTimer.timeout.connect(self.on_timertick)
     self.queueTimer.start(100)
     self.workqueue = queue.Queue()
     self.plot_button.pressed.connect(self.plot_chart)
     self.interval_comboBox.addItems(['1m','5m','1h','12h','1d','1w','1M'])
     self.indicatoroverview_view.add_items(Indicator_Manager.get_indicator_names())
     self.saveindicator_button.pressed.connect(self.on_save_indicator)
     self.save_button.pressed.connect(self.save_data)
     self.path_input.setText(os.path.dirname(os.path.realpath(__file__)) + "/IndicatorTemplates/")
     self.indicators_combobox.addItems(talib.get_functions())
     self.currentStream = ''
     self.lastindicator = "Overview"
     self.add_queueitem('init_plotter')
     self.add_queueitem('plot_chart')
     API_Manager.set_newexchange("binance","","")
     self.show()
示例#31
0
def run_ta(candlesticks, indicators):
    '''
    Runs calculation for each indicator and sets the value
    in the Pair attributes
    this is called every time the websocket tics
    :param pair:
    '''
    stats = {}
    for key in candlesticks:
        for indicator in indicators:
            if indicator['name'] in ta.get_functions():
                # try:
                inds = get_indicators(candlesticks[key],
                                      indicator['name'],
                                      candle_period=indicator['candle_period'])
                # except Exception as ex:
                #     print(ex)
                #     continue
                for k, v in inds:
                    stats.update({k + '_' + key: v})

    return stats
示例#32
0
    def ALL(self):
        self.company_stock = self.company_stock.drop('code', axis=1)
        self.company_stock = self.company_stock.set_index('date')
        self.company_stock = self.company_stock.astype('float')
        df = self.company_stock

        ta_list = talib.get_functions()

        for x in ta_list:
            try:
                output = eval('abstract.' + x + '(df)')
                output.name = x.lower() if type(
                    output) == pd.core.series.Series else None
                df = pd.merge(df,
                              pd.DataFrame(output),
                              left_on=df.index,
                              right_on=output.index)
                df = df.set_index('key_0')
            except:
                print(x, ' error')

        return df
示例#33
0
 def __ta_look_back(self):
     """
     获取所需回溯历史数据的长度,计算技术指标时需要n天前的数据,同时预测涨跌时又要windows_size的历史指标
     :return:
     """
     ta_fun_names = ta.get_functions()
     lk_list = []
     for j in self.dic_factors:
         if j[0] in ta_fun_names:
             ta_fun = Function(j[0])
             if j[1] == {}:
                 continue
             else:
                 dic_param = dict(ta_fun.parameters)
                 for key1 in dic_param:
                     dic_param[key1] = j[1][key1]
                     ta_fun.parameters = dic_param
             lk = ta_fun.lookback
             lk_list.append(lk)
         else:
             pass
     ret = max(lk_list)
     return ret
示例#34
0
def main():
    df = pd.read_csv("ford_2012.csv", index_col='Date', parse_dates='Date')
    df['Volume'] = df['Volume'].astype(np.float64)
    df.columns = [s.lower() for s in df.columns]
    print(df)
    lst_errors = []
    for i, funcname in enumerate(talib.get_functions()):
        try:
            print("%03d %s" % (i, funcname))
            func = talib.abstract.Function(funcname)
            print(func.info)
            expected = func(df)
            if isinstance(expected, pd.Series):
                expected.name = "Value"
                expected = pd.DataFrame(expected)
            print(expected)
            print(type(expected))
            print("")
            expected.to_csv("expected/%s.csv" % funcname)
        except:
            print(traceback.format_exc())
            lst_errors.append(funcname)

    print("errors: %s" % lst_errors)
示例#35
0
文件: ohlc.py 项目: minghui/lquant
 def add_specified_feature(self,
                           feature_name,
                           column_name,
                           parameters=None):
     """
     Use this method to extract all the feature we can get from talib.
     :param feature_name:
     :param column_name:
     :param parameters:
     :return:
     """
     # TODO: Test if this method work.
     extract_method = talib.get_functions(feature_name)
     if parameters is not None and isinstance(parameters, dict):
         feature = extract_method(self._inputs, parameters)
     else:
         feature = extract_method(self._inputs)
     feature = np.vstack(feature).T
     self.data = np.hstack((self.data, feature))
     self.columns = self.columns + column_name
     self.data_frame = pd.DataFrame(data=self.data,
                                    columns=self.columns,
                                    index=self.data_frame.date)
     return True
示例#36
0
文件: ohlc.py 项目: squall1988/lquant
    def configure(self, config_name):
        """
        Add all feature we need configured by the configure file.
        :param config_name:
        :return:
        """
        # TODO: Test this method.

        def read_config(config_file):
            with codecs.open(config_file, encoding='utf-8') as f:
                config = yaml.load(f)
            return config

        config = read_config(config_name)
        for key in config:
            try:
                method = talib.get_functions(key)
                tmp_result = method(self._inputs)
                tmp_result = np.vstack(tmp_result).T
                assert tmp_result.shape[0] == self.data.shape[0]
                self.data = np.hstack((self.data, tmp_result))
            except Exception as e:
                raise ValueError(e, 'Wrong in configure')
        self.data_frame = pd.DataFrame(self.data, index=self.data_frame.date)
示例#37
0
                for i, o in enumerate(output):
                    self.lines[i].array = array.array(str('d'), o)

        def next(self):
            # prepare the data arrays - single shot
            size = self._lookback or len(self)
            narrays = [np.array(x.lines[0].get(size=size)) for x in self.datas]

            out = self._tafunc(*narrays, **self.p._getkwargs())

            fsize = self.size()
            lsize = fsize - self._iscandle
            if lsize == 1:  # only 1 output, no tuple returned
                self.lines[0][0] = o = out[-1]

                if fsize > lsize:  # candle is present
                    candleref = narrays[self.CANDLEREF][-1] * self.CANDLEOVER
                    o2 = candleref * (o / 100.0)
                    self.lines[1][0] = o2

            else:
                for i, o in enumerate(out):
                    self.lines[i][0] = o[-1]

    # When importing the module do an automatic declaration of thed
    tafunctions = talib.get_functions()
    for tafunc in tafunctions:
        _TALibIndicator._subclass(tafunc)

    __all__ = tafunctions + ['MA_Type', '_TALibIndicator']
示例#38
0
import numpy as np
import talib
from pandas.io.data import DataReader
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt


f = lambda x: float(x)
SPX = DataReader("SP500",  "fred", datetime(2011,1,1), datetime(2012,1,11)).applymap(f).bfill() #SPX
# SPX['ma']=SPX['SP500'].apply(abstract.Function('sma'))

SPX['SMA'] = talib.MA(SPX.SP500, 15)
print SPX.to_string()

print talib.get_functions()
#https://github.com/mrjbq7/ta-lib
示例#39
0
文件: indicators.py 项目: nanojack/fx
"""
indicators.py

uses talib to add indicator data to market data

"""

import talib  # @UnresolvedImport

FUNCS = talib.get_functions()
FUNC_GROUPS = talib.get_function_groups()

from utils.logger import fx_logger

log = fx_logger(__name__)
log.setLevel("DEBUG")


class Calculator(object):
    """
    wrapper to allow calling of indicator functions
    (just ta-lib functions for now)
    """

    def __call__(self, name, *data, **kwargs):
        if name in FUNCS:
            meth = getattr(talib, name)
            return meth(*data, **kwargs)
        else:
            log.error("talib does not provide {0}".format(name))
            return
示例#40
0
def test_num_functions():
    assert_equals(len(talib.get_functions()), 158)
def get_random_indicator():
    all_indicaotrs = talib.get_functions()
    return talib.abstract.Function(random.sample(all_indicaotrs, 1)[0])
示例#42
0
def handler(event, context):
  return talib.get_functions()[:5] 
示例#43
0
    BarGenerator,
    ArrayManager,
)
from bokeh.io import output_file, show
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import Label
from bokeh.themes import built_in_themes
from bokeh.io import curdoc
from bokeh.palettes import d3, brewer, mpl
from bokeh.core.enums import colors
from bokeh.layouts import column, gridplot
from bokeh.models import WheelZoomTool
from talib import abstract
import talib

print(talib.get_functions())
print(talib.get_function_groups())

palettes_colors = d3["Category20"][20]

xx = np.array([])
xx = np.append(xx, 1)
xx = np.append(xx, 2)

x = np.arange(3343, 3368)
print(x)

vt_symbol = "goog.SMART"
symbol, exchange = extract_vt_symbol(vt_symbol)

start_date = datetime.datetime(2019, 7, 20, 20)
示例#44
0
def talib_candlestick_funcs():
    ''' Retrieves candlestick function names '''
    return [x for x in talib.get_functions() if 'CDL' in x]
示例#45
0
#

import pandas as pd
import numpy as numpy

#import pandas.io.data as web
from pandas_datareader import data, wb
from pandas_datareader.data import Options
import pandas_datareader.data as web

import talib as ta
import matplotlib.pyplot as plt

##Own test
#from pandas.io.data import Options
print(ta.get_functions())

close = numpy.random.random(100)
#print(ta.SMA(close))

import time
import datetime
thirty_days = datetime.date.today() - datetime.timedelta(days=30)
twenty_days = datetime.date.today() - datetime.timedelta(days=20)
def GetStockQuote(symbol) :
    quote = web.get_data_yahoo(symbol,thirty_days.strftime("%m/%d/%Y"), time.strftime("%m/%d/%Y"))
    #quote = web.get_data_yahoo(symbol,thirty_days.strftime("%m/%d/%Y"), twenty_days.strftime("%m/%d/%Y"))
    return quote


#from talib import MA_Type