Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

set_maximum_leverage #197

Open
plamen1989 opened this issue May 26, 2021 · 0 comments
Open

set_maximum_leverage #197

plamen1989 opened this issue May 26, 2021 · 0 comments

Comments

@plamen1989
Copy link

plamen1989 commented May 26, 2021

Dear community,

this is my very first posting on Github, so apologies upfront if I am not following the format you require.

I run a simple backtest (full code below) and would like to set the model's maximum leverage to 1. I read in the official documentation that there is a function set_max_leverage (max_leverage) but I am unsure how and where to integrate it into my code.

May I please ask you for advice?

Thank you very much in advance!

from zipline import run_algorithm
from zipline.api import order_target_percent, symbol, schedule_function,\
    date_rules, time_rules
from datetime import datetime
import pandas as pd
import pytz
import pyfolio as pf

def initialize(context):
    # Which stocks to trade
    dji = [
        "AAPL",
        "AXP",
        "BA",
        "CAT",
        "CSCO",
        "CVX",
        "DIS",
        "DWDP",
        "GS",
        "HD",
        "IBM",
        "INTC",
        "JNJ",
        "JPM",
        "KO",
        "MCD",
        "MMM",
        "MRK",
        "MSFT",
        "NKE",
        "PFE",
        "PG",
        "TRV",
        "UNH",
        "UTX",
        "V",
        "VZ",
        "WBA",
        "WMT",
        "XOM"
    ]
    
    # Make symbol list from tickers
    context.universe = [symbol(s) for s in dji]
    
    # History window
    context.history_window = 20
    
    # Size of our portfolio
    context.stocks_to_hold = 10
    
    # Schedule the daily trading routine for once per month
    schedule_function(handle_data, date_rules.month_start(),\
                      time_rules.market_close())

def month_perf(ts):
    perf = (ts[-1] / ts[0]) - 1
    return perf

def handle_data (context, data):
    # Get history for all the stocks
    hist = data.history (context.universe, "close", context.history_window, "1d")
    
    # This creates a table of percent returns, in order
    perf_table = hist.apply(month_perf).sort_values(ascending = False)
    
    # Make buy list of the top N stocks
    buy_list = perf_table[ : context.stocks_to_hold]
    
    # The rest will not be held
    the_rest = perf_table[context.stocks_to_hold : ]
    
    # Place target buy orders for top N stocks
    for stock, perf in buy_list.iteritems():
        stock_weight = 1 / context.stocks_to_hold
        
        # Place order
        if data.can_trade(stock):
            order_target_percent(stock, stock_weight)
            
    # Make sure we are flat the rest
    for stock, perf in the_rest.iteritems():
        
        # Place order
        if data.can_trade(stock):
            order_target_percent(stock, 0.0)
            
def analyze (context, perf):
    # Use PyFolio to generate a performance report
    returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(perf)
    pf.create_returns_tear_sheet(returns, benchmark_rets = None)
    
# Set start and end date
start = pd.to_datetime("2003-1-1", utc = True)
end = pd.to_datetime("2017-12-31", utc = True)

# Fire off the backtest
result = run_algorithm(start = start, end = end, initialize = initialize, 
                       analyze = analyze, capital_base = 10000,
                       data_frequency = "daily", bundle = "quandl")  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant