Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with the for/if loops and history data used in those....

Hi,

Needs some help to achieve something. Here is a part of code that I did simplify to make sure I get an answer on what I'm looking for. It do not make any logic as for the order criterias but you will get what I want to achieve.

Here I want to make some decision when it is 9h32AM, for a universe of stock, with some conditions to decide if I buy or if I sell. Everything goes great until I try to close my orders. In the ''close my position'' section, my problem is that I want to create a decision using the exact same data ''low_1m'' that I use in the ''order section'' . This data is being created at 9h32 and it is the low of a stock at the first minute candlestick of the day. It seems like when I get out of the first ''for'' loop, and create an other one for the stock in context.portfolio.position, it won't reconize the ''low_1m''. And if I recreate this low_1m using history, it won't use the history of the first two minute of the day....it will use the last two minutes of any moment in the day....

Any help would be appreciated....

def initialize(context):
set_universe(universe.DollarVolumeUniverse(94.0, 99.0))

def handle_data(context, data):

exchange_time = get_datetime().astimezone(pytz.timezone('US/Eastern'))  
close_ = history(2, '1m', 'close_price')  
low_ = history(2, '1m', 'low')  
high_ = history(2, '1m', 'high')  
open_ = history(2, '1m', 'open_price')  
price_ = history(2, '1m', 'price')  
dayprice = history(2, '1d', 'price')  
volume_history = history(10, '1d', 'volume')  
trade_ = 0
Order section ######
if exchange_time.hour == 9 and exchange_time.minute == 32:  

    for stock in data:  
        open_1m = open_[stock][-2]  
        low_1m = low_[stock][-2]  
        high_1m = high_[stock][-2]  
        close_1m = close_[stock][-2]  
        open_2m = open_[stock][-1]  
        close_2m = close_[stock][-1]

        if open_2m < open_1m:  
            order_value(stock, 20000)  
        elif open_2m < high_1m:  
            order_value(stock, -20000)
Close my position section ######
open_orders = get_open_orders()  
elif:  
    for stock in context.portfolio.positions:  
        current_ratioreturn = data[stock].price / cost_  
        amount_ = context.portfolio.positions[stock].amount

        if stock not in open_orders and amount_ > 0 and data[stock].price <= low_1m or current_ratioreturn >= 1.04:  
            order_target(stock, 0)  
        elif stock not in open_orders and amount_ < 0 and data[stock].price >= high_1m or current_ratioreturn <= 0.96:  
3 responses

Hi Pierre-Luc,

I think what you will want to do here is use a global variable by storing low_1m in context. To do this, after setting low_1m = low_[stock][-2], you will want to set context.low_1m = low_1m. Since context.low_1m is global, you should be able to access it from your close position section later.

I hope this helps!

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.

Hi Jamie,

Thanks for taking time to reply. Problem with this is that my first buying loop is executed for a universe of stock at 9h32. When the buying is done, I have an other loop for the selling of the stocks in the context.position. When I do what you told me, the value in the context.low_1m at the end of my loop will be the last stock of the universe that has been analysed in my buying section. So when I do my loop for the selling, no matter what is the stock in context.portfolio.positions, it will use the last value registered in context.low_1m....

There might be something I did not get though....I should record the low_1m in a pandas frame with a column for stock and a column for the low_1m value of this stock. Then I could recall context.low_1m using [stock] to get the value of a stock.

I'm not sure how to do this...i'll take a look. Let me know if you agree that it's the way to do it .. !

Thank you !

Jamie,

Setting a context.low_1m doesn't help me much. this variable is not recalled by its ''stock''. I mean, my loop set up this variable for each stock in data and when I try to use it to close my position, it recalls the context.low_1m of the last stock analysed in the loop. Is there a way to create a Panda dataframe of this variable so I can recall the value of context.low_1m[stock] for the stock of my opened position instead of recalling the last stock analysed?

It might not be explained in a proper english, I hope you get what I mean and can help me out a bit....