Overall Statistics
Total Trades
1
Average Win
0%
Average Loss
0%
Compounding Annual Return
-0.044%
Drawdown
6.400%
Expectancy
0
Net Profit
-0.471%
Sharpe Ratio
-0.01
Probabilistic Sharpe Ratio
0.003%
Loss Rate
0%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
-0.004
Beta
0.041
Annual Standard Deviation
0.017
Annual Variance
0
Information Ratio
-0.723
Tracking Error
0.136
Treynor Ratio
-0.004
Total Fees
$1.00
Estimated Strategy Capacity
$3700000000.00
Lowest Capacity Asset
AAPL R735QTJ8XC9X
# region imports
import numpy as np
import pandas as pd
from AlgorithmImports import *
# endregion

class SwimmingSkyBlueFish(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2012, 1, 1)  # Set Start Date
        self.SetEndDate(2022,12,31)
        self.SetCash(100000)  # Set Strategy Cash
        self.stocks = ["SPY", "AMD", "AAPL"]
        
        for stock in self.stocks:
            self.AddEquity(stock, Resolution.Daily)
            self.rsi = self.RSI(stock, 14)
            self.back_1 = None
            self.back_2 = None
            self.current = None
            self.entry_price = None
            self.long_list=[]
            self.short_list=[]
            self.stop=False
            self.__macd = self.MACD(stock, 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
            self.__previous = datetime.min
            self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
            self.PlotIndicator(stock, self.__macd.Fast, self.__macd.Slow)
            self.sto = self.STO(stock, 5, 3, 3, Resolution.Daily)


    def OnData(self, data: Slice):
        '''OnData even is the primary entry point for your algorithm.
            Each new data point will be pumped in here.
            Arguments:
                data: Slice object keyed by symbol containing the stock data
        '''
        if self.stop:
            return

        for item in self.stocks[1:]:
            if not data.ContainsKey(item) or not data[item]:
                self.Debug(f"{self.Time.date()} has no data for {item}")
                return

            self.back_2 = self.back_1
            self.back_1 = self.current
            self.current = data[item].Close
            


            stockPrice = self.History([item], 30, Resolution.Daily)
            MA21_Pre = stockPrice.close[8:29].mean()
            MA5_Pre = stockPrice.close[24:29].mean()

            MA21_Current = stockPrice.close[9:30].mean()
            MA5_Current = stockPrice.close[25:30].mean()


                # if self.rsi.IsReady:
                #     self.Debug("RSI Ready")
            
            
            if self.back_2 == None or self.back_1 == None or self.current == None:
                return

            #trading conditions, only when we are not invested in the specific Stock

            if self.rsi.Current.Value > 40 and self.back_1 > self.back_2 and self.current > self.back_1 and MA5_Pre < MA21_Pre and MA5_Current > MA21_Current: 
                if not self.Portfolio[item].Invested:
                    self.SetHoldings(item,0.2) #invest 20% of our capital
                    self.entry_price = self.current
                    self.Debug("Bought" + item + " at $" + str(self.entry_price))

            
            # exit conditions, only if we are invested in the specific Stock
            if self.Portfolio[item].Invested and self.back_1 < self.back_2 and self.current < self.back_1 and MA5_Pre > MA21_Pre and MA5_Current < MA21_Current and self.rsi.Current.Value < 60:  
                if self.current <= self.entry_price - 0.0005:
                    self.Liquidate(item, "stop-loss")
                    self.Debug(item + "Sold via Stop-Loss at $" + str(self.entry_price))
                if self.current >= self.entry_price + 0.0010:
                    self.Liquidate(item,"take-profit")
                    self.Debug(item + "Sold via Take-Profit $" + str(self.entry_price))
            
            if self.Portfolio.Cash < 0.6*100000:
                self.stop=True
                self.Liquidate()

    
    def OnEndOfAlgorithm(self):

        history_spy = self.History(self.Symbol("SPY"), 30, Resolution.Daily)
        history_spy = history_spy["close"].tolist()
        spy_abs_return = (history_spy[-1]-history_spy[0]/history_spy[0])

        self.Debug('abs return of SPY is ' + str(spy_abs_return))

        df = pd.DataFrame()
        df["SPY_Price"]= history_spy
        df["SPY_returns"] = df["SPY_Price"].pct_change()
        spy_daily_returns = df["SPY_returns"].mean()
        spy_var = df["SPY_returns"].var()
        spy_std = df["SPY_returns"].std()

        for item in self.stocks[1:]:
            history = self.History(self.Symbol(item), 30, Resolution.Daily)
            history = history["close"].tolist()
            abs_return = (history[-1]- history[0]/history[0])

            self.Debug('abs return of {} is '.format(item) + str(abs_return))

            df[f"{item} Price"] = history

            specificStockPrice = df[f"{item} Price"]

            df[f"{item} returns"] = df[f"{item} Price"].pct_change()

            specificStockReturns = df[f"{item} returns"]

            daily_returns = specificStockReturns.mean()

            #self.Debug('SPY mean returns = {}'.format(spy_daily_returns))
            #self.Debug('{} mean returns = {}'.format(item, daily_returns))

            #variance
            var = specificStockReturns.var()

            # covariance
            covariance = df["SPY_returns"].cov(specificStockReturns)
            self.Debug('Covariance between SPY and {} is {} '.format(item, covariance))

            # correlation
            correlation = df["SPY_returns"].corr(specificStockReturns)
            self.Debug('Correlation between SPY and {} is {} '.format(item, correlation))

            # Standard Deviation
            std = specificStockReturns.std()
            self.Debug('Standard Deviation of {} is {} '.format(item, std))

            # TSLA Beta
            beta = covariance / spy_var
            self.Debug('Beta of {} is {}'.format(item, beta))

            alpha = abs_return - beta * spy_abs_return
            self.Debug('Alpha of {} is {}'.format(item, alpha))

            SR = daily_returns/ std * (252**0.5)
            self.Debug('Sharpe Ratio of {} is {}'.format(item, SR))

            self.Debug('------------------------------------------------')

            #self.Debug('Beta: {} | Alpha: {} | Sharpe Ratio: {} '.format(beta,alpha,SR))

        self.Debug(df)


        # ------------------------------------

        # region imports
# import numpy as np
# import pandas as pd
# from AlgorithmImports import *
# # endregion

# class GeekyYellowGreenCaterpillar(QCAlgorithm):

#     # Entry Rules
#     # 1. MACD fast line cross above slow line
#     # 2. MACD above 70%
#     # 3. Stochastics fast cross above slow
#     # 4. Stochastics around 20% (No trades are done when this is implemented)
#     # 5. Sell when Opposite is True

#     def Initialize(self):

#         self.SetStartDate(2012, 1, 1)    #Set Start Date
#         self.SetEndDate(2022, 1, 1)      #Set End Date
#         self.SetCash(10000)             #Set Strategy Cash

#         self.spy = self.AddEquity("AAPL", Resolution.Daily)

#         # define our daily macd(12,26) with a 9 day signal
#         self.__macd = self.MACD("AAPL", 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily)
#         self.__previous = datetime.min
#         self.PlotIndicator("MACD", True, self.__macd, self.__macd.Signal)
#         self.PlotIndicator("AAPL", self.__macd.Fast, self.__macd.Slow)
#         self.sto = self.STO("AAPL", 5, 3, 3, Resolution.Daily)


#     def OnData(self, data):
        
#         if not self.__macd.IsReady: return

#         if not self.sto.IsReady: return

#         # only once per day
#         if self.__previous.date() == self.Time.date(): return

#         # Stochastics variables
#         fast_stoch = self.sto.FastStoch.Current.Value
#         stoch_k = self.sto.StochK.Current.Value
#         stoch_d = self.sto.StochD.Current.Value
#         current = self.sto.Current.Value

#         # MACD tolerance
#         tolerance = 0.007

#         holdings = self.Portfolio["AAPL"].Quantity

#         signalDeltaPercent = (self.__macd.Current.Value - self.__macd.Signal.Current.Value)/self.__macd.Fast.Current.Value

#         # Go long when MACD in on uptrend
#         if holdings <= 0 and signalDeltaPercent > tolerance and stoch_k>stoch_d:  

#             self.SetHoldings("AAPL", 1.0)
#             self.Debug(f"Buy at {self.Portfolio['AAPL'].Price}")
#             self.Debug(f"stoch_k: {stoch_k}")
#             self.Debug("--------------")

#         # Liquidate when MACD is on downtrend
#         elif holdings >= 0 and signalDeltaPercent < -tolerance and stoch_k<stoch_d:
#             self.Liquidate("AAPL")
#             self.Debug(f"Sell at {self.Portfolio['AAPL'].Price}")
#             self.Debug(f"stoch_k: {stoch_k}")
#             self.Debug("--------------")


#         self.__previous = self.Time