def __init__(
        self,
        name,
        model_parsers,
        options_fn=None,
        add_io_options=True,
        add_general_options=True,
        add_logging_options=True,
        add_save_load_options=True,
    ):
        self.name = name

        # Give the option to create pipelines with no models
        if model_parsers is not None:
            self._models = {model.name: model for model in model_parsers}
        else:
            self._models = None

        if name in self._parsers:
            self._parser = self._parsers[name]
        else:
            self._parser = configargparse.get_argument_parser(
                self.name,
                add_help=False,
                prog='kiwi {}'.format(self.name),
                config_file_parser_class=configargparse.YAMLConfigFileParser,
                ignore_unknown_config_file_keys=True,
            )
            self._parsers[name] = self._parser
            self.add_config_option(self._parser)

            if add_io_options:
                opts.io_opts(self._parser)
            if add_general_options:
                opts.general_opts(self._parser)
            if add_logging_options:
                opts.logging_opts(self._parser)
            if add_save_load_options:
                opts.save_load_opts(self._parser)

            if options_fn is not None:
                options_fn(self._parser)

            if model_parsers is not None:
                group = self._parser.add_argument_group('models')
                group.add_argument(
                    '--model',
                    required=True,
                    choices=self._models.keys(),
                    help="Use 'kiwi {} --model <model> --help' for specific "
                    "model options.".format(self.name),
                )

        if 'config' in self._parsers:
            self._config_option_parser = self._parsers['config']
        else:
            self._config_option_parser = configargparse.get_argument_parser(
                'config', add_help=False)
            self._parsers['config'] = self._config_option_parser
            self.add_config_option(self._config_option_parser, read_file=False)
def cfg():
    backend = Path(__file__).parent / 'densedepth_backend'
    parser = configargparse.get_argument_parser()
    group = parser.add_argument_group('DenseDepth',
                                      'DenseDepth-specific params.')
    group.add('--densedepth-path', default=str(backend / 'nyu.h5'))
    group.add('--gpu', type=str)
class Junior(Base, ScikitBase):
    """
    Junior strategy
    About: Strategy using trained model from Junior blueprint factory
    """
    arg_parser = configargparse.get_argument_parser()

    def __init__(self):
        args = self.arg_parser.parse_known_args()[0]
        super(Junior, self).__init__()
        self.name = 'junior'
        self.min_history_ticks = 35
        self.pair = self.parse_pairs(args.pairs)[0]
        self.buy_sell_mode = BuySellMode.all
        self.feature_names = [
            'open', 'quoteVolume', 'close', 'low', 'high', 'volume',
            'weightedAverage', 'ema2', 'ema4', 'ema8', 'ema12', 'ema16',
            'ema20', 'rsi5', 'rsi_above_505', 'cci5', 'macd_above_signal34',
            'macd_above_zero34', 'obv2', 'obv4', 'obv8', 'obv12', 'obv16',
            'obv20'
        ]

    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()

        df = look_back.tail(self.min_history_ticks)
        df_blueprint = Model.calculate_features(df)

        # Remove not-used columns
        df_blueprint = df_blueprint.drop(
            ['pair', 'date', 'id', '_id', 'exchange', 'curr_1', 'curr_2'],
            axis=1)

        # Re-ordering column names
        column_names = self.feature_names
        x = df_blueprint[column_names]
        predicted = self.predict(x)[0]

        new_action = TradeState.sell if predicted == 1 else TradeState.buy
        trade_price = self.get_price(new_action, df.tail(), self.pair)

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
    def __init__(self,
                 name,
                 pipeline_parser,
                 pipeline_config_key,
                 options_fn=None):
        self.name = name
        self._pipeline_parser = pipeline_parser
        self._pipeline_config_key = pipeline_config_key.replace('-', '_')

        self._parser = configargparse.get_argument_parser(
            self.name,
            prog='kiwi {}'.format(self.name),
            add_help=False,
            config_file_parser_class=configargparse.YAMLConfigFileParser,
            ignore_unknown_config_file_keys=False,
        )

        self._parser.add(
            '--config',
            required=False,
            is_config_file=True,
            type=PathType(exists=True),
            help='Load config file from path',
        )

        if options_fn is not None:
            options_fn(self._parser)
Exemple #5
0
def configure_evaluation(args: List[str]) -> argparse.Namespace:

    import configargparse

    p = configargparse.get_argument_parser()
    p.add('-c',
          '--config',
          required=True,
          is_config_file=True,
          help='configuration file')
    p.add('--vocab',
          required=True,
          help='Pickle file containing a Vocabulary object')
    p.add('--corpus', required=True, help='Filename of corpus to evaluate')
    p.add('--encoder',
          required=True,
          help='Pytorch save file containing a trained EncoderRNN object')
    p.add('--decoder',
          required=True,
          help='Pytorch save file containing a trained AttnDecoderRNN object')
    # p.add('--max_decode_length', required=True, type=int, help='Maximum length string to generate during decoding')
    p.add('--max_src_length', required=True, type=int)
    p.add('--max_tgt_length', required=True, type=int)

    return p.parse_args(args=args)
Exemple #6
0
def main():
    argp = configargparse.get_argument_parser()
    argp.add_argument('-i', help='input label inventory csv', type=str)
    argp.add_argument('-o', help='output folder', type=str)
    argp.add_argument('-lsi', help='label selector (comma delimited numbers)', type=str)
    argp.add_argument('-lsr', help='regular expression for labeling', type=str)
    argp.add_argument('-rxkeep', help='keep if regular expression found', type=str)
    argp.add_argument('-rxdrop', help='drop if regular expression found', type=str)
    argp.add_argument('-d', help='label delimiter', type=str, default=" ")
    argp.add_argument('-split', help='split by folders, coma delimited string', type=str, default="train,valid,test")
    argp.add_argument('-portions', help='split by folders, coma delimited string', type=str, default="0.7,0.2,0.1")


    args = {k:v for k,v in vars(argp.parse_args()).items()}



    out = Path('/home/serge/database/data/genomes/ncbi-genomes-2019-04-07')
    folders = {
        'train': out / "Bacillus" / "train",
        'valid': out / "Bacillus" / "valid",
        'test': out / "Bacillus" / "test"
    }
    for k in folders:
        if not os.path.exists(folders[k]):
            os.makedirs(folders[k])

    for i in tqdm(range(short_list.shape[0])):
        cnt = short_list.loc[i, "seq_count"]
        train = int(0.75 * cnt)
        valid = cnt - train
        files = short_list.loc[i, "files"]
        for i in range(cnt):
            copy(files[i], folders["train"]) if i < train else copy(files[i], folders["valid"])
def get_input_arguments():
    argument_parser = configargparse.get_argument_parser()
    argument_parser.add(
        '--host',
        type=str,
        default='minechat.dvmn.org',
        env_var='CHAT_HOST',
        help='An address of the chat host.'
    )
    argument_parser.add(
        '--port',
        type=int,
        default=5000,
        env_var='READING_PORT',
        help='A number of port which the chat server listens.'
    )
    argument_parser.add(
        '--history',
        type=str,
        default='chat_history.txt',
        env_var='HISTORY_FILEPATH',
        help='A file path where script should output result.'
    )
    input_arguments = argument_parser.parse_args()
    return input_arguments
def get_input_arguments():
    argument_parser = configargparse.get_argument_parser()
    argument_parser.add('--host',
                        type=str,
                        default='minechat.dvmn.org',
                        env_var='CHAT_HOST',
                        help='The chat address.')
    argument_parser.add('--port',
                        type=int,
                        default=5050,
                        env_var='WRITING_PORT',
                        help='The number of port the chat server listens.')
    argument_parser.add(
        '--token',
        type=str,
        default='',
        env_var='USER_TOKEN',
        help='An existed user token the client should use to send a message.')
    argument_parser.add('--user_name',
                        type=str,
                        default='Script Bot',
                        env_var='USER_NAME',
                        help="""
        If user do not set the argument '--token', 
        the script will create a new user having this name.
        """)
    argument_parser.add('--message',
                        type=str,
                        default='Hello everyone!',
                        help='A message the client should send.')
    input_arguments = argument_parser.parse_args()
    return input_arguments
Exemple #9
0
def main():
    parser = configargparse.get_argument_parser()

    parser.add('config')

    with open(parser.parse_known_args()[0].config, 'r') as stream:
        args = SimpleNamespace(**yaml.safe_load(stream)['config'])

    args = amci.utils.cuda_config(args)
    torch.set_grad_enabled(False)

    args.figure_remse_number_of_tries = int(
        float(args.figure_remse_number_of_tries))
    args.figure_remse_number_of_y_theta_samples = int(
        float(args.figure_remse_number_of_y_theta_samples))
    args.figure_remse_xaxis_max_samples = int(
        float(args.figure_remse_xaxis_max_samples))

    args.number_of_samples_gpu_capacity = int(
        float(args.number_of_samples_gpu_capacity))

    amci.utils.validate_checkpoints(args)

    if args.logs_root is None:
        args.logs_root = os.path.normpath(
            os.path.join(os.path.dirname(sys.argv[0]), '../../logs'))

    pprint.pprint(args.__dict__)

    generate_and_save_samples(args)
Exemple #10
0
def configure_train(args: List[str]) -> argparse.Namespace:

    import configargparse

    p = configargparse.get_argument_parser()
    p.add('-c', '--config', required=True, is_config_file=True, help='configuration file')

    p.add('--vocab', required=True, help='Pickle file containing a Vocabulary object')
    p.add('--corpus', required=True, help='Filename of corpus to train')
    p.add('--encoder', required=True, help='Path to save trained EncoderRNN object')
    p.add('--decoder', required=True, help='Path to save trained AttnDecoderRNN object')

    p.add('--continue_training', required=False, type=bool, help='Continue training')
    
    p.add('--print_every', required=True, type=int)
    p.add('--batch_size', required=True, type=int)
    p.add('--num_epochs', required=True, type=int)
    p.add('--learning_rate', required=True, type=float)
    p.add('--teacher_forcing_ratio', required=True, type=float)

    p.add('--encoder_embedding_size', required=True, type=int)
    p.add('--encoder_hidden_size', required=True, type=int)
    p.add('--encoder_hidden_layers', required=True, type=int)

    p.add('--decoder_embedding_size', required=True, type=int)
    p.add('--decoder_hidden_size', required=True, type=int)
    p.add('--decoder_hidden_layers', required=True, type=int)
    p.add('--decoder_dropout', required=True, type=float)

    p.add('--max_src_length', required=True, type=int)
    p.add('--max_tgt_length', required=True, type=int)

    return p.parse_args(args=args)
def configure_training(args: List[str]) -> argparse.Namespace:

    p = configargparse.get_argument_parser()
    p.add('-c',
          '--config',
          required=False,
          is_config_file=True,
          help='configuration file')

    p.add('--corpus',
          required=True,
          help='Pickle file containing a MorphemeCorpus object')
    p.add('--hidden_size', required=True, type=int)
    p.add('--hidden_layers', required=True, type=int)

    p.add('-o',
          '--output_file',
          required=True,
          type=str,
          metavar="FILENAME",
          help="Output file where trained MorphemeVectors model will be saved")

    p.add('--continue_training',
          required=False,
          type=bool,
          help='Continue training')

    p.add('--print_every', required=True, type=int)
    p.add('--batch_size', required=True, type=int)
    p.add('--num_epochs', required=True, type=int)
    p.add('--learning_rate', required=True, type=float)

    return p.parse_args(args=args)
 def __init__(self, tool_name: str):
     """Create param namespace, pull global parser and create sub-group for arguments."""
     self.params: argparse.Namespace = argparse.Namespace()
     self.parser: configargparse.ArgumentParser = configargparse.get_argument_parser(
     )
     self.group = self.parser.add_argument_group(tool_name)
     self.env_to_params: Dict[str, str] = dict()
Exemple #13
0
def init_argparser():
    config_home = os.getenv('XDG_CONFIG_HOME', '~/.config')
    home = os.path.expanduser('~')
    if config_home.startswith(home):
        config_home = '~' + config_home[len(home):]
    config_file = os.path.join(config_home, 'blitzloop', 'blitzloop.conf')
    configargparse.init_argument_parser(
        default_config_files=['/etc/blitzloop/blitzloop.conf', config_file])
    parser = configargparse.get_argument_parser()
    parser.add_argument('--fullscreen',
                        default=False,
                        action='store_true',
                        help='run blitzloop fullscreen')
    parser.add_argument('--display',
                        default="glut",
                        help='Choose a display backend')
    parser.add_argument('--mpv-ao',
                        default="jack",
                        help='Audio output driver for libmpv')
    parser.add_argument('--mpv-vo',
                        default="opengl-cb",
                        help='Video output driver for libmpv')
    parser.add_argument('--fps',
                        default="60",
                        type=int,
                        help='Display FPS (required for correct video sync)')
    parser.add_argument(
        '--mpv-options',
        default="",
        help='Additional options for libmpv (space separated opt=val)')
Exemple #14
0
def parse_args():
    """Parse all of the command line arguments"""
    import configargparse
    import sys

    configargparse.init_argument_parser(
        name="main",
        description="MetaWards optional package installation tool. See "
        "https://metawards.org for more information.",
        prog="metawards-install")

    parser = configargparse.get_argument_parser("main")

    parser.add_argument('--version',
                        action="store_true",
                        default=None,
                        help="Print the version information about "
                        "metawards-plot")

    parser.add_argument('--install-optional',
                        action="store_true",
                        default=None,
                        help="Install all of the optional MetaWards "
                        "dependencies")

    parser.add_argument("--conda",
                        action="store_true",
                        default=None,
                        help="Install dependencies using 'conda'")

    parser.add_argument("--pip",
                        action="store_true",
                        default=None,
                        help="Install dependencies using 'pip'")

    parser.add_argument("--dry-run",
                        action="store_true",
                        default=None,
                        help="Just print out what will be done - don't "
                        "actually do anything")

    parser.add_argument("--list",
                        action="store_true",
                        default=None,
                        help="Print out of the optional dependencies.")

    parser.add_argument("--user",
                        action="store_true",
                        default=None,
                        help="Install using '--user' rather than globally.")

    args = parser.parse_args()

    if args.version:
        from metawards import get_version_string
        print(get_version_string())
        sys.exit(0)

    return (args, parser)
Exemple #15
0
class Dojo:
    """
    Main module responsible for training
    """
    arg_parser = configargparse.get_argument_parser()

    def __init__(self):
        args = self.arg_parser.parse_known_args()[0]
        self.verbose = args.verbose

    def train(self,
              blueprint=None,
              automatic_search=True,
              models=None,
              minimum_score=0.7):
        """
        Trains input data by automatic_search (GA) or with given models
        :param blueprint: multi-currency features csv file (for example generated by blueprint module)
        :param automatic_search: automatically find the best models
        :param models: list of models to be used. If automatic_search is True, models will be included into model search
        :param minimum_score: minimum_score the model needs to have so that it is returned
        :return: list of best models with their score
        """
        if not blueprint:
            print(
                "Required blueprint csv. argument value is missing, nothing to do here."
            )
            return

        print('Loading dataset')
        df_pair_groups = self.load_blueprint(blueprint)
        # Get trained models for every pair
        for pair, df in df_pair_groups:
            pair_models = self.train_pair(pair, df, automatic_search, models,
                                          minimum_score)
            # TODO: Store pair_models
            print(pair)

    @staticmethod
    def train_pair(pair, df, automatic_search, models, minimum_score):
        """
        Function that trains given dataset for a specific pair
        """
        print('Training model for pair:', pair)
        # TODO: Train model
        return pair, None

    @staticmethod
    def load_blueprint(blueprint_file):
        """
        Loads blueprint csv file and returns paired groups (grouped by pair)
        """
        print('Loading dataset')
        df = pd.read_csv(blueprint_file)
        df_pair_groups = df.groupby(['pair'])
        pairs_names = list(df_pair_groups.groups.keys())
        print('Training total of: ', len(pairs_names), 'pairs and ',
              df.shape[0], 'records')
        return df_pair_groups
Exemple #16
0
    def __init__(self):
        print("a s d")
        p = configargparse.get_argument_parser()
        options, junk = p.parse_known_args()

        print("options.SOMETHINGNEW in Some other class:", options.SOMETHINGNEW)

        p.add_argument("--SomethingFromSomeOtherClass", help="Config-file-settable option for utils")
Exemple #17
0
class Backtest(Base):
    """
    Main class for Backtest trading
    """
    arg_parser = configargparse.get_argument_parser()
    arg_parser.add('--backtest_from', help='Backtest epoch start datetime')
    arg_parser.add("--backtest_to", help='Backtest epoch end datetime')
    arg_parser.add(
        "--days",
        help='Number of history days the simulation should start from')

    mode = TradeMode.backtest
    sim_start = None
    sim_end = None
    sim_days = None

    def __init__(self, wallet):
        args = self.arg_parser.parse_known_args()[0]
        super(Backtest, self).__init__(self.mode)
        self.counter = 0
        if args.backtest_from:
            self.sim_start = int(args.backtest_from)
        if args.backtest_to:
            self.sim_end = int(args.backtest_to)
        if args.days:
            self.sim_days = int(args.days)
        self.sim_epoch_start = self.get_sim_epoch_start(
            self.sim_days, self.sim_start)
        self.current_epoch = self.sim_epoch_start
        self.balance = wallet

    @staticmethod
    def get_sim_epoch_start(sim_days, sim_start):
        if sim_start:
            return sim_start
        elif sim_days:
            epoch_now = int(time.time())
            return epoch_now - (DAY_IN_SECONDS * sim_days)

    def get_next(self, interval_in_min):
        """
        Returns next state of current_time + interval (in minutes)
        """
        if self.sim_end and self.current_epoch > self.sim_end:
            return pd.DataFrame()
        self.ticker_df = self.exchange.get_offline_ticker(
            self.current_epoch, self.pairs)
        self.current_epoch += interval_in_min * 60
        return self.ticker_df

    def trade(self, actions, wallet, trades, force_sell=True):
        """
        Simulate currency buy/sell (places fictive buy/sell orders)
        """
        return super(Backtest, self).trade(actions,
                                           wallet,
                                           trades,
                                           force_sell=False)
def parse_args():
    s_list = STRATEGIES.keys()
    parser = configargparse.get_argument_parser(default_config_files=['config.yml', 'batch.yml'])
    # configuration arguments:
    parser.add_argument("--dsn", help="DSN to for the connection to PostGIS", required=True)
    parser.add_argument("--lidar_table", help="pointcloud table containing lidar/srtm data", required=True)
    parser.add_argument("--base_folder", help="Output base folder for the data", required=True)
    parser.add_argument("-P", "--processes", help="number of parallel processes",
                        default=1, type=int)
    # simulation parameters:
    # iterables
    parser.add_argument("-s", "--strategy",
                        help="a strategy to be used",
                        required=True,
                        action="append")
    parser.add_argument("-d", "--dataset",
                             help="a data set from the available ones",
                             required=True,
                             action="append")

    parser.add_argument("--max_dev",
                             help="maximum number of devices per node",
                             type=int, default=float('inf'), nargs='+')
    parser.add_argument('-g', "--gateway", help="gateway number in [0,n] from gws.yml",
                             type=int, required=True,  nargs='+')
    parser.add_argument('-n', "--max_size", help="number of nodes", type=int, nargs='+')
    parser.add_argument('-e', "--expansion", help="expansion range (in meters),"
                             " defaults to buildings at 30km", type=float,
                             default=30000, nargs='+')
    parser.add_argument('-V', "--viewshed_extra", help="Add at most v links extra link if"
            "these are in the viewshed of the current one.", type=int, default=0, nargs='+')
    parser.add_argument("-C", "--channel_width", help="802.11 channel width",
                    choices=[20,40,80,160], default=20, type=int, nargs="+")

    # not iterables
    parser.add_argument('-B', "--bandwidth", help="Accepts three arguments: bw frac min_n."
            "Stop when a fraction of frac nodes has less than bw bandwidth. "
            "Start measuring after min_n nodes (initially things may behave strangely "
            "(in Mbps). Ex: '1 0 1' will stop when any node has less than 1Mbps "
            "(in Mbps). Ex: '5 0.15 10' will stop when 15% of nodes has less than 5Mbps "
            "but not before we have at least 10 nodes",
            default="1 0 1")
    parser.add_argument('-R', "--restructure", help="restructure with edgeffect every r"
            " rounds, adding l links. Accepts two arguments: r l", default=[])

    parser.add_argument('-r', "--seed", help="random seed,", type=int)
    parser.add_argument("--runs", help="number of repeated runs", default=1, type=int)

    # flags
    parser.add_argument("-D", help="debug: print metrics at each iteration"
                             " and save metrics in the './data' folder",
                             action='store_true')

    parser.add_argument("-p", help="plot the graph using the browser",
                             dest='plot', action='store_true', default=False)
    args, unknown = parser.parse_known_args()
    return args, unknown
def cfg():
    backend = Path(__file__).parent/'midas_backend'
    parser = configargparse.get_argument_parser()
    group = parser.add_argument_group('MiDaS', 'MiDaS-specific params.')
    group.add('--midas-path', default=str(backend/'model.pt'))
    group.add('--full-width', type=int, default=640)
    group.add('--full-height', type=int, default=480)
    group.add('--min-depth', type=float, default=0.1)
    group.add('--max-depth', type=float, default=10.)
    group.add('--gpu', type=str)
Exemple #20
0
 def __init__(self, name, pairs):
     super(Base, self).__init__()
     self.name = name
     self.pairs = pairs
     arg_parser = configargparse.get_argument_parser()
     self.args = arg_parser.parse_known_args()[0]
     self.price_intervals = [int(x.strip()) for x in self.args.price_intervals.split(',')]
     self.Y_prefix = 'Y_'
     self.Yt_prefix = 'Yt_'
     self.Yt_column_names = self.create_yt_column_names(self.price_intervals, self.Yt_prefix)
Exemple #21
0
def get_args():
    p = configargparse.get_argument_parser()
    #dont use parse_args because that will error
    #if there are extra arguments e.g. for plugins
    args = p.parse_known_args()[0]

    #output all configuration values, useful for debugging
    p.print_values()

    return args
Exemple #22
0
def cfg():
    parser = configargparse.get_argument_parser()
    group = parser.add_argument_group('MDE', 'MDE Wrapper config')
    group.add('--mde', choices=['DORN', 'DenseDepth', 'MiDaS'], default='DORN')
    group.add('--img-key',
              default='dorn_image',
              help='Key in data corresponding to image')
    group.add('--in-type', choices=['torch', 'numpy'], default='torch')
    group.add('--in-order', choices=['nchw', 'nhwc'], default='nchw')
    group.add('--out-type', choices=['torch', 'numpy'], default='torch')
    group.add('--out-order', choices=['nchw', 'nhwc'], default='nchw')
 def get_parser(cls, name, **kwargs):
     if name in cls._parsers:
         return cls._parsers[name]
     parser = configargparse.get_argument_parser(
         name,
         prog='... {}'.format(name),
         config_file_parser_class=configargparse.YAMLConfigFileParser,
         ignore_unknown_config_file_keys=True,
         **kwargs,
     )
     cls._parsers[name] = parser
     return parser
def cfg():
    parser = configargparse.get_argument_parser()
    group = parser.add_argument_group('eval_captured', 'evaluation params.')
    group.add('--scene-config', is_config_file=True)
    group.add('--mde-config', is_config_file=True)
    group.add('--method', choices=['mde', 'transient'], required=True)
    group.add('--scene', choices=['kitchen', 'classroom', 'desk', 'hallway',
                                  'poster', 'lab', 'outdoor'],
              default='lab')
    group.add('--transform', action='append')
    group.add('--output-dir', default=str(Path(__file__).parent/'results_captured'))
    group.add('--gpu', type=str)
class StopLoss:
    """
    StopLoss class with normal and trailing stop-loss functionality
    :param: interval: Interval in minutes for checking price difference
    :param stop_loss_limit: Percentage value for stop-loss (how much should the price drop to send stop-loss signal
    :param trailing: If True stop_loss Trailing stop-loss will be applied. If False first price will be used
    for a static stop-loss limit
    :param ticker_size: Ticker size
    """

    arg_parser = configargparse.get_argument_parser()
    arg_parser.add('--stoploss_interval', help='Stop-loss interval in minutes')
    base_price = None

    def __init__(self, ticker_size, interval=30, stop_loss_limit=-0.1, trailing=True, ):
        self.trailing = trailing
        self.checkpoint = int(interval/ticker_size)
        self.stop_loss_limit = stop_loss_limit

    def set_base_price(self, price):
        """
        Sets base price, which is compared to trailing-stop
        :param price:
        """
        self.base_price = price

    def calculate(self, price):
        """

        :param price: numpy array of price values
        :return: Returns True if Stop-Loss met conditions
        """

        # Check if array has data
        if len(price) < self.checkpoint:
            print('StopLoss: not enough data.')
            return False

        if not self.base_price:
            self.base_price = price[-1]
            print('StopLoss: setting base-price to:', self.base_price)
            return False

        last_price = price[-1]
        checkpoint_price = price[-self.checkpoint]
        percentage_change = last_price*100/checkpoint_price - 100.0
        if percentage_change <= self.stop_loss_limit:
            return True

        # Handle trailing
        if self.trailing:
            if last_price > self.base_price:
                self.base_price = last_price
def cfg():
    parser = configargparse.get_argument_parser()
    group = parser.add_argument_group('eval_nyuv2', 'evaluation params.')
    group.add('-c', is_config_file=True)
    group.add('--method', choices=['mde', 'median', 'gt_hist', 'transient'],
               default='mde', help="Method to evaluate.")
    group.add('--sbr', type=float, default=5., help='sbr for transient method')
    group.add('--split', choices=['train', 'test'], default='test')
    group.add('--transform', action='append')
    group.add('--pre-cropped', action='store_true',
               help="True if the model being evaluated already outputs cropped depth images.")
    group.add('--output-dir', default=str(Path(__file__).parent/'results'))
    group.add('--gpu', type=str)
def main():
    argp = configargparse.get_argument_parser()
    argp.add_argument('-i',
                      help='input folder with Fasta files',
                      type=str,
                      default='.')
    argp.add_argument('-o',
                      help='output folder',
                      type=str,
                      default="../d2v_dataset")
    args = {k: v for k, v in vars(argp.parse_args()).items()}

    preprocess_for_dna2vec_training(path=args["i"], out_path=args["o"])
Exemple #28
0
def main():
    actions = {
        'enactability': handle_enactability,
        'liveness': handle_liveness,
        'safety': handle_safety,
        'atomicity': handle_atomicity,
        'syntax': check_syntax,
        'all': handle_all
    }

    parser = configargparse.get_argument_parser()
    parser.description = 'BSPL Protocol property checker'
    parser.add('-s', '--stats', action="store_true", help='Print statistics')
    parser.add('-v',
               '--verbose',
               action="store_true",
               help='Print additional details: spec, formulas, stats, etc.')
    parser.add('-q',
               '--quiet',
               action="store_true",
               help='Prevent printing of violation and formula output')
    parser.add('-f',
               '--filter',
               default='.*',
               help='Only process protocols matching regexp')
    parser.add('--version', action="store_true", help='Print version number')
    parser.add('--debug', action="store_true", help='Debug mode')
    parser.add('action',
               help='Primary action to perform',
               choices=actions.keys())
    parser.add('input', nargs='+', help='Protocol description file(s)')

    if '--version' in sys.argv:
        print(__version__)
        sys.exit(0)
    else:
        args = parser.parse()
        global debug
        debug = args.debug

    for path in args.input:
        spec = load_file(path)
        for protocol in spec.protocols.values():
            if re.match(args.filter, protocol.name):
                print("%s (%s): " % (protocol.name, path))
                actions[args.action](protocol, args)
                print()

    if not spec.protocols:
        print("No protocols parsed from file: ", args.input)
Exemple #29
0
class Stats:
    """
    Main class for statistics
    """

    arg_parser = configargparse.get_argument_parser()

    def __init__(self):
        self.args = self.arg_parser.parse_known_args()[0]

    def run(self):
        print("running stats")

    """
def configure_testing(args: List[str]) -> argparse.Namespace:

    p = configargparse.get_argument_parser()
    p.add('-c',
          '--config',
          required=False,
          is_config_file=True,
          help='configuration file')

    p.add('--morpheme_vectors',
          required=True,
          help='Pickle file containing a MorphemeVectors object')
    p.add('--batch_size', required=True, type=int)

    return p.parse_args(args=args)
Exemple #31
0
def init_argparser():
    config_home = os.getenv('XDG_CONFIG_HOME', '~/.config')
    home = os.path.expanduser('~')
    if config_home.startswith(home):
        config_home = '~' + config_home[len(home):]
    config_file = os.path.join(config_home, 'blitzloop', 'blitzloop.conf')
    configargparse.init_argument_parser(
            default_config_files=['/etc/blitzloop/blitzloop.conf', config_file])
    parser = configargparse.get_argument_parser()
    parser.add_argument(
        '--fullscreen', default=False, action='store_true',
        help='run blitzloop fullscreen')
    parser.add_argument(
        '--display', default="glut",
        help='Choose a display backend')
    parser.add_argument(
        '--mpv-audio-device', default="jack",
        help='Audio output driver and device for libmpv')
    parser.add_argument(
        '--mpv-ao', default=None,
        help='Audio output driver for libmpv (deprecated, use --mpv-audio-device)')
    parser.add_argument(
        '--mpv-options', default="",
        help='Additional options for libmpv (space separated opt=val)')
    parser.add_argument(
        '--mpv-msg-level', default=None,
        help='Message level for mpv')
    parser.add_argument(
        '--mpv-vo', default="opengl-cb",
        help='Video output driver for libmpv')
    parser.add_argument(
        '--mpv-hwdec', default=None,
        help='Hardware decoding mode for libmpv (try --mpv-hwdec=vaapi)')
    parser.add_argument(
        '--mpv-visualizer', default="[aid1]asplit=2[ao][a1]; [a1]volume=volume=%(volume)f * 3.0,showcqt=bar_v=8:count=1:basefreq=120:csp=bt709:s=128x72:axis=0:fps=60:sono_h=0:bar_g=3:cscheme=0.5|1|0|0|0.5|1,format=pix_fmts=rgb24,split[c1][c2]; [c2]vflip,hflip[c3]; [c1][c3]blend=all_mode=addition[vo]",
        help='Visualizer filter for no-video songs')
    parser.add_argument(
        '--fps', default="60", type=int,
        help='Display FPS (required for correct video sync)')
Exemple #32
0
def get_argparser():
    return configargparse.get_argument_parser()