Esempio n. 1
0
def run_taindicator(name, testdata, inputs, btind, pargs):
    # Now, determine the actual indicators. The name is the name from the
    # bta-lib indicator. Find the corresponding ta indicator
    # Either specified or capitalize the given name
    taind_name = testdata.get('taind', name.upper())
    try:
        taind = getattr(talib, taind_name)
    except AttributeError:
        for taind_name in btind.alias:
            try:
                taind = getattr(talib, taind_name)
            except AttributeError:
                pass
            else:
                break
        else:
            logerror('[-] No ta-lib indicator found for: {}'.format(name))
            return False

    takwargs = testdata.get('takwargs', {})
    if pargs.ta_overargs:
        takwargs = eval('dict(' + pargs.ta_overargs + ')')
    elif pargs.ta_kwargs:
        takwargs.update(eval('dict(' + pargs.ta_kwargs + ')'))

    touts = taind(*inputs, **takwargs)
    if isinstance(touts, pd.Series):  # check if single output
        touts = (touts, )  # consistent single-multiple result presentation

    return touts
Esempio n. 2
0
def run_indicator(pargs, name, testdata, main=False):
    loginfo('[+]' + '-' * 74)
    loginfo('[+] Running test for : {}'.format(name))
    loginfo('[+] Testdata is      : {}'.format(testdata))

    # If a string has been passed, check and return the result
    if isinstance(testdata, str):
        rother = RESULTS.get(testdata, False)
        loginfo('[+] Test completed with : {}'.format(testdata))
        loginfo('[+] Test Result     : {} ({})'.format(rother, name))
        return rother

    elif callable(testdata):
        loginfo('[+] Calling tesdata')
        try:
            ret = testdata(main=main)
        except AssertionError as e:
            ret = False
            _, _, tb = sys.exc_info()
            tb_info = traceback.extract_tb(tb)
            filename, line, func, text = tb_info[-1]
            logging.error('[-] Assertiont Message "{}"'.format(e))
            logging.error('[-] File {} / Line {} / Text {}'.format(
                filename,
                line,
                text,
            ))

        loginfo('[+] Test Result     : {} ({})'.format(ret, name))
        return ret

    # bta-lib indicator calculation
    # The indicator is either the given test name or specified in test data
    btind = getattr(btalib, testdata.get('btind', name))

    # The inputs are either specified in the testdata or the default from ind
    inputs = [df[x] for x in testdata.get('inputs', btind.inputs)]

    btkwargs = testdata.get('btkwargs', {})
    if pargs.bt_overargs:
        btkwargs = eval('dict(' + pargs.bt_overargs + ')')
    elif pargs.bt_kwargs:
        btkwargs.update(eval('dict(' + pargs.bt_kwargs + ')'))

    btresult = btind(*inputs, **btkwargs)
    btouts = list(btresult.outputs)
    for a, b in testdata.get('swapouts', {}).items():
        btouts[a], btouts[b] = btouts[b], btouts[a]

    checkminperiods = testdata.get('minperiods', [])
    if checkminperiods:
        eqperiods = btresult._minperiods == checkminperiods
    else:
        eqperiods = -1

    # Now, determine the actual indicators. The name is the name from the
    # bta-lib indicator. Find the corresponding ta indicator
    # Either specified or capitalize the given name
    taind_name = testdata.get('taind', name.upper())
    try:
        taind = getattr(talib, taind_name)
    except AttributeError:
        for taind_name in btind.alias:
            try:
                taind = getattr(talib, taind_name)
            except AttributeError:
                pass
            else:
                break
        else:
            logerror('[-] No ta-lib indicator found for: {}'.format(name))
            return False

    takwargs = testdata.get('takwargs', {})
    if pargs.ta_overargs:
        takwargs = eval('dict(' + pargs.ta_overargs + ')')
    elif pargs.ta_kwargs:
        takwargs.update(eval('dict(' + pargs.ta_kwargs + ')'))

    touts = taind(*inputs, **takwargs)
    if isinstance(touts, pd.Series):  # check if single output
        touts = (touts, )  # consistent single-multiple result presentation

    # Result checking
    logseries = []
    equal = True  # innocent until proven guilty
    for tseries, btout in zip(touts, btouts):
        btseries = btout.series

        # Rounding to x decimals
        decimals = pargs.decimals
        if decimals is None:  # no command line argument was given
            decimals = testdata.get('decimals', None)

        if decimals is not None and decimals >= 0:
            tseries = tseries.round(decimals=decimals)
            btseries = btseries.round(decimals=decimals)

        # Keep record of entire series for verbosity
        logseries.append([tseries, btseries, btseries.eq(tseries)])

        # Minperiod test check settings
        test_minperiod = pargs.minperiod
        if test_minperiod is None:  # nothing in command line
            test_minperiod = testdata.get('minperiod', 0)
        if not test_minperiod:
            minperiod = btresult._minperiod  # global minperiod
        elif test_minperiod > 0:
            minperiod = btout._minperiod  # per output minperiod
        else:  # < 0
            minperiod = 0  # no minperiod at all

        if minperiod:  # check requested from non starting point
            tseries = tseries[minperiod:]
            btseries = btseries[minperiod:]

        equality = btseries.eq(tseries)  # calculate equality of series
        allequal = equality.all()
        if not allequal:  # make a nancheck
            if btseries.isna().all() and tseries.isna().all():
                allequal = True  # both deliver only nans ... are equal

        equal = equal and allequal  # check if result still equal True

    logging.info('[+] Test Result     : {} ({})'.format(equal, name))

    if pargs.verbose:  # if verbosity is requested
        # General Information
        logdebug('-' * 78)
        logdebug('Result         : {}'.format(equal))
        logdebug('Chk Minperiods : {} {}'.format(
            eqperiods,
            '(-1 if no check done)',
        ))
        logdebug('Decimals       : {}'.format(decimals))
        logdebug('-' * 78)
        logdebug('Indicator      : {}'.format(btind.__name__))
        logdebug('Inputs         : {}'.format(btind.inputs))
        logdebug('Outputs        : {}'.format(btind.outputs))
        logdebug('Def Params     : {}'.format(btind.params))
        logdebug('Params         : {}'.format(dict(btresult.params)))
        logdebug('-' * 78)
        logdebug('Period Check   : {} {}'.format(
            test_minperiod,
            ('(0: after max minperiod / 1: per line / -1: ignore)'),
        ))
        logdebug('Minperiods     : {}'.format(btresult._minperiods))
        logdebug('Minperiod      : {}'.format(btresult._minperiod))
        logdebug('-' * 78)

        # Generate logging dataframe
        pdct = {'count': range(1, len(df.index) + 1)}  # visual period check
        for tseries, btseries, eqseries in logseries:
            name = btseries._name

            pdct['ta__' + name] = tseries
            pdct['bta_' + name] = btseries
            pdct['eq__' + name] = eqseries

        logdf = pd.DataFrame(pdct)
        logdebug(logdf.to_string())

    return equal
Esempio n. 3
0
def run_indicators(metatests, main=False):
    pargs = parse_args(None if main else [], main=main)

    loginfo('')
    loginfo('[+] From main        : {}'.format(main))
    if pargs.list_names:
        loginfo(', '.join(metatests))
        sys.exit(0)

    if pargs.name:  # requested specific indicators
        mtests = {k: v for k, v in metatests.items() if k in pargs.name}
    else:
        mtests = metatests

    if pargs.ad_hoc:
        for name in pargs.name:
            if name in mtests:
                continue

            mtests[name] = {}

    if not mtests:  # empty test set ...
        logerror('[-] No tests could be found')
        if pargs.name:
            logerror('[-] Wanted Indicators: {}'.format(','.join(pargs.name)))

        sys.exit(0)

    posttest = {}
    for name, testdata in mtests.items():
        if testdata is None:  # skip
            continue

        if not testdata:  # empty - create empty data
            testdata = {}

        if isinstance(testdata, int):  # only minperiods specified
            testdata = dict(minperiods=testdata)

        if isinstance(testdata, str):  # delay test referred to other tests
            posttest[name] = testdata
            continue  # skip for later

        RESULTS[name] = run_indicator(pargs, name, testdata, main=main)

    # pseudo-run delayed string tests
    for name, othername in posttest.items():
        loginfo('[+]' + '-' * 74)
        loginfo('[+] Test def is string: "{}"'.format(othername))
        if othername not in RESULTS:
            logerror('[-] Test "{}" not run'.format(othername))
            rother = False
        else:
            loginfo('[+] Test completed with : {}'.format(othername))
            rother = RESULTS[othername]

        RESULTS[name] = rother

        loginfo('[+] Test Result     : {} ({})'.format(rother, name))

    all_good = all(RESULTS.values())

    loginfo('[+]' + '-' * 74)
    logging.info('[+] Global Result: {}'.format(all_good))
    if not all_good:
        sys.exit(1)
Esempio n. 4
0
from time import sleep
from requests import get as rget
from os import environ
from logging import error as logerror

BASE_URL = environ.get('BASE_URL_OF_BOT', None).rstrip("/")
try:
    if len(BASE_URL) == 0:
        raise TypeError
except TypeError:
    BASE_URL = None
PORT = environ.get('PORT', None)
if PORT is not None and BASE_URL is not None:
    while True:
        try:
            rget(BASE_URL).status_code
            sleep(600)
        except Exception as e:
            logerror(f"alive.py: {e}")
            sleep(2)
            continue