Back to Community
Problem with coding how much to order based on plausable investment

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))  
4 responses

You are missing a closing right parentheses for you order statement, no big deal, it should look like this...

order(security, amount, style=StopOrder(price))  
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, James. But I am still getting the same error on line 63.

There was another missing paren. This runs:

Clone Algorithm
3
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
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
# 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)) 
There was a runtime error.
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... that fixed it.