Hi,
I have been working on an algorithm that uses fundamentals to determine what stocks to buy and sell. I am having trouble with the syntax of line 63 in the code below. When I attempt to run a backtest I receive an error regarding invalid syntax on that line. That bit of code worked until I added a stop order. I am fairly new to Python syntax and would appreciate any help. Thanks for all the help.
Thanks,
Nick
Note: I fixed the error that James pointed out.
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
context.limit = 10
schedule_function(rebalance,
date_rule = date_rules.every_day(),
time_rule = time_rules.market_open()
)
def rebalance(context, data):
for stock in context.portfolio.positions:
if stock not in context.fundamentals and stock in data:
order_target(stock, 0)
# Will be called on every trade event for the securities you specify.
def before_trading_start(context):
context.fundamentals = get_fundamentals(
query(
# list what statistics you want to get for all companies (in filter)
fundamentals.valuation_ratios.pb_ratio,
fundamentals.valuation_ratios.pe_ratio,
)
.filter(
# filter out so you only query companies that you want to know about because it will search every company if you don't filter
fundamentals.valuation_ratios.pe_ratio < 14
)
.filter(
fundamentals.valuation_ratios.pb_ratio < 2
)
.order_by(
fundamentals.valuation.market_cap.desc() #orders the stocks in order of market cap starting with largest market cap so that the limit picks the most valuable companies that fit the filters
)
.limit(context.limit)
)
update_universe(context.fundamentals.columns.values)
def handle_data(context, data):
# Implement your algorithm logic here.
# data[sid(X)] holds the trade event data for that security.
# context.portfolio holds the current portfolio state.
# Place orders with the order(SID, amount) method.
# TODO: implement your own logic here.
cash = context.portfolio.cash
current_positions = context.portfolio.positions
for stock in data:
current_positions = context.portfolio.positions[stock].amount
stock_price = data[stock].price
plausible_investment = cash / 10.0
stop_price = stock_price - (stock_price * 0.005
share_amount = int(plausible_investment / stock_price)
try:
if stock_price < plausible_investment:
if current_positions == 0:
if context.fundamentals[stock]['pe_ratio'] < 11:
order(stock, share_amount, style=StopOrder(stop_price))
except Exception as e:
print (str(e))