Overall Statistics
'''
Sample simple algorithm 
'''

# The imports below aren't always required but are handy if needed

# Import some datetime functions to use in scheduling
from datetime import datetime, timedelta

# Import numpy and pandas for all the powerful methods
import numpy as np
import pandas as pd

# The following class and associated Initialize method is always required
class BasicTemplateAlgorithm(QCAlgorithm):
    
    def Initialize(context):
        
        # Set the initial cash, start, and end dates for backtesting
        context.SetCash(100000)
        context.SetStartDate(2015,10,10)
        context.SetEndDate(2015,11,10)
        
        # Let's make a place to store the equities we wish to trade
        # In this sample two leveraged ETFs
        # Also store any info about each of them (in this case weight)
        # Put it all into a dataframe called 'context.stocks' for easy access
        stocks = ['SPXL', 'TMF']
        weights = [.6, .4]
        column_name = ['weight']
        context.stocks = pd.DataFrame(
                        index = stocks,
                        data = weights,
                        columns = column_name)

        # Subscribe to data for the equities we want to trade
        # Remember the index of the dataframe holds the stock symbols
        # Defaults to minute and fill-forward
        for stock in context.stocks.index:
            context.AddEquity(stock) 

        # Schedule trading at 10:00 am ET every day 
        context.Schedule.On(
            context.DateRules.EveryDay(),
            context.TimeRules.At(10, 0),     
            Action(context.enter_trades))

        # Schedule logging at 4:01 pm ET every day
        context.Schedule.On(
            context.DateRules.EveryDay(),
            context.TimeRules.At(16, 1),
            Action(context.log_info))
            

    def enter_trades(context):
        '''
        This is a custom method added to do our trading
        In this case we simply want to keep a fixed ratio 
        determned by our stored weight
        '''
        
        # The 'SetHoldings' method is a convenient way to easily
        # submit trades when the portfolio weight is known
        # maybe not robust enough for live trading but great for backtests
        for stock in context.stocks.index:
            weight = context.stocks.get_value(stock, 'weight')
            context.SetHoldings(stock, weight)
            
          
    def log_info(context):
        '''
        Log some info about algorithm
        Also an example of some of the ways to get data
        '''
        cash = context.Portfolio.Cash
        portfolio_value = context.Portfolio.TotalPortfolioValue
        context.Log('cash: {:.2f}  portfolio value: {:.2f} '.
                    format(cash, portfolio_value))
                    
        for stock in context.stocks.index:
            last_price = context.Securities[stock].Price
            shares_held = context.Portfolio[stock].Quantity
            value = last_price * shares_held
            context.Log('holding {} shares of {} with total value of: {:.2f}'.
                    format(shares_held, stock, value))