Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
New to Quantopian and Python - What does the main() function look like?

Hello all,

I am new to quantopian and python. However, I do have 1 semester experience in java.

I was curious what the execution algorithm looks like as I am having a hard time understanding the two main functions,
initialize and handle_data.

And I am assuming 'context' is a class, but I wasn't able to find the documentation behind it.

I am still new to python and have been using codeacademy, so you'll have to forgive me if these are silly questions.

A problem I think I am having is that identifying function parameters is not as easy seeing that you don't have to define the type of variables prior to declaring them.

5 responses

1) context is where you initialize variables and stocks you are interested in trading.... You can declare other properties such as commission and slippage..

2) handle_data is where do actual trading since it is called every minute or day depending on how you decide to backtest

you can download zipline and take a look at it ... I have not looked at it carefully.... But, you can still use quantopian without knowing zipline in full details...

https://github.com/quantopian/zipline

context allows you to pass your the state of your variables between functions. Otherwise, the variable is only available within the function it's created and cannot be accessed by other functions in your code.

For example this simple code will order 1 share of Apple stock when the price dips below $70. Handle_data knows about the stock because it was passed in as a context variable.

def initialize(context):  
  context.stock = sid(24)

def handle_data(context,data):  
   price = data[context.stock].price  
   if price < 70:  
      order(context.stock, 1)  

However, if you were to remove 'context', then the stock is not passed to handle_data and your variable is undefined - throwing an error

def initialize(context):  
 stock = sid(24)

def handle_data(context, data):  
   price = data[stock].price  
   if price < 70:  
      order(stock, 1)  

Here's a tip, if you don't want to type out "context.stock" each time, then you can do something like:

def initialize(context):  
  context.stock = sid(24)

def handle_data(context,data):  
   stock = context.stock  

Initialize() is called only once in the algorithm. In backtesting in the first bar (first minute or day) and in live trading it's called upon first deploy. This is where you setup your variables and create your universe of stocks.

Handle_data is where the algorithm magic happens. It is called every bar and holds your ordering logic to drive your strategy.

If you have any follow-up questions, ask away!

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.

If you are coming from Java land, you might have a better time if you think of your algorithm as an applet. The reason that there is no 'main' function like your 'public static void main(String argv[])' is that you are not exposed to the program's entry point. Your algorithm is not a standalone entity; instead, it is being entered from a larger runtime.

In java applets you have your 'public void init()' method that is almost exactly like the Quantopian 'initialize' function. The only difference is that with applets, you are expected to store any innitial state on the applet object like, 'this.memberVar = 10' where in the Quantopian version, you are expected to store the state on 'context' like 'context.member_var = 10'.

As Alisa explained, after you have setup your state with 'initialize', 'handle_data' is called once per bar of data.

'context' is a modified dictionary object that allows you to use attribute access to index into it. For example:

context.attribute  
context['attribute']  

are the same and can be exchanged anywhere in the algorithm.

About the parameters issue you described, python attribute lookups happen at runtime. For this reason, you may think of everything almost like a Java interface. For example, take the function:

def describe_length(a):  
    length = len(a)  
    if not length:  
        return 'Empty'  
   if length < 5:  
        return 'Short'  
    return 'Long'  

Does it really matter what type 'a' is? As long as it implements a '__len__' method., we know that we can call 'len' on it and it works. To transition from Java to Python, you need to not think about the 'type' of things so rigidly, and start thinking about the behavior of things.

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.

Thank you all for the help. Here is a simple buy low sell high algo for BAC

def initialize(context):  
    context.security = sid(700)  
def handle_data(context, data):  
    stock = context.security  
    price = data[stock].price  
    cash = context.portfolio.cash  
    buy_price = data[stock].mavg(5)*.95  
    sell_price = data[stock].mavg(5)*1.1  
    if price <= buy_price and cash >= price:  
           shares = int(cash/price)  
           order(stock, shares)  
    elif price >= sell_price:  
           order_target(stock,0)  

A problem I see after running the backtest is I don't have a mechanism to sell stock if the price drops below a certain threshold. I only have one to sell if the price goes above a certain price threshold.
Is it possible to carry individual minute data forward? For example, I buy BAC at $10 on day X. On day X+2, can I say sell BAC if price drops below the close price on day X?

You can track your fill price using the get_order object.

Here's an example that buys 100 shares of BAC and sells when the market price is below the fill price.