Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Newbie needs some help, loops and arrays

Hey everyone Im new to Python and Quantopian, though not to trading .

I need to compare a number of items and Im not sure how to go about doing it in Python.

1) see if the current day mavg(10) <= yesterdays mavg(10). I know the mavg(10) gives me the 10 day moving average but Im not sure how to put them inside the program. I tried 10_day = data[context.security].mavg(10), and then calling _10day [0] <= _10_day[1]. That returned an error

2) I need to also compare the last 10 days and log the up and down days, store the down days and then store the highest down day volume value as a variable, then compare todays volume to that bar and see if its higher. I havent tried to script this as of yet however I am aware that I need to loop through the days?

That should be a great start for me and give me some ideas on how to move forward. Any help would be appreciated. Thanks!

6 responses

Look at this code, should be helpful. Its a 5min quick example, it doesnt execute any orders. It does some of these stuff you want, but add no order logic based on them.

def initialize(context):  
    # A stock  
    context.stock = symbol('GOOG_L')  
    # A history list.  
    # Note: To limit this to say just the last 10, use dequeue with a size! Rest is automatic.  
    context.mavg_history = []  
    # Just a cache of the data from yesteryday.  
    context.yesterday = None

# Will be called on every trade event for the securities you specify.  
def handle_data(context, data):  
    # Update yesterday market. Fine in both minute, live and daily.  
    context.yesterday = data  
    today = data[context.stock].mavg(10)  
    upDays = []  
    downDays = []  
    for mavg in context.mavg_history[:10]: # For limit to 10.  
        # mavg is the day. Logic here for looping.  
        if today < mavg:  
            # Store day in downDays.  
            downDays.append(mavg)  
        else:  
            # Store day in upDays  
            upDays.append(mavg)  
    # Use context.mavg_history[-1] to get yesterdays mavg(10), -2 for two days etc.  
    """  
    try:  
        yesterday = context.mavg_history[-1]  
    except:  
        yesterday = None # No data.  
    """  
# Store yesterdays history.  
def before_trading_start(context):  
    # We need a yesterday open market before we start tracking.  
    if not context.yesterday:  
        return  
    mavg = context.yesterday[context.stock].mavg(10)  
    # Add to the list.  
    context.mavg_history.append(mavg)  

Randy,
In regards to your first question, when putting something into python (a variable, list, dataframe, whatever), the name cannot start with a number. So python won't accept 10_mavg=data[context.security].mavg(10). mavg_10=data[context.security].mavg(10) ought to work though.
Also, when you use the data[context.security].mavg(10) function, all it does is find the average of the past nine days prices and the current price. So it only holds one value at a time, not a list of values like the history() function.
To get yesterday’s 10 day moving average, I would use

price_hist = history(11, '1d', 'price')  
yesterdays_mavg_10 = price_hist[context.security][:-1].mean()  

I’m more than willing to explain why this works if you like. Knowing how to properly use the history function is crucial. Until then, good luck!

Calvin

Calivin Hobbes, I am aware of the exception with starting with numbers I have an underscore before the 10. Its not ideal and Im sure I'll change it in the future.

Thanks to both of you in getting back to me so fast! I am excited to get going and will check out your info!

@CALIVIN HOBBES

Thank you that worked!

From what I can gather, your took the last 11 day (closing) price and .mean them together, why was it 11? to remove today from the average?

But I do need to know how to use historical data, anything you could share would be appreciated. I really would like to do a day count and rank days. on daily volume OHLC parameters.

He used 11 because history() with '1d' frequency returns the last X-1 bars plus the current minute price. So history(11, '1d', 'price') will return the last 10 days price data plus the last minute's price. He then removed the last minute datapoint by indexing into the dataframe using "[:-1]" and took the mean() to get the average of the values.

Here's more documentation on the function: https://www.quantopian.com/help#ide-history
And a concrete example: https://www.quantopian.com/help#sample-history

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.

Randy,
This will be a good start. If you're not sure what something does, print it. I drafted this up kinda quick so if you have any questions (or I messed something up) just ask. Have fun