def test_notify_error_boto_error(self):
        with patch.object(aws_service_wrapper, 'cf_read_export_value',
                          return_value="some_sns_arn"), \
            patch.object(aws_service_wrapper, 'sns_publish_notification',
                         side_effect=AWSError("test exception", None)):

            with self.assertRaises(AWSError):
                aws_service_wrapper.notify_error(
                    "Security Recommendation Service", Exception("None"), 'stack trace', 'sa')
예제 #2
0
def main():
    """
        Main function of this script
    """
    try:
        #(app_ns, portfolio_size) = parse_params()
        (app_ns, portfolio_size) = ('sa', 3)

        log.info("Application Parameters")
        log.info("-app_namespace: %s" % app_ns)
        log.info("-portfolio_size: %d" % portfolio_size)

        # test all connectivity upfront, so if there any issues
        # the problem becomes more apparent
        connector_test.test_all_connectivity()

        (current_portfolio,
         security_recommendation) = portfolio_mgr_svc.get_service_inputs(app_ns)

        log.info("Loaded recommendation set id: %s" %
                 security_recommendation.model['set_id'])

        if current_portfolio is None:
            log.info("Creating new portfolio")
            current_portfolio = Portfolio(None)
            current_portfolio.create_empty_portfolio(security_recommendation)
        else:
            log.info("Repricing portfolio")
            current_portfolio.reprice(datetime.now())

        (updated_portfolio, updated) = portfolio_mgr_svc.update_portfolio(
            current_portfolio, security_recommendation, portfolio_size)

        # See if there is anything that needs to be traded
        market_open = td_ameritrade.equity_market_open(datetime.now())

        if market_open == True:
            broker = Broker()
            broker.cancel_all_open_orders()

            log.info("Market is open. Looking for trading opportunities")
            current_positions = td_ameritrade.positions_summary()

            try:
                if broker.reconcile_portfolio(current_positions, updated_portfolio) == False:
                    log.info(
                        "Portfolio is not in sync with brokerage account positions. Positions will be rebalanced")

                broker.materialize_portfolio(
                    current_positions, updated_portfolio)
            finally:
                updated_positions = td_ameritrade.positions_summary()
                broker.synchronize_portfolio(
                    updated_positions, updated_portfolio)

                updated_portfolio.recalc_returns()
                broker.cancel_all_open_orders()
        else:
            log.info("Market is closed. Nothing to trade")

        log.info("updated portfolio: %s" %
                 util.format_dict(updated_portfolio.to_dict()))

        log.info("Saving updated portfolio")
        updated_portfolio.save_to_s3(
            app_ns, constants.S3_PORTFOLIO_OBJECT_NAME)

        portfolio_mgr_svc.publish_current_returns(
            updated_portfolio, updated, app_ns)

    except Exception as e:
        stack_trace = traceback.format_exc()
        log.error("Could run script, because: %s" % (str(e)))
        log.error(stack_trace)

        aws_service_wrapper.notify_error(e, "Portfolio Manager Service",
                                         stack_trace, app_ns)
예제 #3
0
def main():
    """
        Main function for this script
    """
    try:
        (environment, ticker_file_name, output_size, month, year,
         current_price_date, app_ns) = parse_params()

        log.info("Parameters:")
        log.info("Environment: %s" % environment)
        log.info("Ticker File: %s" % ticker_file_name)
        log.info("Output Size: %d" % output_size)
        log.info("Analysis Month: %d" % month)
        log.info("Analysis Year: %d" % year)

        if environment == "TEST":
            log.info("reading ticker file from local filesystem")
            ticker_list = TickerFile.from_local_file(
                constants.TICKER_DATA_DIR, ticker_file_name).ticker_list

            log.info("Performing Recommendation Algorithm")
            strategy = PriceDispersionStrategy(ticker_list, year, month,
                                               output_size)
            strategy.generate_recommendation()
            display_calculation_dataframe(month, year, strategy,
                                          current_price_date)
        else:  # environment == "PRODUCTION"
            # test all connectivity upfront, so if there any issues
            # the problem becomes more apparent
            connector_test.test_aws_connectivity()
            connector_test.test_intrinio_connectivity()

            log.info("Reading ticker file from s3 bucket")
            ticker_list = TickerFile.from_s3_bucket(ticker_file_name,
                                                    app_ns).ticker_list

            log.info("Loading existing recommendation set from S3")
            recommendation_set = None

            try:
                recommendation_set = SecurityRecommendationSet.from_s3(app_ns)
            except AWSError as awe:
                if not awe.resource_not_found():
                    raise awe
                log.info("No recommendation set was found in S3.")

            if recommendation_set == None  \
                    or not recommendation_set.is_current(datetime.now()):

                log.info("Performing Recommendation Algorithm")
                strategy = PriceDispersionStrategy(ticker_list, year, month,
                                                   output_size)

                strategy.generate_recommendation()
                recommendation_set = strategy.recommendation_set
                display_calculation_dataframe(month, year, strategy,
                                              current_price_date)

                recommendation_set.save_to_s3(app_ns)
                recommendation_svc.notify_new_recommendation(
                    recommendation_set, app_ns)
            else:
                log.info(
                    "Recommendation set is still valid. There is nothing to do"
                )

    except Exception as e:
        stack_trace = traceback.format_exc()
        log.error("Could run script, because: %s" % (str(e)))
        log.error(stack_trace)

        if environment == "PRODUCTION":
            aws_service_wrapper.notify_error(
                e, "Securities Recommendation Service", stack_trace, app_ns)