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
-14.207
Tracking Error
0.023
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
Portfolio Turnover
0%
from AlgorithmImports import *
from datetime import timedelta
import datetime
from indicator import *

class TestAlphaModel(AlphaModel):

    def __init__(self, algo):
        self.algo = algo

    def Update(self, algo, slice):
        insights = []

        for symbol in slice.Keys:
            insight = Insight.Price(symbol, timedelta(days=30), InsightDirection.Up, None, None, None, 0.05)
            insights.append(insight)

        return insights
from AlgorithmImports import *

class QQQIndictor():
    def __init__(self, history, algo):
        self.slow = ExponentialMovingAverage(algo.slow)
        self.fast = ExponentialMovingAverage(algo.fast)

        self.mmFast = 0
        self.mmSlow = 0


        for bar in history.itertuples():
            self.fast.Update(bar.Index[1], bar.close)
            self.slow.Update(bar.Index[1], bar.close)
    def is_ready(self):
        return self.slow.IsReady and self.fast.IsReady
    
    def update(self, time, price):
        self.fast.Update(time, price)
        self.slow.Update(time, price)


class PriceAverage():
    def __init__(self, history, algo):
        self.slow = ExponentialMovingAverage(algo.slow)
        self.fast = ExponentialMovingAverage(algo.fast)

        for bar in history.itertuples():
            self.fast.Update(bar.Index[1], bar.close)
            self.slow.Update(bar.Index[1], bar.close)

    def is_ready(self):
        return self.slow.IsReady and self.fast.IsReady
    
    def update(self, time, price):
        self.fast.Update(time, price)
        self.slow.Update(time, price)


class VolumeAverage():
    def __init__(self, history, algo):
        self.vol = SimpleMovingAverage(algo.vol)

        for bar in history.itertuples():
            self.vol.Update(bar.Index[1], bar.volume)
    
    def is_ready(self):
        return self.vol.IsReady
    
    def update(self, time, price, volume):
        self.vol.Update(time, volume)
from AlgorithmImports import *

from alpha import TestAlphaModel
from indicator import *

#lean project-create --language python "Test3"
#lean cloud backtest "Test3" --push --open
#lean backtest Test3
class Test3(QCAlgorithm):
    def Initialize(self):


        self.SetStartDate(2021, 8, 6)  # Set Start Date
        self.SetEndDate(2021, 8, 15)  # Set End Date

        self.SetCash(100000)  # Set Strategy Cash
        self.UniverseSettings.Resolution = Resolution.Hour
        
        self.AddUniverse(self.CoarseFilter)

        self.AddAlpha(TestAlphaModel(self))




    def CoarseFilter(self, universe):
        selected = []

        self.prevClose = {}
        universe = [c for c in universe if (str(c.Symbol.Value) == "KLR")]

        for coarse in universe:
            symbol = coarse.Symbol
            if str(self.Time.date())=="2021-08-06":
                selected.append(symbol)


        return selected
from AlgorithmImports import *
from datetime import timedelta

class FixedWeightingPortfolioConstructionModel(PortfolioConstructionModel):
    insightCollection = InsightCollection()

    def __init__(self, portfolioBias = PortfolioBias.Long):
        super().__init__()
        self.portfolioBias = portfolioBias
        self.SetRebalancingFunc(Resolution.Daily)


    def CreateTargets(self, algo, insights):
        targets = []

        if (insights.Length > 0):
            self.insightCollection.AddRange(insights)

        percents = self.DetermineTargetPercent(insights)

        for insight in insights:
            percent = float(percents.get(insight))
            #algo.Log(f"CreateTargets Add -> {insight.Symbol.Value} {insight.Direction} {percent} ")
            
            if (insight.Direction == InsightDirection.Up):
                target = PortfolioTarget.Percent(algo, insight.Symbol, percents.get(insight))
                if target != None:
                    targets.append(target)
            
            

        expiredInsights = self.insightCollection.RemoveExpiredInsights(algo.UtcTime)


        for insight in expiredInsights:
            algo.Log(f"CreateTargets Expired -> {insight.Symbol.Value} {insight.IsExpired(algo.UtcTime)}, {insight.CloseTimeUtc}")
            target = PortfolioTarget.Percent(algo, insight.Symbol, 0)
            if target != None and algo.Portfolio[insight.Symbol].Invested:
                targets.append(target)

        return targets

    def DetermineTargetPercent(self, activeInsights):
        result = {}

        count = sum(x.Direction != InsightDirection.Flat and self.RespectPortfolioBias(x) for x in activeInsights)
        percent = 0 if count == 0 else 1.0 / count
        for insight in activeInsights:
            result[insight] = (insight.Direction if self.RespectPortfolioBias(insight) else InsightDirection.Flat) * insight.Weight
        return result

    def RespectPortfolioBias(self, insight):
        return self.portfolioBias == PortfolioBias.LongShort or insight.Direction == self.portfolioBias