Esempio n. 1
0
def request(method: str, url: str, params: dict, payload: dict):
    '''
        Value add wrapper around the "request" method. Add auth header, timeout,
        and throws an exception if the response is not valid

        Parameters
        ----------
        method : str
            the HTTP method (GET, PUT, etc) of the request
        url : str
            URL of the API
        params : dict
            request parameters
        payload : dict
            request payload (data)
    '''
    try:
        api_response = requests.request(method,
                                        url,
                                        params=params,
                                        json=payload,
                                        headers=auth_header(),
                                        timeout=REQUEST_TIMEOUT)
    except Exception as e:
        raise TradeError("Could not execute %s to %s" % (method, url), e, None)

    __validate_response(url, api_response)

    try:
        body = api_response.json()
        log.debug("API Response: %s" % util.format_dict(body))
        return (api_response.headers, body)
    except:
        log.debug("API Response: None")
        return (api_response.headers, {})
    def display_results(self):
        '''
            Displays the results of the strategy to the screen.
            Specifically displays the ranking of the securities using
            a Pandas Dataframe and the resulting recommendation set.
        '''
        log.info("Calculating Current Returns")
        raw_dataframe = calculator.mark_to_market(self.raw_dataframe, 'ticker',
                                                  'analysis_price',
                                                  self.current_price_date)
        recommendation_dataframe = calculator.mark_to_market(
            self.recommendation_dataframe, 'ticker', 'analysis_price',
            self.current_price_date)

        log.info("")
        log.info("Recommended Securities")
        log.info(util.format_dict(self.recommendation_set.to_dict()))
        log.info("")

        log.info("Recommended Securities Return: %.2f%%" %
                 (recommendation_dataframe['actual_return'].mean() * 100))
        log.info("Average Return: %.2f%%" %
                 (raw_dataframe['actual_return'].mean() * 100))
        log.info("")
        log.info("Analysis Period - %s, Actual Returns as of: %s" %
                 (self.analysis_period, self.current_price_date))

        # Using the logger will mess up the header of this table
        print(raw_dataframe[[
            'analysis_period', 'ticker', 'dispersion_stdev_pct',
            'analyst_expected_return', 'actual_return', 'decile'
        ]].to_string(index=False))
    def display_results(self):
        '''
            Display the final recommendation and the intermediate results of the strategy
        '''

        log.info("Displaying results of MACD strategy")
        log.info("Analysis Date: %s" % self.analysis_date.strftime("%Y-%m-%d"))
        log.info("Divergence Tolerance Factor: %f, MACD Parameters: (%d, %d, %d)" % (
            self.divergence_factor_threshold, self.macd_fast_period, self.macd_slow_period, self.macd_signal_period))
        print(self.raw_dataframe.to_string(index=False))
        log.info(util.format_dict(self.recommendation_set.model))
    def save_to_s3(self, app_ns: str):
        '''
            Uploads the model to S3

            Parameters
            ----------
            app_ns : str
                The application namespace supplied to the command line
                used to identify the appropriate CloudFormation exports
        '''

        self.validate_model()

        s3_data_bucket_name = aws_service_wrapper.cf_read_export_value(
            constants.s3_data_bucket_export_name(app_ns))
        object_name = "%s/%s" % (self.model_s3_folder_prefix,
                                 self.model_s3_object_name)

        log.info("Uploading %s to S3: s3://%s/%s" %
                 (self.model_name, s3_data_bucket_name, object_name))
        aws_service_wrapper.s3_upload_ascii_string(
            util.format_dict(self.model), s3_data_bucket_name, object_name)
Esempio n. 5
0
def display_calculation_dataframe(month: int, year: int, strategy: object,
                                  current_price_date: datetime):
    '''
        Displays the results of the calculation using a Pandas dataframe,
        using the supplied PriceDispersionStrategy object.
        Speficially display the underlining stock rankings that lead to the
        current recommendation
    '''

    recommendation_set = strategy.recommendation_set
    recommendation_dataframe = strategy.recommendation_dataframe
    raw_dataframe = strategy.raw_dataframe

    log.info("Calculating Current Returns")
    raw_dataframe = calculator.mark_to_market(strategy.raw_dataframe,
                                              current_price_date)
    recommendation_dataframe = calculator.mark_to_market(
        strategy.recommendation_dataframe, current_price_date)

    log.info("")
    log.info("Recommended Securities")
    log.info(util.format_dict(recommendation_set.to_dict()))
    log.info("")

    log.info("Recommended Securities Return: %.2f%%" %
             (recommendation_dataframe['actual_return'].mean() * 100))
    log.info("Average Return: %.2f%%" %
             (raw_dataframe['actual_return'].mean() * 100))
    log.info("")
    log.info("Analysis Period - %d/%d, Actual Returns as of: %s" %
             (month, year, datetime.strftime(current_price_date, '%Y/%m/%d')))

    # Using the logger will mess up the header of this table
    print(raw_dataframe[[
        'analysis_period', 'ticker', 'dispersion_stdev_pct',
        'analyst_expected_return', 'actual_return', 'decile'
    ]].to_string(index=False))
Esempio n. 6
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)