Back to Community
How to have schedule function of six month?

I want to run a filter-stock function every six month. How can I set the schedule function?

1 response

The attached Annual holding period, long only, 30 random assets, evenly weighted should help you get started. Change modulo (%12 to %6) for semi-annual.

Clone Algorithm
12
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
import pandas as pd
from quantopian.algorithm import (
    attach_pipeline,
    pipeline_output,
    order_optimal_portfolio,
 )
from quantopian.optimize import (
    MaxGrossExposure,
    TargetWeights,
 ) 
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data import Fundamentals
from quantopian.pipeline.experimental import QTradableStocksUS
class Test( CustomFactor ):
    inputs = [ Fundamentals.current_assets ]
    window_length = 1
    def compute(self, today, assets, out, *inputs):
        out[:] = 0.0
    
def pipe():
    return Pipeline(
        columns = { 'test': Test() },
        screen=QTradableStocksUS()
    )
    
def initialize(context):
    schedule_function(
        monthly,
        date_rules.month_start(),
        time_rules.market_open(hours=1)
    )
    attach_pipeline(pipe(), 'pipe')
    context.month = 0
    context.order_ids = list()
    
def before_trading_start(context, data):
    if [id for id in context.order_ids if get_order(id).status == 2]:
        place_orders(context)
    context.df = pipeline_output('pipe')
    
def monthly(context, data):
    log.info(context.month)
    if not context.month % 12:
        N = 30
        context.index = context.df.sample(N).index
        place_orders(context)
        context.month = 0
    context.month += 1
    
def place_orders(context):
    N = len(context.index)
    try:
        context.order_ids = order_optimal_portfolio(
            TargetWeights(
                pd.Series(
                    N*[1.0/N],
                    index=context.index
                )
            ),
            [
                MaxGrossExposure(1.0),
            ]
        )
    except Exception as e:
        log.warn(e)
There was a runtime error.