Пример 1. Простейший пример.

Условие покупки/продажи: если текущая цена больше пятидневного скользящего среднего плюс один процент и есть деньги для покупки - покупаем.
Если текущая цена меньше скользящего среднего и у нас есть акции, то продаем все акции.
def initialize(context):
 
    context.security = symbol('AAPL')
 
def handle_data(context, data):
 
    average_price = data[context.security].mavg(5)
    current_price = data[context.security].price
    amount = context.portfolio.positions[symbol('AAPL')].amount
    cash = context.portfolio.cash
    # Need to calculate how many shares we can buy
    number_of_shares_buy = int(cash/current_price)
    number_of_shares_sell = amount    
    if current_price > 1.01*average_price and cash > current_price:
        # Place the buy order (positive means buy, negative means sell)
        order(context.security, +number_of_shares_buy)
        log.info("Buying %s, amount: %d, cash: %d, price: %s" % (context.security.symbol, number_of_shares_buy, cash, current_price))
       
    elif current_price < average_price and amount>0:
        # Sell all of our shares by setting the target position to zero
        order(context.security, -number_of_shares_sell)
        log.info("Selling %s %d" % (context.security.symbol, number_of_shares_sell))
 
    record(stock_sum=amount)