Back to Community
Need comment on my algo structure

I am new to Python and Quantopian. Only have few months experience.

Here, I put up my algo, hidden some important strategy and would need some comment on the code structure.
The algo is to scan penny stock worth to buy after market open. Since the volume of penny stock is low, I call the buy function every 30 minutes to update the buying limit price and that increases the buying chance, otherwise I may need to use market order that may be dangerous.

When the market is about to close, I will scan is there any bar/chart pattern and put them into sell list.
The sell function will keeps selling them til zero.

I know my code is naive, so I would be appreciated if someone could have a comment on the code structure, or is there something missing.

Clone Algorithm
2
Loading...
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.data.quandl import cboe_vix as vix
from quantopian.pipeline import CustomFactor
import talib
import math

MAX_LEVERAGE = 1
MIN_PCTX_DIF = 0.01
MIN_PRICE = 1      
MAX_PRICE = 5       
STOCK_PCTX = 0.2
MIN_VIX = 20     
BUYFACTOR = 1.00
SELLFACTOR = 1.00

def initialize(context):
    
    set_long_only()
    set_slippage(slippage.VolumeShareSlippage(volume_limit=1, price_impact=0.0))
    schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open())
    schedule_function(close_positions, date_rules.every_day(), time_rules.market_close())
    for minutez in range(1,390,30):
        schedule_function(Buy_Sell, date_rules.every_day(), time_rules.market_open(minutes=minutez))
    set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.00))
    attach_pipeline(make_pipeline(), 'my_pipeline')
    context.sl = {}
    context.vl = MIN_VIX
    context.win = 0
    context.loss = 0
    context.pctx = 0
    context.count = 0
    context.sell_list = {}
    
def make_pipeline():
    pipe = Pipeline() 
    pipe.add(GetVIX(inputs=[vix.vix_close]), 'VixClose')
    depositary_screen = ~morningstar.share_class_reference.is_depositary_receipt.latest
    otc_screen = ~morningstar.share_class_reference.exchange_id.latest.startswith('OTC')
    price_screen = (USEquityPricing.close.latest >= MIN_PRICE and USEquityPricing.close.latest <= MAX_PRICE)
    volume_screen = (USEquityPricing.volume.latest > 100000)
    pipe.set_screen(price_screen & volume_screen & depositary_screen & otc_screen)
    return pipe

def before_trading_start(context, data):
    context.output = pipeline_output('my_pipeline')
    context.vix = context.output["VixClose"].iloc[0]
    context.security_list = context.output.index
    context.security_listF = {}
    context.shares = {}

def my_rebalance(context,data):
    ma8 = data.history(context.security_list,'price',8,'1d').mean()
    ma20 = data.history(context.security_list,'price',20,'1d').mean()
    ma50 = data.history(context.security_list,'price',50,'1d').mean()
    ma100 = data.history(context.security_list,'price',100,'1d').mean()
    cl = data.history(context.security_list,'price',2,'1d')
    op = data.history(context.security_list,'open',2,'1d')

    for s in context.security_list:
     if s not in context.portfolio.positions:
       if context.vix <= context.vl:
        if cl[s][-2] > op[s][-2] * 1.05:
          if ma8[s] > ma20[s] and ma50[s] > ma100[s]:
                print s.symbol
                context.security_listF[s] = s
               
    MAX_LEVERAGE = calc_leverage(context.portfolio.cash)
    context.pctx = diversify(context,data,context.security_listF,MAX_LEVERAGE)       
    if context.pctx == 0:
        return
    
    for s in context.security_listF:
        cp = float(data.current(s,'price'))
        context.shares[s] = context.portfolio.portfolio_value * context.pctx /cp
    
def Buy_Sell(context,data):
    
    for s in list(context.security_listF):
        if s in context.sell_list:
            del context.security_listF[s]
        
        elif s not in context.sell_list:
            StockShares = context.portfolio.positions[s].amount
            if StockShares < context.shares[s]:
                cancel_open_buy_orders(context, data, s)
                cp = float(data.current(s,'price'))
                #if context.portfolio.cash * MAX_LEVERAGE > 0:
                if data.can_trade(s):
                    BuyPrice=float(make_div_by_05(cp, buy=True))
                    order_target(s,context.shares[s],style=LimitOrder(BuyPrice))  
    
    for s in list(context.sell_list):
        cp = float(data.current(s,'price'))
        cb = context.portfolio.positions[s].cost_basis
        StockShares = context.portfolio.positions[s].amount
        if s not in context.portfolio.positions:
            del context.sell_list[s]
        
        elif s in context.portfolio.positions:
            if data.can_trade(s):
              if StockShares > 0:
                cancel_open_sell_orders(context, data, s)
                SellPrice = float(make_div_by_05(cp*SELLFACTOR, buy=False))
                order_target(s,0,style=LimitOrder(SellPrice))
                if cp > cb:
                    context.win = context.win + 1
                if cp < cb:
                    context.loss = context.loss + 1
                loss = cp/cb                    
                print s.symbol + str(loss)

def handle_data(context,data):
    pass
                
def close_positions(context, data):
     context.stock = len(context.portfolio.positions)
     record(Leverage = context.account.leverage)
     record(Losses = context.loss)
     record(Gains = context.win)
     record(stock = context.stock)
    
     for s in context.portfolio.positions:
       if s not in get_open_orders() and data.can_trade(s):
            ma8 = data.history(s,'price',8,'1d').mean()
            ma20 = data.history(s,'price',8,'1d').mean()
            if ma8 < ma20:
                context.sell_list[s] = s
            else:
                pass
            
def calc_leverage(cash): 
    max_cash = 10000000
    if cash > max_cash:
        return max_cash/cash * MAX_LEVERAGE
    else:
        return cash/cash * MAX_LEVERAGE
                    
def diversify(context,data,watchlist,max_leverage):
        
        pctx_max = STOCK_PCTX * max_leverage
        buy_no = len(watchlist)
        cur_no = len(context.portfolio.positions)
        target_pctx = 0.00
        total_no = buy_no + cur_no
        if total_no > 0:
            target_pctx = max_leverage/total_no
        
            if target_pctx > pctx_max:
                target_pctx = pctx_max
        
        return target_pctx
        
class GetVIX(CustomFactor):  
    window_length = 1  
    def compute(self, today, assets, out, vix):  
        out[:] = vix[-1]
        
#if cents not divisible by .05, round down if buy, round up if sell
def make_div_by_05(s, buy=False):
    s *= 20.00
    s =  math.floor(s) if buy else math.ceil(s)
    s /= 20.00
    return s

def cancel_open_buy_orders(context, data, stock):
    oo = get_open_orders(stock)
    for stock in oo:
        for order in oo:
            if 0 < order.amount:
                cancel_order(order.id)
                
def cancel_open_sell_orders(context, data, stock):
    oo = get_open_orders(stock)
    for stock in oo:
        for order in oo:
            if 0 > order.amount:
                cancel_order(order.id)
There was a runtime error.
1 response

You're having some leverage problems. Looks like you intend to only use 1.0 leverage, but you go up to 4.73.