Overall Statistics
Total Orders
423
Average Win
1.01%
Average Loss
-0.71%
Compounding Annual Return
4.821%
Drawdown
24.000%
Expectancy
0.066
Start Equity
100000
End Equity
114105.43
Net Profit
14.105%
Sharpe Ratio
0.087
Sortino Ratio
0.101
Probabilistic Sharpe Ratio
7.800%
Loss Rate
56%
Win Rate
44%
Profit-Loss Ratio
1.43
Alpha
0.01
Beta
0.121
Annual Standard Deviation
0.148
Annual Variance
0.022
Information Ratio
-0.054
Tracking Error
0.196
Treynor Ratio
0.107
Total Fees
$722.46
Estimated Strategy Capacity
$780000000.00
Lowest Capacity Asset
SPY R735QTJ8XC9X
Portfolio Turnover
36.86%
#region imports
from AlgorithmImports import *
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam
#endregion
class KerasExampleAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2021, 7, 5)  # Set Start Date
        self.set_cash(100000)  # Set Strategy Cash
        self.symbol = self.add_equity("SPY", Resolution.DAILY).symbol

        model_key = "model.keras"
        if self.object_store.contains_key(model_key):
            file_name = self.object_store.get_file_path(model_key)
            self.model = load_model(file_name)
        
        else:
            self.model = Sequential([Dense(10, input_shape=(5,5), activation='relu'),
                            Dense(10, activation='relu'),
                            Flatten(),
                            Dense(1)])
            self.model.compile(loss='mse',
                    optimizer=Adam(),
                    metrics=['mae', 'mse'])

        training_length = 252*2
        self.training_data = RollingWindow[TradeBar](training_length)
        history = self.history[TradeBar](self.symbol, training_length, Resolution.DAILY)
        for trade_bar in history:
            self.training_data.add(trade_bar)

        self.train(self.my_training_method)
        self.train(self.date_rules.every(DayOfWeek.SUNDAY), self.time_rules.at(8, 0), self.my_training_method)
            
    def get_features_and_labels(self, n_steps=5) -> Tuple[float, float]:
        training_df = self.pandas_converter.get_data_frame[TradeBar](list(self.training_data)[::-1])
        daily_pct_change = training_df.pct_change().dropna()

        features = []
        labels = []
        for i in range(len(daily_pct_change)-n_steps):
            features.append(daily_pct_change.iloc[i:i+n_steps].values)
            labels.append(daily_pct_change['close'].iloc[i+n_steps])
        features = np.array(features)
        labels = np.array(labels)

        return features, labels

    def my_training_method(self) -> None:
        features, labels = self.get_features_and_labels()
        self.model.fit(features, labels, epochs=5)

    def on_data(self, slice: Slice) -> None:
        if self.symbol in slice.bars:
            self.training_data.add(slice.bars[self.symbol])

        features, _ = self.get_features_and_labels()
        features = features[-1].reshape(1, 5, 5)
        prediction = float(self.model.predict(features)[-1])

        if prediction > 0:
            self.set_holdings(self.symbol, 1)
        elif prediction < 0:            
            self.set_holdings(self.symbol, -1)

    def on_end_of_algorithm(self):
        model_key = "model.keras"
        file_name = self.object_store.get_file_path(model_key)
        self.model.save(file_name)