Overall Statistics
Total Orders
13
Average Win
122.38%
Average Loss
-30.10%
Compounding Annual Return
0.143%
Drawdown
86.300%
Expectancy
1.026
Start Equity
100000
End Equity
100859.47
Net Profit
0.859%
Sharpe Ratio
0.191
Sortino Ratio
0.241
Probabilistic Sharpe Ratio
1.253%
Loss Rate
60%
Win Rate
40%
Profit-Loss Ratio
4.07
Alpha
0.004
Beta
1.03
Annual Standard Deviation
0.482
Annual Variance
0.233
Information Ratio
0.014
Tracking Error
0.449
Treynor Ratio
0.09
Total Fees
$303.81
Estimated Strategy Capacity
$3000.00
Lowest Capacity Asset
SATO XSGUM9B6ZA79
Portfolio Turnover
0.50%
Drawdown Recovery
139
Avg. Lost% Per Losser
-33.27%
Avg. Win% Per Winner
83.74%
Max Win%
222.04%
Max Loss%
-68.84%
*Profit Ratio
1.0
'''
Usage: 
    def Initialize(self):
        self.log = Log(self)

    # code xxxxxx
    self.log.log("---->1")        
        
'''


from AlgorithmImports import *

import time

class Log():
    def __init__(self, algo):
        self.timer = round(time.time() * 1000)
        self.algo = algo
        self.maxLine = 400
        self.count = 0
        self.debug(f"Live mode={self.algo.live_mode}.....Log Initialized")

    def log(self, message):
        self.algo.Log(f"[LOG] {message}")

    def info(self, message):
        now = round(time.time() * 1000)
        timer = (now - self.timer) / 1000
        self.timer = now
        if (self.algo.Time <= self.algo.Time.replace(hour=9, minute=35)):
            self.algo.Log(f"[INFO] {message}")

    def debug(self, message):
        if (self.count < self.maxLine or self.algo.live_mode):
            self.algo.Log(f"[DEUBG] {message}")
            self.count += 1

    def live(self, message):
        if self.algo.live_mode:
            self.algo.Log(f"[DEUBG] {message}")
# ================================================================================
# DISCLAIMER
# ================================================================================
# This code is provided free of charge for EDUCATIONAL PURPOSES ONLY. Users are 
# granted permission to study, modify, and redistribute this script for non-
# commercial learning and research.
#
# The author and developers of this code assume NO LIABILITY for any financial 
# losses, trading damages, or missed opportunities resulting from the use or 
# misuse of this algorithm. Quantitative trading involves significant risk, 
# and past performance is not indicative of future results
#
# This code is provided "AS IS" without any warranties. The author does not 
# provide technical support, bug fixes, or maintenance for this script. 
# Users are responsible for their own due diligence and backtesting before 
# considering any live deployment

from AlgorithmImports import *
from datetime import timedelta, datetime
from security_initializer import CustomSecurityInitializer
from utils import Utils
from log import Log

'''
Scope: All in S&P500 best performance constituents
'''
# lean project-create --language python "ALLIN01"
# lean cloud backtest "ALLIN01" --push --open
class ALLIN01(QCAlgorithm):
    def initialize(self):
        # Set backtest range and initial capital
        self.set_start_date(2020, 1, 1)
        self.set_end_date(2025, 12, 31)
        self.init_cash = 100000
        self.set_cash(self.init_cash)  # Set Strategy Cash

        
        # Define the benchmark and the base ETF for constituent selection (SPY)
        self._symbol = self.add_equity("SPY", Resolution.HOUR).Symbol

        ''' We pick the best performing of non-leveraged ETFs (available to trade in major exchange only) from previous year and hold for a year
            source:
                2019 best performing ETF: https://www.etf.com/sections/news/best-performing-etfs-2019
                2020 best performing ETF: https://www.statmuse.com/money/ask/best-performing-etf-in-2020
                2021 best performing ETF: https://www.etf.com/sections/news/best-performing-etfs-2021
                2022 best performing ETF: https://www.etf.com/sections/news/best-performing-etfs-2022
                2023 best performing ETF: https://www.etf.com/sections/etf-basics/best-performing-etfs-2023
                2024 best performing ETF: https://www.investing.com/analysis/3-topperforming-nonleveraged-etfs-from-2024-and-into-2025-200655112
        '''
        self.picked = {
            2020: "TAN",   # Invesco Solar ETF
            2021: "CN",    # China Fund  
            2022: "BDRY",  # Breakwave Dry Bulk Shipping
            2023: "TUR",   # iShares MSCI Turkey ETF
            2024: "WGMI",  # Valkyrie Bitcoin Miners ETF
            2025: "SATO"   # Invesco Alerian Galaxy Crypto Economy
        }

        self.assets = list(self.picked.values())

        for ticker in self.assets:
            self.add_equity(ticker, Resolution.HOUR).symbol
        
        self.log = Log(self)
        self.utils = Utils(self, self._symbol)

        self.schedule.on(self.date_rules.every_day(), self.time_rules.before_market_close(self._symbol, 0), self.utils.plot)

        self.schedule.on(self.date_rules.every_day(), 
            self.time_rules.after_market_open(self._symbol, 1), 
            self.market_open)

    
    def on_end_of_algorithm(self):
        self.utils.stats()

    def market_open(self):
        holding_symbols: list[Symbol] = [
            holding.symbol for holding in self.portfolio.values()
            if holding.quantity != 0
        ]
        if holding_symbols != self.picked[self.time.year]:
            self.set_holdings(self.picked[self.time.year], 1.0, liquidate_existing_holdings=True)
# region imports
from AlgorithmImports import *
# endregion

class CustomSecurityInitializer(BrokerageModelSecurityInitializer):

    def __init__(self, brokerage_model: IBrokerageModel, security_seeder: ISecuritySeeder) -> None:
        super().__init__(brokerage_model, security_seeder)

    def initialize(self, security: Security) -> None:
        super().initialize(security)
        
        security.set_slippage_model(VolumeShareSlippageModel())
        security.set_settlement_model(ImmediateSettlementModel())
        security.set_leverage(1.0)
        security.set_buying_power_model(CashBuyingPowerModel())
        security.set_fee_model(InteractiveBrokersFeeModel())
        security.set_margin_model(SecurityMarginModel.NULL)
from AlgorithmImports import *

from Newtonsoft.Json import JsonConvert
import System
import psutil

class Utils():
    def __init__(self, algo, ticker):
        self.algo = algo
        self.ticker = ticker
        self.mkt = []
        self.insights_key = f"{self.algo.project_id}/Live_{self.algo.live_mode}_insights"
        self.algo.set_benchmark(ticker)

        self._initial_portfolio_value = self.algo.init_cash
        self._initial_benchmark_price = 0
        self._portfolio_high_watermark = 0

        self.init_chart()

    def init_chart(self):
        chart_name = "Strategy Performance"
        chart = Chart(chart_name)

        strategy_series = Series("Strategy", SeriesType.LINE, 0, "$")
        strategy_series.color = Color.ORANGE
        chart.add_series(strategy_series)

        benchmark_series = Series("Benchmark", SeriesType.LINE, 0, "$")
        benchmark_series.color = Color.LIGHT_GRAY
        chart.add_series(benchmark_series)

        drawdown_series = Series("Drawdown", SeriesType.LINE, 1, "%")
        drawdown_series.color = Color.INDIAN_RED
        chart.add_series(drawdown_series)

        allocation_series = Series("Allocation", SeriesType.LINE, 2, "%")
        allocation_series.color = Color.CORNFLOWER_BLUE
        chart.add_series(allocation_series)

        holding_series = Series("Holdings", SeriesType.LINE, 3, "")
        holding_series.color = Color.YELLOW_GREEN
        chart.add_series(holding_series)

        self.algo.add_chart(chart)

    def plot(self):
        if self.algo.live_mode or self.algo.is_warming_up:
            return


        # Capture initial reference values
        if self._initial_portfolio_value == 0.0:
            self._initial_portfolio_value = float(self.algo.portfolio.total_portfolio_value)

        benchmark_price = float(self.algo.securities[self.algo._symbol].price)
        if self._initial_benchmark_price == 0.0 and benchmark_price > 0.0:
            self._initial_benchmark_price = benchmark_price

        # Ensure both initial values are set
        if self._initial_portfolio_value == 0.0 or self._initial_benchmark_price == 0.0:
            return

        # Current values
        current_portfolio_value = float(self.algo.portfolio.total_portfolio_value)

        # Defensive check (avoid division by zero)
        if self._initial_portfolio_value == 0.0 or self._initial_benchmark_price == 0.0:
            return

        # Normalize (start at 1.0)
        normalized_portfolio = current_portfolio_value / self._initial_portfolio_value
        normalized_benchmark = benchmark_price / self._initial_benchmark_price

        current_value = self.algo.portfolio.total_portfolio_value

        if current_value > self._portfolio_high_watermark:
            self._portfolio_high_watermark = current_value

        drawdown = 0.0

        if self._portfolio_high_watermark != 0.0:
            drawdown = (current_value - self._portfolio_high_watermark) / self._portfolio_high_watermark * 100.0

        holding_count = 0

        for symbol in list(self.algo.securities.keys()):
            if symbol is None:
                continue
            holding = self.algo.portfolio[symbol]
            if holding is None or not holding.invested:
                continue

            holding_count += 1

        chart_name = "Strategy Performance"
        self.algo.plot(chart_name, "Drawdown", drawdown)
        self.algo.plot(chart_name, "Strategy", normalized_portfolio*self.algo.init_cash)
        self.algo.plot(chart_name, "Benchmark", normalized_benchmark*self.algo.init_cash)
        self.algo.plot(chart_name, "Allocation", round(self.algo.portfolio.total_holdings_value / self.algo.portfolio.total_portfolio_value,2)*100)
        self.algo.plot(chart_name, "Holdings", holding_count)

        self.algo.plot('Strategy Equity', self.ticker, normalized_benchmark*self.algo.init_cash)

    def pctc(no1, no2):
        return((float(str(no2))-float(str(no1)))/float(str(no1)))


    def stats(self):
        df = None
        trades = self.algo.trade_builder.closed_trades
        for trade in trades:
            data = {
                'symbol': trade.symbol,
                'time': trade.entry_time,
                'entry_price': trade.entry_price,
                'exit_price': trade.exit_price,
                'pnl': trade.profit_loss,
                'pnl_pct': (trade.exit_price - trade.entry_price)/trade.entry_price,
            }
            df = pd.concat([pd.DataFrame(data=data, index=[0]), df])
        
        if df is not None:
            profit = df.query('pnl >= 0')['pnl'].sum()
            loss = df.query('pnl < 0')['pnl'].sum()

            avgWinPercentPerWin = "{0:.2%}".format(df.query('pnl >= 0')['pnl_pct'].mean())
            avgLostPercentPerLost = "{0:.2%}".format(df.query('pnl < 0')['pnl_pct'].mean())
            maxLost = "{0:.2%}".format(df.query('pnl < 0')['pnl_pct'].min())
            maxWin = "{0:.2%}".format(df.query('pnl > 0')['pnl_pct'].max())
            
            self.algo.set_summary_statistic("*Profit Ratio", round(profit / abs(loss),2))
            self.algo.set_summary_statistic("Avg. Win% Per Winner", avgWinPercentPerWin)
            self.algo.set_summary_statistic("Avg. Lost% Per Losser", avgLostPercentPerLost)
            self.algo.set_summary_statistic("Max Loss%", maxLost)
            self.algo.set_summary_statistic("Max Win%", maxWin)


    def read_insight(self):
        if self.algo.object_store.contains_key(self.insights_key) and self.algo.live_mode:
            insights = self.algo.object_store.read_json[System.Collections.Generic.List[Insight]](self.insights_key)
            self.algo.log.debug(f"Read {len(insights)} insight(s) from the Object Store")
            self.algo.insights.add_range(insights)
            
            #self.algo.object_store.delete(self.insights_key)

    def store_insight(self):
        if self.algo.live_mode:
            insights = self.algo.insights.get_insights(lambda x: x.is_active(self.algo.utc_time))
            # If we want to save all insights (expired and active), we can use
            # insights = self.insights.get_insights(lambda x: True)

            self.algo.log.debug(f"Save {len(insights)} insight(s) to the Object Store.")
            content = ','.join([JsonConvert.SerializeObject(x) for x in insights])
            self.algo.object_store.save(self.insights_key, f'[{content}]')

    
    def trace_memory(self, name):
        self.algo.log.debug(f"[{name}] RAM memory % used: {psutil.virtual_memory()[2]} / RAM Used (GB): {round(psutil.virtual_memory()[3]/1000000000,2)}")