Back to Community
Magic Formula

In our algorithm we have made a condition not to make any transaction between February to November, but it is doing transactions in months apart from January and December. How to solve this problem? Please Help.

Clone Algorithm
13
Loading...
Backtest from to with initial capital
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
"""
This is a template algorithm on Quantopian for you to adapt and fill in.
"""
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, Fundamentals
from quantopian.pipeline.data import factset 
import pandas as pd  
import numpy as np
 
def initialize(context):
    
    """
    Called once at the start of the algorithm.
    """      
    # Create our dynamic stock selector.
    context.capacity = 30.0
    context.weight = 1.0/context.capacity
    context.buy = True
    
    my_pipe = make_pipeline()
    attach_pipeline(my_pipe, 'my_pipeline')
    
    set_slippage(slippage.FixedSlippage(spread=0.02))
    set_long_only()
    
    
    #schedule for buying a week after the year start
    schedule_function(func=schedule_task_a,
                      date_rule=date_rules.month_start(4),
                      time_rule=time_rules.market_open())
    #schedule for selling losers a week before the year start
    schedule_function(func=schedule_task_b,
                      date_rule=date_rules.month_end(4),
                      time_rule=time_rules.market_open())
    #schedule for selling winners on the 7th day of year start
    schedule_function(func=schedule_task_c,
                      date_rule=date_rules.month_start(3),
                      time_rule=time_rules.market_close())
    
def schedule_task_a(context, data):
    today = get_datetime('US/Eastern')
    if today.month == 1:
        for stock in context.portfolio.positions:
            #print stock
            print stock
        for stock in context.output.index:
            order_target_percent(stock, context.weight)
            
#selling losers
def schedule_task_b(context, data):
    today = get_datetime('US/Eastern')
    if today.month == 12 and context.portfolio.positions_value != 0:
        for stock in context.portfolio.positions:
            if context.portfolio.positions[stock].cost_basis > data.current(stock, 'price'):
                order_target_percent(stock, 0)            
        print today, 'losers sold'

#selling winners
def schedule_task_c(context, data):
    today = get_datetime('US/Eastern')
    if today.month == 1:
        for stock in context.portfolio.positions:
            order_target_percent(stock, 0)

def make_pipeline():
    filter_market_cap = (Fundamentals.market_cap.latest > 1000000000) & (Fundamentals.market_cap.latest < 10000000000)
    
    
    filter_plus = (
        Fundamentals.shares_outstanding.latest.notnull() &
        Fundamentals.market_cap.latest.notnull() &
        Fundamentals.country_id.latest.matches("USA") &
        filter_market_cap
    ) 
    
    earnings_yield = Fundamentals.ebit.latest/Fundamentals.enterprise_value.latest
    EY_rank = earnings_yield.rank(ascending=False)
    Return_On_Capital=                 Fundamentals.ebit.latest/(factset.Fundamentals.assets.latest-factset.Fundamentals.liabs_curr.latest-factset.Fundamentals.intang.latest)
    ROC_rank = Return_On_Capital.rank(ascending=False)
    sum_rank = EY_rank + ROC_rank
    
    pipe = Pipeline(columns = {
        'earnings_yield': earnings_yield,
        'ROC': Return_On_Capital,
        'sum_rank': sum_rank,
    } ,screen = filter_plus )
    return pipe
    
def before_trading_start(context, data):
  context.output=pipeline_output('my_pipeline').sort_values(by='sum_rank', ascending=True).head(int(context.capacity))

There was a runtime error.
1 response

The transactions you are seeing are associated with delisted stocks. The backtester automatically closes any positions of delisted stocks. The shares will go to zero and the portfolio will be credited with cash equal to the closing value on the day the delisting took place. Note that the opposite can also happen with other types of corporate actions. With a 'spin-off' or 'merger' one may see shares of an unknown stock suddenly appear in ones account. Additionally, dividends are automatically credited to ones account as of the payout date. These show up as an increase in cash.

All these actions are exactly what one would see in a real brokerage account. A broker will automatically adjust your account similar to what the backtester does. The backtester is designed to mimic very closely the account transactions which would happen in real life.

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.