Overall Statistics
Total Trades
0
Average Win
0%
Average Loss
0%
Compounding Annual Return
0%
Drawdown
0%
Expectancy
0
Net Profit
0%
Sharpe Ratio
0
Probabilistic Sharpe Ratio
0%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
0
Annual Standard Deviation
0
Annual Variance
0
Information Ratio
-2.268
Tracking Error
0.113
Treynor Ratio
0
Total Fees
$0.00
from collections import deque
from datetime import datetime, timedelta
from numpy import sum
import numpy as np
from scipy import stats

### Demonstrates how to create a custom indicator and register it for automatic updated
class CustomIndicatorAlgorithm(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2019,1,1)
        self.SetEndDate(2019,12,31)
        
        spy = self.AddEquity("SPY", Resolution.Daily).Symbol

        self.custom = My_Custom('My_Custom', spy, 100)
        self.RegisterIndicator("SPY", self.custom, Resolution.Daily)
        
        history = self.History(spy, 100, Resolution.Daily)
        self.custom.Warmup(history)

    def OnData(self, data):
        self.Plot("My_Custom_Slope", "Slope", self.custom.Slope)
        self.Plot("My_Custom_Intercept", "Intercept", self.custom.Intercept)
        self.Plot("My_Custom_R_value", "R_value", self.custom.R_value)
        #self.Plot("My_Custom_P_value", "P_value", self.custom.P_value)
        #self.Plot("My_Custom_Std_err", "Std_err ", self.custom.Std_err )

# Python implementation of Custom Indicator
class My_Custom:
    def __init__(self, name, symbol, period):
        self.symbol = symbol
        self.Name = name
        self.Time = datetime.min
        self.Value = 0
        self.Slope = 0
        self.Intercept = 0
        self.R_value = 0
        self.P_value = 0
        self.Std_err = 0
        self.queue = deque(maxlen=period)
        self.IsReady = False

    # Update method is mandatory
    def Update(self, input):
        return self.Update2(input.Time, input.Close)
    
    def Update2(self, time, value):
        self.queue.appendleft(value)
        count = len(self.queue)
        self.Time = time
        
        self.IsReady = count == self.queue.maxlen
        
        #### start here the indicator calulation
        if self.IsReady:    
            y = np.log(self.queue)
            x = [range(len(y))]
            slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
            self.Slope = slope * 10000 # value is very small an will display 0 if not multiplyed
            self.Intercept = intercept
            self.R_value = r_value * 10
            self.P_value = p_value 
            self.Std_err = std_err 
        #### finish the custom indicator
        
        return self.IsReady
        
    def Warmup(self,history):
        for index, row in history.loc[self.symbol].iterrows():
            self.Update2(index, row['close'])