Overall Statistics
Total Trades
216
Average Win
1.40%
Average Loss
-1.27%
Compounding Annual Return
-20.012%
Drawdown
11.000%
Expectancy
-0.028
Net Profit
-5.521%
Sharpe Ratio
-1.095
Loss Rate
54%
Win Rate
46%
Profit-Loss Ratio
1.11
Alpha
0.001
Beta
-10.6
Annual Standard Deviation
0.131
Annual Variance
0.017
Information Ratio
-1.199
Tracking Error
0.131
Treynor Ratio
0.014
Total Fees
$440.18
import decimal as d
import pandas as pd
from datetime import datetime, timedelta



# https://www.quantconnect.com/forum/discussion/2865/crypto-bollinger-band-strategy/p1
# https://www.factorresearch.com/research-quant-strategies-in-the-cryptocurrency-space
# https://www.quantconnect.com/tutorials/strategy-library/short-term-reversal-strategy-in-stocks
# https://www.quantconnect.com/tutorials/introduction-to-financial-python/rate-of-return,-mean-and-variance
# https://www.quantconnect.com/tutorials/strategy-library/forex-momentum


class BasicTemplateCryptoAlgorithm(QCAlgorithm):
    
    
    
    def __init__(self):
    # set the flag for rebalance
        self.reb = 1

    # Number of assets to long/short
        self.num_fine = 8
        
        
    

    def Initialize(self):

        self.SetStartDate(2018, 10, 1)  #Set Start Date
        self.SetEndDate(2018, 12, 31)    #Set End Date


        # Set Strategy Cash (USD)
        self.SetCash(10000)


        self.SetBrokerageModel(BrokerageName.Bitfinex, AccountType.Margin)
        
        self.SetBenchmark('BTCUSD')


        tickers = ["BTCUSD", "ETHUSD", "XRPUSD", "LTCUSD", "EOSUSD", "NEOUSD", "XMRUSD", "TRXUSD"]

        for ticker in tickers:
            self.AddCrypto(ticker, Resolution.Daily, Market.Bitfinex)
        
        

        # set warmup period
        #self.SetWarmUp(20)
        self.SetWarmUp(timedelta(7))

        # Schedule the rebalance function to execute at the begining of each month
        self.Schedule.On(self.DateRules.WeekStart(), self.TimeRules.At(12, 0, 0), Action(self.rebalance))





    def OnData(self, data):
        # Beräkna 7d avkastning på samtliga valutor.
        # Gå lång på de 4 valutor som utvecklats bäst de senaste 7d.
        # Gå kort på de 4 valutor som utvecklats sämst de senaste 7d.
        
        # Ombalansera varje vecka.
        pass
        
        
        
        
        
    def rebalance(self):
        
        tickers = ["BTCUSD", "ETHUSD", "XRPUSD", "LTCUSD", "EOSUSD", "NEOUSD", "XMRUSD", "TRXUSD"]

        
        df = pd.DataFrame()

        start = datetime(2018, 10, 1)
        end = datetime(2018, 12, 31)
        
        
       
        # Gets historical data from the subscribed assets
       
        #h1 = self.History(self.Securities.Keys, start, end, Resolution.Daily)
        h1 = self.History(tickers, timedelta(30), Resolution.Daily)
        #h1 = self.History(["BTCUSD", "ETHUSD", "XRPUSD", "LTCUSD", "EOSUSD", "NEOUSD", "XMRUSD", "TRXUSD"], timedelta(30), Resolution.Daily)
        
        if h1.empty:
            self.Log("EMPTY dataframe!")
        
        # Resample to 1W timeframe.
        for i in tickers:
            df[i] = h1.loc[i]['close'].resample('W').mean().pct_change()
        
        # Sort the lastrow of dataframe       
        last_week = df.iloc[-1].sort_values(ascending=False)
        
        # Assign the assets to short/long       
        self.long = [last_week.index[0], last_week.index[1], last_week.index[2], last_week.index[3]]
        self.short = [last_week.index[4], last_week.index[5], last_week.index[6], last_week.index[7]]

       
       
       
       
       
        # if this month the stock are not going to be long/short, liquidate it.
        #long_short_list = self.long + self.short
        #for i in self.Portfolio.Values:
        #    if (i.Invested) and (i not in long_short_list):
        #        self.Liquidate(i.Symbol)
   
        
        self.Liquidate()
        
        
        # Assign each asset equally. Alternatively you can design your own portfolio construction method
        for i in self.long:
            self.SetHoldings(i, 0.9/self.num_fine)
        
        for i in self.short:
            self.SetHoldings(i, -0.9/self.num_fine)

        self.reb = 1




    def OnOrderEvent(self, orderEvent):
        self.Debug("{} {}".format(self.Time, orderEvent.ToString()))

    def OnEndOfAlgorithm(self):
        self.Log("{} - TotalPortfolioValue: {}".format(self.Time, self.Portfolio.TotalPortfolioValue))
        self.Log("{} - CashBook: {}".format(self.Time, self.Portfolio.CashBook))