Ejemplo n.º 1
0
    def test_chain_get_by_delta(self):
        assetindex = AssetIndexMongo(MONGO_CONNSTR, MONGO_EXO_DB)

        base_date = datetime(2015, 6, 13, 12, 45, 0)

        futures_limit = 3
        options_limit = 20

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

        instr = datasource.get("ES", base_date)
        rh = RolloverHelper(instr)
        fut, opt_chain = rh.get_active_chains()

        atm_strike = opt_chain.atmstrike

        opt = opt_chain.get_by_delta(0.5)
        self.assertEqual(opt.strike, atm_strike)
        self.assertEqual(opt.putorcall, 'C')

        opt = opt_chain.get_by_delta(-0.5)
        self.assertEqual(opt.strike, atm_strike)
        self.assertEqual(opt.putorcall, 'P')

        self.assertRaises(ValueError, opt_chain.get_by_delta, 0)
        self.assertRaises(ValueError, opt_chain.get_by_delta, float('nan'))
        self.assertRaises(ValueError, opt_chain.get_by_delta, 1)
        self.assertRaises(ValueError, opt_chain.get_by_delta, 2)
        self.assertRaises(ValueError, opt_chain.get_by_delta, -2)
        self.assertRaises(ValueError, opt_chain.get_by_delta, -1)

        # ITM Put
        opt = opt_chain.get_by_delta(-0.7)
        self.assertEqual(opt.strike, 2115)
        self.assertEqual(opt.putorcall, 'P')
        self.assertAlmostEqual(opt.delta, -0.75, 2)

        opt = opt_chain.get_by_delta(-0.999999)
        self.assertEqual(opt.strike, 2195.0)
        self.assertEqual(opt.putorcall, 'P')
        self.assertAlmostEqual(opt.delta, -0.989, 3)

        # OTM Put
        opt = opt_chain.get_by_delta(-0.3)
        self.assertEqual(opt.strike, 2070)
        self.assertEqual(opt.putorcall, 'P')
        self.assertAlmostEqual(opt.delta, -0.27, 2)

        opt = opt_chain.get_by_delta(-0.00001)
        self.assertEqual(opt, opt_chain[-20].P)

        # ITM Call
        opt = opt_chain.get_by_delta(0.7)
        self.assertEqual(opt.strike, 2070)
        self.assertEqual(opt.putorcall, 'C')
        self.assertAlmostEqual(opt.delta, 0.73, 2)

        opt = opt_chain.get_by_delta(0.9999999)
        self.assertEqual(opt, opt_chain[-20].C)

        # OTM Call
        opt = opt_chain.get_by_delta(0.3)
        self.assertEqual(opt.strike, 2115)
        self.assertEqual(opt.putorcall, 'C')
        self.assertAlmostEqual(opt.delta, 0.24, 2)

        opt = opt_chain.get_by_delta(0.000001)
        self.assertEqual(opt, opt_chain[20].C)
Ejemplo n.º 2
0
    assetindex = AssetIndexMongo(mongo_connstr, mongo_db_name)
    exostorage = EXOStorage(mongo_connstr, mongo_db_name)

    base_date = datetime(2014, 1, 13, 12, 45, 0)
    futures_limit = 3
    options_limit = 10

    DEBUG = '.'

    datasource = DataSourceMongo(mongo_connstr, mongo_db_name, assetindex,
                                 futures_limit, options_limit, exostorage)

    server = 'h9ggwlagd1.database.windows.net'
    user = '******'
    password = '******'
    datasource = DataSourceSQL(server, user, password, assetindex,
                               futures_limit, options_limit, exostorage)

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

    instruments = ['CL', 'ES']
    directions = [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:
            for dir in directions:
Ejemplo 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()