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
-0.702
Tracking Error
0.142
Treynor Ratio
0
Total Fees
$0.00
Estimated Strategy Capacity
$0
Lowest Capacity Asset
# region imports
from AlgorithmImports import *
# endregion

# Imports
from keras.models import Sequential
from keras.layers import Activation, Dense
from keras.utils.generic_utils import serialize_keras_object
import json
import numpy as np

class PensiveYellowGreenBison(QCAlgorithm):

    def Initialize(self):

        # # # # # User input area # # # # #

        # Set Start Date
        self.SetStartDate(2013, 1, 1)

        # Set Strategy Cash
        self.SetCash(100000)

        # Stop loss percent
        self.stop_loss_percent = 2

        # Stock to trade
        stock_to_trade = "GOOG"

        # # # # # End user input area # # # # #

        # Add stock
        self.stock_symbol = self.AddEquity(stock_to_trade, Resolution.Daily).Symbol

        # SMA
        self.symbol_SMA = self.SMA(self.stock_symbol, 10, Resolution.Daily)

        # EMA
        self.symbol_EMA = self.EMA(self.stock_symbol, 10, Resolution.Daily)

        # RSI
        self.symbol_RSI = self.RSI(self.stock_symbol, 14, Resolution.Daily)

        # Storage
        self.storage = {"sum_OHLC":[],"SMA":[], "EMA":[], "RSI":[], "close":[]}

        # Read serialized model
        model_serialized = self.ObjectStore.Read("model_key")

        # Config
        model_serialized_config = json.loads(model_serialized)['config']

        # Convert back to model
        self.trained_model = Sequential.from_config(model_serialized_config)

        # Saved average of values at entry
        self.saved_average = 0

        # Set warmup
        self.SetWarmup(200)

    def OnData(self, data: Slice):

        # If SMA, EMA and RSI ready
        if self.symbol_RSI.IsReady:
            
            # Open
            open_price = self.Securities[self.stock_symbol].Open

            # High
            high = self.Securities[self.stock_symbol].High

            # Low
            low = self.Securities[self.stock_symbol].Low

            # Close
            close = self.Securities[self.stock_symbol].Close

            # Store values
            self.storage["sum_OHLC"].append(open_price + high + low + close)
            self.storage["SMA"].append(self.symbol_SMA.Current.Value)
            self.storage["EMA"].append(self.symbol_EMA.Current.Value)
            self.storage["RSI"].append(self.symbol_RSI.Current.Value)
            self.storage["close"].append(close)

            # Cut length
            if len(self.storage["sum_OHLC"]) > 100:
                self.storage["sum_OHLC"] = self.storage["sum_OHLC"][-100:]
                self.storage["SMA"] = self.storage["SMA"][-100:]
                self.storage["EMA"] = self.storage["EMA"][-100:]
                self.storage["RSI"] = self.storage["RSI"][-100:]
                self.storage["close"] = self.storage["close"][-100:]

            # If not warming up
            if not self.IsWarmingUp:

                # If not invested
                if not self.Portfolio.Invested:

                    # Normalize storage values
                    sum_OHLC_normalized = [i/max(self.storage["sum_OHLC"]) for i in self.storage["sum_OHLC"]]
                    EMA_normalized = [i/max(self.storage["EMA"]) for i in self.storage["EMA"]]
                    SMA_normalized = [i/max(self.storage["SMA"]) for i in self.storage["SMA"]]
                    RSI_normalized = [i/max(self.storage["RSI"]) for i in self.storage["RSI"]]
                    close_normalized = [i/max(self.storage["close"]) for i in self.storage["close"]]

                    # Reshape
                    sum_OHLC_normalized_reshaped = np.array(sum_OHLC_normalized).reshape(len(sum_OHLC_normalized),1)
                    EMA_normalized_reshaped = np.array(EMA_normalized).reshape(len(EMA_normalized),1)
                    SMA_normalized_reshaped = np.array(SMA_normalized).reshape(len(SMA_normalized),1)
                    RSI_normalized_reshaped = np.array(RSI_normalized).reshape(len(RSI_normalized),1)

                    # Predict
                    sum_OHLC_predict = self.trained_model.predict(sum_OHLC_normalized_reshaped)
                    EMA_predict = self.trained_model.predict(EMA_normalized_reshaped)
                    SMA_predict = self.trained_model.predict(SMA_normalized_reshaped)
                    RSI_predict = self.trained_model.predict(RSI_normalized_reshaped)

                    # Get most recent values
                    predicted_current_close_from_sum_OHLC = sum_OHLC_predict[-1][0][0]
                    predicted_current_close_from_EMA = EMA_predict[-1][0][0]
                    predicted_current_close_from_SMA = SMA_predict[-1][0][0]
                    predicted_current_close_from_RSI = RSI_predict[-1][0][0]
                    current_close = close_normalized[-1]

                    # If current close lower than all predicted values
                    if (
                        
                        current_close < predicted_current_close_from_sum_OHLC and 
                        current_close < predicted_current_close_from_EMA and
                        current_close < predicted_current_close_from_SMA and
                        current_close < predicted_current_close_from_RSI

                        ):

                        # Buy with 100% portfolio cash
                        self.SetHoldings(self.stock_symbol, 1)

                        # Save average
                        self.saved_average = (predicted_current_close_from_sum_OHLC + predicted_current_close_from_EMA + predicted_current_close_from_SMA + predicted_current_close_from_RSI) / 4
                
                # Else
                else:
                    
                    # Get normalized close prices
                    close_normalized = [i/max(self.storage["close"]) for i in self.storage["close"]]

                    # If current price under saved average
                    if close_normalized[-1] > self.saved_average:

                        # Sell
                        self.Liquidate(tag = "Normalized value exceeded predicted average at entry")

                    # Else
                    else:

                        # If current price lower than average price by stop loss percent
                        if close < self.Portfolio[self.stock_symbol].AveragePrice * (1 - (0.01 * self.stop_loss_percent)):

                            # Sell
                            self.Liquidate(tag = "Stop loss")