| Author | 
              Topic: Quantopian -- The basics  |  
           
         |  
        
          
            
              
                
                	
                  
                    
                      WebSpider member offline     |  
                    
                      |   |  
                    
                      
                        
                          
                            | posts: | 
                            147 |  
                          
                            | joined: | 
                            06/29/2006 |  
                          
                            | from: | 
                            Seattle, WA |  
                         
                       |  
                    | 
                  | 
                
                  
                    
                       |  
                    
                       |  
                    
                      
                        
                          | Quantopian -- The basics |  
                        
                          The Algorithm Bare Bone:
 
 
# Import Algorithm API
import quantopian.algorithm as algo
def initialize(context):
    # Initialize algorithm parameters
    context.minute_count = 0
    context.day_count = 0
    context.minutely_message = "Minute {}."
    context.daily_message = "Day {}."
    context.weekly_message = "Time to place some trades!"
    # Schedule rebalance function
    algo.schedule_function(
        rebalance,
        date_rule=algo.date_rules.week_start(),
        time_rule=algo.time_rules.market_open()
    )
def handle_data(context, data):
    context.minute_count += 1
    if context.minute_count%60 == 0:
        log.info(context.minutely_message, context.minute_count)
    
def before_trading_start(context, data):
    # Execute any daily actions that need to happen
    # before the start of a trading session
    context.day_count += 1
    log.info(context.daily_message, context.day_count)
def rebalance(context, data):
    # Execute rebalance logic
    log.info(context.weekly_message)    
  The output:
 
2019-01-02 05:45 before_trading_start:29 INFO Day 1.
2019-01-02 07:30 handle_data:23 INFO Minute 60.
2019-01-02 08:30 handle_data:23 INFO Minute 120.
2019-01-02 09:30 handle_data:23 INFO Minute 180.
2019-01-02 10:30 handle_data:23 INFO Minute 240.
2019-01-02 11:30 handle_data:23 INFO Minute 300.
2019-01-02 12:30 handle_data:23 INFO Minute 360.
2019-01-03 05:45 before_trading_start:29 INFO Day 2.
2019-01-03 07:00 handle_data:23 INFO Minute 420.
2019-01-03 08:00 handle_data:23 INFO Minute 480.
2019-01-03 09:00 handle_data:23 INFO Minute 540.
2019-01-03 10:00 handle_data:23 INFO Minute 600.
2019-01-03 11:00 handle_data:23 INFO Minute 660.
2019-01-03 12:00 handle_data:23 INFO Minute 720.
2019-01-03 13:00 handle_data:23 INFO Minute 780.
2019-01-04 05:45 before_trading_start:29 INFO Day 3.
2019-01-04 07:30 handle_data:23 INFO Minute 840.
2019-01-04 08:30 handle_data:23 INFO Minute 900.
2019-01-04 09:30 handle_data:23 INFO Minute 960.
2019-01-04 10:30 handle_data:23 INFO Minute 1020.
2019-01-04 11:30 handle_data:23 INFO Minute 1080.
2019-01-04 12:30 handle_data:23 INFO Minute 1140.
2019-01-07 05:45 before_trading_start:29 INFO Day 4.
2019-01-07 06:31 rebalance:34 INFO Time to place some trades!
2019-01-07 07:00 handle_data:23 INFO Minute 1200.
2019-01-07 08:00 handle_data:23 INFO Minute 1260.
2019-01-07 09:00 handle_data:23 INFO Minute 1320.
2019-01-07 10:00 handle_data:23 INFO Minute 1380.
2019-01-07 11:00 handle_data:23 INFO Minute 1440.
2019-01-07 12:00 handle_data:23 INFO Minute 1500.
2019-01-07 13:00 handle_data:23 INFO Minute 1560.
2019-01-08 05:45 before_trading_start:29 INFO Day 5.
2019-01-08 07:30 handle_data:23 INFO Minute 1620.
2019-01-08 08:30 handle_data:23 INFO Minute 1680.
2019-01-08 09:30 handle_data:23 INFO Minute 1740.
2019-01-08 10:30 handle_data:23 INFO Minute 1800.
2019-01-08 11:30 handle_data:23 INFO Minute 1860.
2019-01-08 12:30 handle_data:23 INFO Minute 1920.
2019-01-09 05:45 before_trading_start:29 INFO Day 6.
2019-01-09 07:00 handle_data:23 INFO Minute 1980.
2019-01-09 08:00 handle_data:23 INFO Minute 2040.
2019-01-09 09:00 handle_data:23 INFO Minute 2100.
2019-01-09 10:00 handle_data:23 INFO Minute 2160.
2019-01-09 11:00 handle_data:23 INFO Minute 2220.
2019-01-09 12:00 handle_data:23 INFO Minute 2280.
2019-01-09 13:00 handle_data:23 INFO Minute 2340.
2019-01-10 05:45 before_trading_start:29 INFO Day 7.
2019-01-10 07:30 handle_data:23 INFO Minute 2400.
2019-01-10 08:30 handle_data:23 INFO Minute 2460.
2019-01-10 09:30 handle_data:23 INFO Minute 2520.
2019-01-10 10:30 handle_data:23 INFO Minute 2580.
2019-01-10 11:30 handle_data:23 INFO Minute 2640.
2019-01-10 12:30 handle_data:23 INFO Minute 2700.
2019-01-11 05:45 before_trading_start:29 INFO Day 8.
2019-01-11 07:00 handle_data:23 INFO Minute 2760.
2019-01-11 08:00 handle_data:23 INFO Minute 2820.
2019-01-11 09:00 handle_data:23 INFO Minute 2880.
2019-01-11 10:00 handle_data:23 INFO Minute 2940.
2019-01-11 11:00 handle_data:23 INFO Minute 3000.
2019-01-11 12:00 handle_data:23 INFO Minute 3060.
2019-01-11 13:00 handle_data:23 INFO Minute 3120.
2019-01-14 05:45 before_trading_start:29 INFO Day 9.
2019-01-14 06:31 rebalance:34 INFO Time to place some trades!
 
  What's going on here?  Function handle_data(context, data) (-- optional) has been triggered by system every minute;  Function before_trading_start(context, data) has been triggered by system (45 minutes) before trading start;  Function rebalance(context, data) has been triggered by Scheduler by its own specific rules.
 
  |  
                        
                           |  
                        |  
                    
                       |  
                    
                       |  
                    |  
                |  
        
          
            
              
                
                	
                  
                    
                      WebSpider member offline     |  
                    
                      |   |  
                    
                      
                        
                          
                            | posts: | 
                            147 |  
                          
                            | joined: | 
                            06/29/2006 |  
                          
                            | from: | 
                            Seattle, WA |  
                         
                       |  
                    | 
                  | 
                
                  
                    
                       |  
                    
                       |  
                    
                      
                        
                          | The Basic Objects and Functions |  
                        
                           Object context: 
  context is a Python dictionary used for maintaining state by attaching any property:
 
    context.some_property = some_value
  
   Object assets:    assets is a Asset or a list of Assets which represents security.
   Find security asset by name: 
 
      assets = symbol('AAPL')
      assets = [symbol('AAPL'), symbol('MSFT')]
      assets = symbols('AAPL', 'MSFT')
   Find security asset by id: 
 
      # AAPL
      assets = sid(24)  
      # AAPL, MSFT, and SPY
      assets = [sid(24), sid(5061), sid(8554)]  
 
  |  
                        
                           |  
                        |  
                    
                       |  
                    
                       |  
                    |  
                |  
        
          
            
              
                
                	
                  
                    
                      WebSpider member offline     |  
                    
                      |   |  
                    
                      
                        
                          
                            | posts: | 
                            147 |  
                          
                            | joined: | 
                            06/29/2006 |  
                          
                            | from: | 
                            Seattle, WA |  
                         
                       |  
                    | 
                  | 
                
                  
                    
                       |  
                    
                       |  
                    
                      
                        
                          | Object Data |  
                        
                          data.current(assets, fields)
  This method returns the current value of the given assets for the given fields at the current algorithm time.
  Parameter fields:  'price' -- returns the last known close price, NaN if not founded  'last_traded' -- returns the date of the last trade event  'open' -- return the relevant information for the current trade bar  'high' -- return the relevant information for the current trade bar  'low' -- return the relevant information for the current trade bar  'close' -- return the relevant information for the current trade bar  'volume' -- returns the trade volume, 0 if there is no trade this minute  'contract' --  returns the current active contract
  Example:
 
        price = data.current(symbol('AAPL'), 'price');
 
  data.history(assets, fields, bar_count, frequency) This method returns a window of data for the given assets and fields.
  Parameter fields:  'price' -- returns the last known close price, NaN if not founded  'open' -- return the relevant information for the current trade bar  'high' -- return the relevant information for the current trade bar  'low' -- return the relevant information for the current trade bar  'close' -- return the relevant information for the current trade bar  'volume' -- returns the trade volume, 0 if there is no trade this minute
  Parameter frequency:   '1m' -- for minutely data   '1d' --  for daily data
  Examples (DAILY):
 
    # returns the current price
    price_history = data.history(assets, "price", 1, "1d"); 
    # returns yesterday's close price and the current price
    price_history = data.history(assets, "price", 2, "1d");
    # returns the prices for the previous 5 days and the current price
    price_history = data.history(assets, "price", 6, "1d");
    # returns the volume since the current day's open, even if it is partial
    price_history = data.history(assets, "volume", 1, "1d"); 
  Examples (MINUTELY):
 
    # returns the current price
    price_history = data.history(assets, "price", 1, "1m"); 
    # returns the previous minute's close price and the current price
    price_history = data.history(assets, "price", 2, "1m"); 
    # returns the prices for the previous 5 minutes and the current price
    price_history = data.history(assets, "price", 6, "1m");
    # returns the volume for the previous 60 minutes
    price = data.history(assets, "volume", 60, "1m");
  Example -- Up or down compared to previouse day's close price?
 
def initialize(context):
    # AAPL, MSFT, and SPY
    context.securities = [sid(24), sid(5061), sid(8554)]
def handle_data(context, data):
    price_history = data.history(context.securities, fields="price", bar_count=2, frequency="1d")
    for s in context.securities:
        prev_close = price_history[s][-2];
        curr_price = price_history[s][-1];
        if curr_price > prev_close:
            print(s, prev_close, curr_price, ' --> UP');
        else:
            print(s, prev_close, curr_price, ' --> DOWN');
  Example -- VWAP (Volume Weighted Average Price)
 
def initialize(context):
    # AAPL, MSFT, and SPY
    context.securities = [sid(24), sid(5061), sid(8554)]
def vwap(prices, volumes):
    return (prices * volumes).sum() / volumes.sum()
def handle_data(context, data):
    hist = data.history(context.securities, fields=["price", "volume"], bar_count=30, frequency="1d")
    vwap_10 = vwap(hist["price"][-10:], hist["volume"][-10:])
    vwap_30 = vwap(hist["price"], hist["volume"])
    for s in context.securities:
        if vwap_10[s] > vwap_30[s] :
            order(s, 100)
        elif vwap_10[s] < vwap_30[s] :
            order(s, -10)
  Other data's methods:  data.can_trade(assets) -- For the given asset or iterable of assets, returns true if the security has a known last price  data.is_stale(assets) -- For the given asset or iterable of assets, returns true if the asset has ever traded and there is no trade data for the current simulation time |  
                        
                           |  
                        |  
                    
                       |  
                    
                       |  
                    |  
                |  
        
          
            
              
                
                	
                  
                    
                      WebSpider member offline     |  
                    
                      |   |  
                    
                      
                        
                          
                            | posts: | 
                            147 |  
                          
                            | joined: | 
                            06/29/2006 |  
                          
                            | from: | 
                            Seattle, WA |  
                         
                       |  
                    | 
                  | 
                
                  
                    
                       |  
                    
                       |  
                    
                      
                        
                          | Ordering Methods |  
                        
                          order_optimal_portfolio(objective, constraints) This method places one or more orders by calculating a new optimal portfolio based on the objective and constraints. 
  order(asset, amount, style=OrderType) This methods places an order for the specified asset and the specified amount of shares (equities) or contracts (futures). 
  Parameter OrderType:  style=MarketOrder(exchange)  style=StopOrder(stop_price, exchange)  style=LimitOrder(limit_price, exchange)  style=StopLimitOrder(limit_price=price1, stop_price=price2, exchange)
  order_value(asset, amount, style=OrderType) Place an order by desired value rather than desired number of shares or contracts.
  order_percent(asset, amount, style=OrderType) Places an order in the specified asset corresponding to the given percent of the current portfolio value, which is the sum of the positions value and ending cash balance. Placing a negative percent order will result in selling the given percent of the current portfolio value. Orders are always truncated to whole shares or contracts. Percent must be expressed as a decimal (0.50 means 50%).
  Example order_percent(symbol('AAPL'), .5) will order AAPL shares worth 50% of current portfolio value. If AAPL is $100/share and the portfolio value is $2000, this buys 10 shares (discarding slippage and transaction cost).
  order_target(asset, amount, style=OrderType) Places an order to maintain the target number of shares in portfolio. Placing a negative target order will result in a short position equal to the negative number specified.
  Example If the current portfolio has 5 shares of AAPL and the target is 20 shares, order_target(symbol('AAPL'), 20) orders 15 more shares of AAPL.
  order_target_value(asset, amount, style=OrderType) Places an order to adjust a position to a target value. Placing a negative target order will result in a short position equal to the negative target value. 
  Example If the current portfolio holds $500 worth of AAPL and the target is $2000, order_target_value(symbol('AAPL'), 2000) orders $1500 worth of AAPL (rounded down to the nearest share).
  cancel_order(order) Attempts to cancel the specified order.
  Parameters order: Can be the order_id as a string or the order object.
 
  get_open_orders(sid) If asset is None or not specified, returns all open orders. If asset is specified, returns open orders for that asset
  Parameters sid: An Equity object or a Future object. Can also be None.
  Returns If asset is unspecified or None, returns a dictionary keyed by asset ID. The dictionary contains a list of orders for each ID, oldest first. If an asset is specified, returns a list of open orders for that asset, oldest first.
  get_order(order) Returns the specified order. The order object is discarded at the end of handle_data.
  Parameters order: Can be the order_id as a string or the order object.
  Returns An order object that is read/writeable but is discarded at the end of handle_data.
 
  |  
                        
                           |  
                        |  
                    
                       |  
                    
                       |  
                    |  
                |  
      |