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

Hi,
I'm pretty new to the programming world and was wondering if someone out there could please give me a helping hand. I'm trying to create an algorithm that relies on fundamental data. The issue that I am facing is that I am not sure whether the universe of stocks output by the get_fundamentals function have the data that I am looking for (or whether these are NA). You can see below that after the function I have used " context.fundamentals=context.fundamentals.dropna()" to try and get rid of any N/A's in the data set. Towards the end of the algo I use " print stock, cash, fundamentals.valuation_ratios.pe_ratio" to see what is happening, a sample of the produced log can be seen directly below. Every other stock is different but still indicates $1,000,000 cash remaining (which tells me that this stock has not been bought, despite meeting my criteria?) and UserInstrumentedAttribute (which I assume is the print off of fundamentals.valuation_ratios.pe_ratio). Assuming that the stocks that have been sorted into my universe don't actually have the data I require how do I ensure that I only get stocks in my universe that have these fundamental values?

Thanks in advance!

Log

2015-07-07PRINTEquity(17920 [RNWK])
2015-07-07PRINT
2015-07-07PRINT1000000.0
2015-07-07PRINT
2015-07-07PRINTUserInstrumentedAttribute

Algo

import pandas as pd
import numpy as np

def initialize(context):
set_max_order_count(50)

def before_trading_start(context):

context.fundamentals=get_fundamentals(  
        query(  
            fundamentals.balance_sheet.ordinary_shares_number,  
            fundamentals.valuation_ratios.book_value_per_share,  
            fundamentals.earnings_ratios.equity_per_share_growth,  
            fundamentals.valuation_ratios.pe_ratio,  
            fundamentals.valuation_ratios.pb_ratio,  
            fundamentals.balance_sheet.total_assets,  
            fundamentals.balance_sheet.total_liabilities,  
            fundamentals.earnings_report.normalized_basic_eps  

            # put your query in here by typing "fundamentals."  
        )  
        .filter(  
            fundamentals.valuation_ratios.pe_ratio<18  

            # put your filters here  
        )  
        .filter(  
        fundamentals.valuation_ratios.pb_ratio<2  

        )  
        .order_by(  
            fundamentals.valuation_ratios.pe_ratio.asc()  
            # sort your query  
        )  
        .limit(200)  
    )  
context.fundamentals=context.fundamentals.dropna()  


update_universe(context.fundamentals.columns.values)  

def handle_data(context, data):

    cash = context.portfolio.cash  
    #current_positions = context.portfolio.positions




    for stock in data:  
            current_position = context.portfolio.positions[stock].amount  
            stock_price = data[stock].price  
        #how much of the remaining cash you're willing to invest  
            plausible_investment = cash/50

          #  share_amount = int(plausible_investment/stock_price)  

            try:  
                if stock_price<plausible_investment:  
                    if current_position==0:  
                        #if context.fundamentals[stock]['normalized_basic_eps']>0:  
                            if context.fundamentals[stock]['pe_ratio']<14:  

                                order_target_percent(stock,5, style=MarketOrder())  


                                print stock, cash, fundamentals.valuation_ratios.pe_ratio  



            except Exception as e:  
                print(str(e))  
3 responses

Stephen,

So if you take a look at your code a little closer you'll see that your print statement is pretty deeply nested in if statements, since you are trying to use your print statement for logging/debugging purposes this isn't great placement. Ideally you'd want to print every bar, consequently, the log that you are showing only shows the first few bars as those were the only bars that still had a positive cash balance. Because of this line if stock_price<plausible_investment you will only get the first few bars because your algorithm loses money so fast your plausible_investment goes negative and obviously that will always be less than the stock price so your print statement is never reached.

I placed a couple of print statements in handle_data that weren't nested and they showed a changing cash balance, and a changing number of positions, so your code is executing trades. FYI, the IDE has a builtin debugger that works really well, I'd suggest becoming proficient with that. Here are the docs for the debugger.

Also use caution when calling .dropna() on DataFrames, .dropna() has an optional axis parameter, so make sure that it is dropping from the axis that you intend.

I hope you get it working! If you are still having trouble PM me or reply here.

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.

Stephen,

Often times there will be fundamental metrics that are null for specific companies. This can occur for a variety of reasons. One main one is that not all metrics are reported by the companies themselves.

One way to examine the fundamentals data is to use the debugger, within the IDE: https://www.quantopian.com/posts/new-feature-debugging-in-the-ide

Another way is to try out get_fundamentals() within the research environment where you can examine the data more easily with iPython. There's a tutorial notebook to help walk you through using fundamentals in Research

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 for your responses, have tried using the iPython and it helps out a lot. Still struggling with the debugger though.