Back to Community
First attempt at fundamental algo. Having some problems.

I am having problems getting the following fundamental algo to run. Does someone mind helping me?

import pandas as pd
import numpy as np

def initialize(context):
context.stocks = []

def before_trading_start(context, data):
fundamental_df = get_fundamentals(

    .filter(fundamentals.asset_classification.morningstar_industry_group_code == 10428)  
    .filter(fundamentals.company_reference.country_id == "USA")  
    .filter(fundamentals.balance_sheet.ordinary_shares_number > 0)  


context.stocks = []  
for stock in fundamental_df:  
    OR = fundamental_df[stock]['operating_revenue'] or 0  
    CR = fundamental_df[stock]['cost_of_revenue'] or 0  
    SE = fundamental_df[stock]['stockholders_equity'] or 0  
    PSOSE = fundamental_df[stock]['preferred_securities_outside_stock_equity'] or 0  
    PSE = fundamental_df[stock]['preferred_stock_equity'] or 0  
    OSN = fundamental_df[stock]['ordinary_shares_number'] or 0  

    cashFlow = (OR - CR)*4  
    NAV = cashFlow + SE - PSOSE - PSE  
    intrinsicValue = NAV/float(OSN)  
    last = data[stock][symbol].price  

    if last <= .8*intrinsicValue:  

context.fundamental_df = fundamental_df[context.stocks]  

def handle_data(context, data):

if len(context.stocks) == 0:  
    weight = 0  
    weight = 1.0/len(context.stocks)  

for stock in context.portfolio.positions:  
    order_target_percent(stock, 0)  

for stock in context.stock:  
    if weight != 0:  
        order_target_percent(stock, weight)  
1 response

You're on the right track! On line 44, this is the proper syntax to query for the current stock price:

last = data[stock].price  

The KeyError you're seeing in the fundamental query is because you're requesting a stock price in a bar the stock didn't trade. Hence, there's no price to return. Since every stock doesn't trade every minute, you need to add a guard:

 for stock in fundamental_df:  
        if stock in data:  
          last = data[stock].price  

I made these minor adjustments and now the code compiles.

Clone Algorithm
Backtest from to with initial capital
Total Returns
Max Drawdown
Benchmark Returns
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 56844a348b1bd711c82153fc
There was a runtime error.

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.