Back to Community
How to order one stock from a list of stocks?

I have list of stock and then am going through each stock and check if short term moving average is bigger then long term moving average. I then want to purchase one stock that fits my criteria using

order_target_percent(stock, .50)

using 50% of capitol to that position. Am trying to then sell that stock once the longer moving average is bigger then the smaller moving average for the stock I purchased. Am having issues with how my code over buys and doesn't seem to keep track of what positions am holding. How do i go about fixing this? What am i doing wrong?

Clone Algorithm
10
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.
import talib
def initialize(context):
    set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))
    set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025,                       price_impact=0.10))
    
    set_symbol_lookup_date('2014,12,22')
    context.stocks = symbols('IBM','BAC','XOM','CVX','GOOG','PG','MMM','JNJ',
                            'MCD','WMT','UTX','KO','BA','CAT','JPM','HPQ','VZ',
                            'T','DD','MRK','DIS','HD','MSFT','AXP','BAC','PFE',
                            'GE','INTC','C','GM')
    
    

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    # Implement your algorithm logic here.
    for stock in context.stocks:
        price = data[stock].price
        current_position = context.portfolio.positions[stock].amount
        ma_long = data[stock].mavg(25)
        ma_short = data[stock].mavg(10)
        
    
        if len(get_open_orders()) == 0:
            if (current_position == 0) and (ma_short > ma_long):
                order_target_percent(stock, .50)
                log.info("Buying %s at Price: %s" %(stock.symbol, price))  
            elif (current_position != 0) and (price > context.portfolio.positions[stock].cost_basis):
                order_target_percent(stock, 0)
                log.info("Selling %s at Price: %s" %(stock.symbol,price))
                
                
    record(Cash=context.portfolio.cash, POS=current_position, Price = price, MAlong=ma_long, MAshort=ma_short) 

   
    
There was a runtime error.
3 responses

Hi Hassan,

It looks like the over ordering issue is stemming from the fact that current_position is being set to the amount of shares you hold for the stock you are currently looking at, as opposed to whether you are holding any positions at all. I would suggest you check something like len(context.portfolio.positions) to check whether or not you are holding any positions!

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.

You are selling on the first bar that you have a profit:

elif (current_position != 0) and (price > context.portfolio.positions[stock].cost_basis):

sounds like you want

elif(ma_long > ma_short): ...

It sounds like you need to track how many open positions you have. If you order 50% of the account 4 times you have invested 200% of the account. I added a maximum position count constraint to your algo. The issue you will have is that you end up ignoring signals when you already have the maximum open positions.

Clone Algorithm
8
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.
import talib
def initialize(context):
    set_commission(commission.PerShare(cost=0.0075, min_trade_cost=1.00))
    set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025,                       price_impact=0.10))
    
    set_symbol_lookup_date('2014,12,22')
    context.stocks = symbols('IBM','BAC','XOM','CVX','GOOG','PG','MMM','JNJ',
                            'MCD','WMT','UTX','KO','BA','CAT','JPM','HPQ','VZ',
                            'T','DD','MRK','DIS','HD','MSFT','AXP','BAC','PFE',
                            'GE','INTC','C','GM')
    
    context.max_positions = 4
    
    

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    # Implement your algorithm logic here.
    open_positions = {k: v for k, v in context.portfolio.positions.iteritems()
                      if v.amount != 0}
    # print context.portfolio.positions[symbol('SPY')].amount
    for stock in context.stocks:
        price = data[stock].price
        current_position = context.portfolio.positions[stock].amount
        ma_long = data[stock].mavg(25)
        ma_short = data[stock].mavg(10)
        
    
        if len(get_open_orders()) == 0:
            if (current_position == 0) and (ma_short > ma_long) and (len(open_positions) < context.max_positions):
                order_target_percent(stock, .50)
                log.info("Buying %s at Price: %s" %(stock.symbol, price))  
            elif (current_position != 0) and (price > context.portfolio.positions[stock].cost_basis):
                order_target_percent(stock, 0)
                log.info("Selling %s at Price: %s" %(stock.symbol,price))
                
                
    record(Cash=context.portfolio.cash,
           position_count=len(open_positions)) 

   
    
There was a runtime error.