Overall Statistics
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)
                
        # Add securities and indicators
        self.bonds = ["SHY","IEF"]
        for s in self.bonds:
            self.AddEquity(s, Resolution.Minute)
            #self.bonds[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))
            
        # Days to warm up the indicators
        self.SetWarmup(timedelta(20))
     
        
    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))