Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Python help

I have a list of stocks sorted by a "custom_metric" and calculate the percentile rank for each. I want to plot the value of the custom_metric at the 95th percentile each day, can someone point me in the right direction?

# Sort pipeline by custom metric  
    context.custom_metrics = sorted(custom_metrics, key=lambda x: x[1], reverse=True) # sort high to low  
    log.info('Sorted custom metrics...')  
    log.info(context.custom_metrics)  
    # Calculate custom metric percentile  
    context.custom_metric_percent = {}  
    for i, (stock, custom_metric) in enumerate(context.custom_metrics):  
        context.custom_metric_percent[stock] = 1.0-(float(i)/len(context.custom_metrics))  
2 responses

For every backtest there is an AlgorithmResult object created and stored. Recorded variables, transactions, end of day positions, and some other data are stored in this object. The backtest, or AlgorithmResult object, can be referenced from a notebook with the get_backtest method (see https://www.quantopian.com/docs/api-reference/research-api-reference#quantopian.research.get_backtest). Once one has a reference to this object then the recorded_vars attribute can be accessed (check out https://www.quantopian.com/docs/api-reference/research-api-reference#quantopian.research.AlgorithmResult.recorded_vars). This will contain the values of any recorded variables which can then be plotted.

So, the first step is to get the value at the 75th percentile in a variable. The power of pandas to the rescue. Assuming that custom_metrics is a pandas series. Use the quantile method (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.quantile.html). Next 'record' this variable in ones algo code using the record method. Something like this

# First need to calculate the value at 75th percentile  
# Assume 'custom_metrics' is a pandas series  
value_at_75_pct = context.custom_metrics.quantile(.75)

# Then record this value  
record(my_var=value_at_75_pct)


Run the backtest. Copy the backtest ID. Open a notebook. Fetch the AlgorithmResult object using the backtest ID. Like this...

# Put your own backtest ID below  
my_backtest_id = '5d8ba9ba268a4c29d22e265c'  
bt = get_backtest(my_backtest_id)

One can now access any of the backtest attributes. In this case we want recorded_vars . It can then easily be plotted (again with pandas magic) using the plot method.

# The recorded variables can be fetched as a dataframe with the attribute 'recorded_vars'  
# The index will be the date. There is a column for each recorded variable.  
# If the recorded variable is called 'my_var' then the values could be plotted like this  
bt.recorded_vars['my_var'].plot()

That should get you started. Good luck.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thanks much Dan, i appreciate it.