def main(self):
        self.logger.info("Initiating EXO building engine for {0}".format(
            self.args.instrument))

        # Initialize EXO engine SignalApp (report first status)
        self.signalapp = SignalApp(self.args.instrument, APPCLASS_EXO,
                                   RABBIT_HOST, RABBIT_USER, RABBIT_PASSW)
        self.signalapp.send(MsgStatus('INIT', 'Initiating EXO engine'))

        # Get information about decision and execution time
        assetindex = AssetIndexMongo(MONGO_CONNSTR, MONGO_EXO_DB)
        self.asset_info = assetindex.get_instrument_info(args.instrument)

        if self.args.backfill is not None:
            # Backfill mode enabled
            self.do_backfill()
            self.signalapp.send(
                MsgStatus("OK",
                          "EXO backfill for {0} has been finished.".format(
                              self.args.instrument),
                          notify=True))
        else:
            # Online mode

            # Subscribe to datafeed signal app
            self.logger.debug('Subscribing datafeed for: ' +
                              self.args.instrument)
            datafeed = SignalApp(self.args.instrument, APPCLASS_DATA,
                                 RABBIT_HOST, RABBIT_USER, RABBIT_PASSW)
            # Listening datafeed loop
            datafeed.listen(self.on_new_quote)
    def main(self):
        logging.info("Initiating data notification script")

        # Initialize EXO engine SignalApp (report first status)
        self.signalapp = SignalApp(self.args.instrument, APPCLASS_DATA,
                                   RABBIT_HOST, RABBIT_USER, RABBIT_PASSW)
        self.signalapp.send(
            MsgStatus('INIT', 'Initiating data notification script'))

        # Get information about decision and execution time
        assetindex = AssetIndexMongo(MONGO_CONNSTR, MONGO_EXO_DB)
        self.asset_info = assetindex.get_instrument_info(args.instrument)

        # TODO: replace DB name after release
        mongo_db_name = 'tmldb_test'
        tmp_mongo_connstr = 'mongodb://*****:*****@10.0.1.2/tmldb_test?authMechanism=SCRAM-SHA-1'
        client = MongoClient(tmp_mongo_connstr)
        self.db = client[mongo_db_name]
        # Creating index for 'bartime'
        self.db['futurebarcol'].create_index([('bartime', pymongo.DESCENDING)],
                                             background=True)

        status_client = MongoClient(MONGO_CONNSTR)
        self.status_db = status_client[MONGO_EXO_DB]
        self.status_db[STATUS_QUOTES_COLLECTION].create_index(
            [('instrument', pymongo.DESCENDING)], background=True)

        last_minute = 0
        while True:
            # Getting last bar time from DB
            last_bar_time = self.get_last_bar_time()
            self.process_quote(last_bar_time)
            time.sleep(15)
Exemplo n.º 3
0
class SmartEXOUtils:
    def __init__(self, smartexo_class, **kwargs):
        self.verbosive_logging = kwargs.get('verbosive_logging', False)
        self.futures_limit = kwargs.get('futures_limit', 3)
        self.options_limit = kwargs.get('options_limit', 20)
        self.smartexo_class = smartexo_class

        if self.verbosive_logging:
            logging.basicConfig(format='%(message)s', level=logging.DEBUG)
        else:
            logging.basicConfig(format='%(message)s', level=logging.INFO)

        self.assetindex = AssetIndexMongo(MONGO_CONNSTR, MONGO_EXO_DB)
        self.exostorage = EXOStorage(MONGO_CONNSTR, MONGO_EXO_DB)

        self.datasource = DataSourceSQL(SQL_HOST, SQL_USER, SQL_PASS,
                                        self.assetindex, self.futures_limit,
                                        self.options_limit, self.exostorage)

    def plot_transactions_payoff(self, smart_exo_position_func, analysis_date,
                                 analysis_instrument, **whatif_kwargs):

        payoff = PayoffAnalyzer(self.datasource)
        instr = self.datasource.get(analysis_instrument, analysis_date)
        rh = RolloverHelper(instr)
        fut, opt_chain = rh.get_active_chains()

        strikes_on_graph = whatif_kwargs.get('strikes_on_graph', 30)
        whatif_iv_change = whatif_kwargs.get('whatif_iv_change', 0)
        whatif_days_to_expiration = whatif_kwargs.get(
            'whatif_days_to_expiration', int(opt_chain.to_expiration_days / 2))

        payoff.load_transactions(
            smart_exo_position_func(analysis_date, fut, opt_chain),
            analysis_date)
        payoff.plot(strikes_on_graph, whatif_iv_change,
                    whatif_days_to_expiration)

    def clear_smartexo(self):
        logging.info("Deleting all SmartEXO of :" +
                     self.smartexo_class.EXO_NAME)
        client = MongoClient(MONGO_CONNSTR)
        db = client[MONGO_EXO_DB]
        db['exo_data'].delete_many({
            'name': {
                '$regex': '.*{0}*.'.format(self.smartexo_class.EXO_NAME)
            }
        })

    def build_smartexo(self, start_date, **smartexo_kwargs):
        self.clear_smartexo()

        logging.info(
            "Starting EXO calculation process from: {0}".format(start_date))

        if self.smartexo_class.ASSET_LIST is None:
            warnings.warn(
                "You must define ASSET_LIST inside SmartEXO class. Aborting..."
            )
            return

        for ticker in self.smartexo_class.ASSET_LIST:
            logging.info("Processing: " + ticker)
            currdate = start_date
            enddate = datetime.combine(datetime.now().date(), dttime(0, 0, 0))

            while currdate <= enddate:
                start_time = time.time()
                date = currdate

                asset_info = self.assetindex.get_instrument_info(ticker)
                exec_time_end, decision_time_end = AssetIndexMongo.get_exec_time(
                    date, asset_info)

                logging.info("\t\tRun on {0}".format(decision_time_end))

                with self.smartexo_class(ticker, 0, decision_time_end,
                                         self.datasource,
                                         **smartexo_kwargs) as exo_engine:
                    try:
                        asset_list = exo_engine.ASSET_LIST
                        # Checking if current symbol is present in EXO class ASSET_LIST
                        if asset_list is not None:
                            if ticker not in asset_list:
                                # Skipping assets which are not in the list
                                continue
                    except AttributeError:
                        warnings.warn(
                            "EXO class {0} doesn't contain ASSET_LIST attribute filter, calculating all assets"
                            .format(self.smartexo_class))

                    # Load EXO information from mongo
                    exo_engine.load()
                    exo_engine.calculate()

                end_time = time.time()
                currdate += timedelta(days=1)
                logging.debug("Elapsed: {0}".format(end_time - start_time))
        logging.info('Done')

    def plot_smartexo_price(self):
        if self.smartexo_class.ASSET_LIST is None:
            warnings.warn(
                "You must define ASSET_LIST inside SmartEXO class. Aborting..."
            )
            return

        for ticker in self.smartexo_class.ASSET_LIST:
            exo_df, exo_info = self.exostorage.load_series('{0}_{1}'.format(
                ticker, self.smartexo_class.EXO_NAME))

            f, (ax1, ax2) = plt.subplots(2,
                                         gridspec_kw={'height_ratios': [3, 1]})

            exo_df['exo'].plot(ax=ax1,
                               title='{0}_{1}'.format(
                                   ticker, self.smartexo_class.EXO_NAME))
            ax = exo_df['regime'].plot(ax=ax1, secondary_y=True)
            ax.set_ylim(-2, 2)

            exo_df['delta'].plot(ax=ax2)
            ax2.set_title('Delta')
            plt.show()
                               futures_limit, options_limit, exostorage)

    enddate = datetime.combine(datetime.now().date(), dttime(12, 45, 0))
    currdate = base_date

    instruments = ['CL', 'ES', 'NG', 'ZC', 'ZS', 'ZW', 'ZN']
    directions = [1]  #[1, -1]

    # for i in range(100):
    while currdate <= enddate:
        start_time = time.time()
        # date = base_date + timedelta(days=i)
        date = currdate

        for ticker in instruments:
            asset_info = assetindex.get_instrument_info(ticker)
            exec_time_end, decision_time_end = AssetIndexMongo.get_exec_time(
                date, asset_info)

            for dir in directions:
                with SmartEXOichimokuFutures(
                        ticker,
                        dir,
                        exec_time_end,
                        datasource,
                        log_file_path=DEBUG) as exo_engine:
                    # Load EXO information from mongo
                    exo_engine.load()
                    exo_engine.calculate()

        end_time = time.time()