Is this the correct way of creating a new variable that relies on fundamental data from "before_trading_start"? I keep getting an error when running the code on the payout_ratio line... I have tried breaking the line and using the debugger but don't get any return on: "payout_ratio". When I remove the break I get the runtime error: "KeyError: , {}), orders={}, new_orders=[], current_dt=2011-01-04 00:00:00+00:00), recorded_vars={'cash': 1000000.0, 'asset': 1000000.0})>
There was a runtime error on line 59."
def before_trading_start(context):
"""
Called before the start of each trading day.
It updates our universe with the
securities and values found from fetch_fundamentals.
"""
#Number of stocks to be stored in our universe
#num_stocks = 30
#simplify by using f for fundamentals
fundamental_df = get_fundamentals(
query(
# put your query in here by typing "fundamentals."
fundamentals.operation_ratios.revenue_growth,
fundamentals.asset_classification.morningstar_sector_code,
fundamentals.balance_sheet.ordinary_shares_number,
fundamentals.valuation_ratios.book_value_per_share,
fundamentals.valuation_ratios.earning_yield,
fundamentals.balance_sheet.total_assets,
fundamentals.balance_sheet.total_liabilities,
fundamentals.earnings_report.dividend_per_share,
fundamentals.earnings_report.basic_eps,
fundamentals.asset_classification.profitability_grade,
)
.filter(fundamentals.valuation.market_cap > 0)
.filter(fundamentals.earnings_report.dividend_per_share > 0)
.filter(fundamentals.earnings_report.basic_eps > 0)
.filter(fundamentals.valuation_ratios.book_value_per_share > 0)
.filter(fundamentals.valuation_ratios.earning_yield > 0)
.filter(fundamentals.valuation.shares_outstanding != None)
.order_by(fundamentals.asset_classification.profitability_grade.asc())
.limit(30),
)
# Filter out only stocks that fits in criteria
context.stocks = [stock for stock in fundamental_df]
# Update context.fundamental_df with the securities that we need
context.fundamental_df = fundamental_df[context.stocks]
update_universe(context.fundamental_df.columns.values)
record (cash = context.portfolio.cash, asset = context.portfolio.portfolio_value)
def handle_data(context,data):
payout_ratio = (context.fundamental_df['dividend_per_share'])/(context.fundamental_df['basic_eps'])
book_value = context.fundamental_df['book_value_per_share']
ROE = context.fundamental_df['earning_yield']