Hello, I'm trying to create my first code here, on Quantopian.
My first attempt was to mimic a buy-and-hold approach with the following code (not sure how to share it properly):
def initialize(context):
context.spy = sid(8554)
context.invested = False
schedule_function(initialize_my_portfolio, date_rules.every_day(), time_rules.market_open())
schedule_function(record_leverage, date_rules.every_day(), time_rules.market_close())
def record_leverage(context, data):
record('Leverage', context.account.leverage)
def initialize_my_portfolio(context, data):
if not context.invested:
order_target_percent(context.spy, 1.0)
context.invested = True
I made a short backtest on a period between 01/03/2017 and 07/15/2018. The strategy shows a return of 26.9% but this is not important.
It is the level of leverage what caught my attention. Correct me if I am wrong but if I start with 100 USD and my account goes up by 27%, my leverage should go down from 1 (fully invested at the beginning) to something like 0.79 (100 / 126.9). However, my code shows that my leverage remains nearly intact. Not sure why is that.
I'd say there is some problem with my code but I cannot figure out where and why. Perhaps someone could spot my mistake easily.
Thank you for every hint!
Mike