Overall Statistics
Total Trades
2350
Average Win
0.04%
Average Loss
-0.02%
Compounding Annual Return
103.383%
Drawdown
6.800%
Expectancy
0.248
Net Profit
7.671%
Sharpe Ratio
3.029
Probabilistic Sharpe Ratio
66.999%
Loss Rate
52%
Win Rate
48%
Profit-Loss Ratio
1.59
Alpha
0.749
Beta
1.436
Annual Standard Deviation
0.298
Annual Variance
0.089
Information Ratio
3.151
Tracking Error
0.252
Treynor Ratio
0.628
Total Fees
$2368.10
Estimated Strategy Capacity
$36000000.00
Lowest Capacity Asset
BABA VU1EHIDJYJXH
from QuantConnect import *
from QuantConnect.Parameters import *
from QuantConnect.Benchmarks import *
from QuantConnect.Brokerages import *
from QuantConnect.Util import *
from QuantConnect.Interfaces import *
from QuantConnect.Algorithm import *
from QuantConnect.Algorithm.Framework import *
from QuantConnect.Algorithm.Framework.Selection import *
from QuantConnect.Algorithm.Framework.Alphas import *
from QuantConnect.Algorithm.Framework.Portfolio import *
from QuantConnect.Algorithm.Framework.Execution import *
from QuantConnect.Algorithm.Framework.Risk import *
from QuantConnect.Indicators import *
from QuantConnect.Data import *
from QuantConnect.Data.Consolidators import *
from QuantConnect.Data.Custom import *
from QuantConnect.Data.Fundamental import *
from QuantConnect.Data.Market import *
from QuantConnect.Data.UniverseSelection import *
from QuantConnect.Notifications import *
from QuantConnect.Orders import *
from QuantConnect.Orders.Fees import *
from QuantConnect.Orders.Fills import *
from QuantConnect.Orders.Slippage import *
from QuantConnect.Scheduling import *
from QuantConnect.Securities import *
from QuantConnect.Securities.Equity import *
from QuantConnect.Securities.Forex import *
from QuantConnect.Securities.Interfaces import *
from datetime import date, datetime, timedelta
from QuantConnect.Python import *
from QuantConnect.Storage import *

QCAlgorithmFramework = QCAlgorithm
QCAlgorithmFrameworkBridge = QCAlgorithm

from QuantConnect import Resolution
from QuantConnect.Algorithm import QCAlgorithm


import pandas as pd

# # wilders moving average
# class nvdia_rsi(QCAlgorithm):
#     def Initialize(self):
#         self.SetStartDate(2021, 3, 1)  # Set Start Date
#         self.SetEndDate(2021, 3, 10) # Set End Date
#         self.SetCash(100000)  # Set Strategy Cash
#         self.UniverseSettings.Resolution = Resolution.Daily
#         self.AddUniverse(self.SelectCoarse)


#     def SelectCoarse(self, coarse):
#         # select NVIDIA from coarse
#         nvda_ticker = "NVDA RHM8UTD8DT2D"
#         for c in coarse:
#             symbol = c.Symbol
#             if SymbolCache.GetTicker(symbol) == nvda_ticker:
#                 nvda = symbol

#         # get nvidia history
#         history = self.History([nvda], 365, Resolution.Daily)

#         rsi = RelativeStrengthIndex(6, MovingAverageType.Wilders)

#         # update rsi for nvidia
#         for row in history.loc[nvda_ticker].itertuples():
#             rsi.Update(row.Index, row.close)

#         # print time and rsi value
#         self.Debug(self.Time)
#         self.Debug(rsi.Current.Value)
#         return []

# force to liquidate on market open

class buyBeforeMarketClose(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2021, 5, 1)  # Set Start Date
        self.SetCash(100000)  # Set Strategy Cash
        self.UniverseSettings.Resolution = Resolution.Minute
        self.AddUniverseSelection(
            FineFundamentalUniverseSelectionModel(self.SelectCoarse, self.SelectFine)
        )
        self.SetAlpha(buyBeforeMarketCloseAlphaModel())
        self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel(rebalance = None))
        self.SetExecution(ImmediateExecutionModel())

    def SelectCoarse(self, coarse):
        # select top 3 most liquid
        mostliquid = sorted(coarse, key=lambda c: c.DollarVolume, reverse=True)[:5]

        return [c.Symbol for c in mostliquid]

    def SelectFine(self, fine):
        # selected_new_day = [f.Symbol for f in fine]
        # selected = [s for s in selected_new_day if self.Portfolio.ContainsKey(s) and self.Portfolio[s].Invested and s not in selected_new_day] + selected_new_day
        return [f.Symbol for f in fine]

class buyBeforeMarketCloseAlphaModel(AlphaModel):
    '''Buy 5 minutes before market close and hold for 3 days'''

    def __init__(self):
        self.securities = []
        self.insightPeriod = timedelta(days=5)
        self.direction = InsightDirection.Up

    def Update(self, algorithm, data):
        insights = []
        # buy 5 mins before market close
        if algorithm.Time.hour == 15 and algorithm.Time.minute == 55:
            for security in self.securities:
                insights.append(Insight.Price(security.Symbol, self.insightPeriod, self.direction))

        return insights

    def OnSecuritiesChanged(self, algorithm, changes):
        for added in changes.AddedSecurities:
            self.securities.append(added)