Overall Statistics
Total Trades
36
Average Win
0.12%
Average Loss
-0.02%
Compounding Annual Return
36.843%
Drawdown
1.200%
Expectancy
3.673
Net Profit
1.263%
Sharpe Ratio
4.136
Loss Rate
33%
Win Rate
67%
Profit-Loss Ratio
6.01
Alpha
0.122
Beta
0.491
Annual Standard Deviation
0.055
Annual Variance
0.003
Information Ratio
0.222
Tracking Error
0.055
Treynor Ratio
0.463
Total Fees
$127.19
import math
import numpy as np
import pandas as pd
import statistics 
import talib

from datetime import datetime, timedelta


class BasicTemplateAlgorithm(QCAlgorithm):

    def Initialize(self):

        self.SetCash(100000)
        self.SetStartDate(2017, 1, 1)
        self.SetEndDate(2017, 1, 15)
        self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin)
        self.Portfolio.MarginModel = MarginCallModel.Null
        
        # Add securities and indicators
        self.bonds = ["SHY","IEF"]
        for s in self.bonds:
            self.AddEquity(s, Resolution.Minute)
            self.Securities[s].MarginModel = PatternDayTradingMarginModel()

        # Schedule trades
        self.Schedule.On(self.DateRules.EveryDay("SHY"),
            self.TimeRules.At(9, 40), Action(self.Rebalance))
                 
        # Schedule trades
        self.Schedule.On(self.DateRules.EveryDay("SHY"),
            self.TimeRules.At(13, 50), Action(self.Rebalance2))
                 
        # Run Portfolio Stats
        self.Schedule.On(self.DateRules.EveryDay("SHY"),
            self.TimeRules.At(16, 00), Action(self.PortfolioStats))
            
        # Establish day trading leverage at 4x
        #self.Securities["IEF"].MarginModel = PatternDayTradingMarginModel()
        #self.Securities["SHY"].MarginModel = PatternDayTradingMarginModel()
        
        # Days to warm up the indicators
        self.SetWarmup(timedelta(2))
     
        
    def OnData(self, slice):
        pass
    
    
    def Rebalance(self):
        
        for s in self.bonds:
            price = round(self.Securities[s].Price, 2)
            self.Log("price:{}" .format(price))
            self.SetHoldings(s, 1.5)


    def Rebalance2(self):
        
        for s in self.bonds:
            price = round(self.Securities[s].Price, 2)
            self.Log("price:{}" .format(price))
            self.SetHoldings(s, 0.9)
            
            
    def PortfolioStats(self):
        
        port_val = self.Portfolio.TotalPortfolioValue
        
        for s in self.bonds:
            actual_weight = self.Portfolio[s].Quantity * self.Securities[s].Price / port_val 
            self.Log("{} {}".format(s, round(actual_weight, 3)))
        account_leverage = self.Portfolio.TotalAbsoluteHoldingsCost / port_val
        self.Log("{}%".format(round(account_leverage,3) * 100))