| Overall Statistics |
|
Total Orders
40767
Average Win
0.35%
Average Loss
-0.25%
Compounding Annual Return
14.785%
Drawdown
52.700%
Expectancy
0.068
Start Equity
100000
End Equity
3336919.50
Net Profit
3236.920%
Sharpe Ratio
0.493
Sortino Ratio
0.596
Probabilistic Sharpe Ratio
0.421%
Loss Rate
55%
Win Rate
45%
Profit-Loss Ratio
1.38
Alpha
0.09
Beta
0.234
Annual Standard Deviation
0.202
Annual Variance
0.041
Information Ratio
0.247
Tracking Error
0.233
Treynor Ratio
0.425
Total Fees
$475947.83
Estimated Strategy Capacity
$94000000.00
Lowest Capacity Asset
LMT R735QTJ8XC9X
Portfolio Turnover
38.26%
|
# https://quantpedia.com/strategies/short-term-reversal-in-stocks/
#
# The investment universe consists of the 100 biggest companies by market capitalization.
# The investor goes long on the ten stocks with the lowest performance in the previous week and
# goes short on the ten stocks with the greatest performance of the prior month. The portfolio is rebalanced weekly.
#
# QC implementation changes:
#region imports
from AlgorithmImports import *
from pandas.core.frame import DataFrame
from typing import List, Dict
#endregion
class ShortTermReversalEffectinStocks(QCAlgorithm):
def Initialize(self) -> None:
self.SetStartDate(2000, 1, 1)
self.SetCash(100000)
market:Symbol = self.AddEquity('SPY', Resolution.Daily).Symbol
self.fundamental_count:int = 100
self.fundamental_sorting_key = lambda x: x.MarketCap
self.period:int = 21
self.week_period:int = 5
self.stock_selection:int = 10
self.leverage:int = 5
self.min_share_price:float = 1.
self.long:List[Symbol] = []
self.short:List[Symbol] = []
# daily close data
self.data:Dict[Symbol, SymbolData] = {}
self.day:int = 1
self.selection_flag:bool = False
self.UniverseSettings.Resolution = Resolution.Daily
self.AddUniverse(self.FundamentalSelectionFunction)
self.Settings.MinimumOrderMarginPortfolioPercentage = 0.
self.Schedule.On(self.DateRules.EveryDay(market), self.TimeRules.AfterMarketOpen(market), self.Selection)
self.settings.daily_precise_end_time = False
def OnSecuritiesChanged(self, changes: SecurityChanges) -> None:
for security in changes.AddedSecurities:
security.SetFeeModel(CustomFeeModel())
security.SetLeverage(self.leverage)
def FundamentalSelectionFunction(self, fundamental: List[Fundamental]) -> List[Symbol]:
# update the rolling window every day
for stock in fundamental:
symbol:Symbol = stock.Symbol
# store monthly price
if symbol in self.data:
self.data[symbol].update(stock.AdjustedPrice)
if not self.selection_flag:
return Universe.Unchanged
selected:List[Fundamental] = [x for x in fundamental if x.HasFundamentalData and x.Market == 'usa' and \
x.Price >= self.min_share_price and x.MarketCap != 0]
if len(selected) > self.fundamental_count:
selected = [x for x in sorted(selected, key=self.fundamental_sorting_key, reverse=True)[:self.fundamental_count]]
month_performances:Dict[Symbol, float] = {}
week_performances:Dict[Symbol, float] = {}
# warmup price rolling windows
for stock in selected:
symbol:Symbol = stock.Symbol
if symbol not in self.data:
self.data[symbol] = SymbolData(self.period+1)
history:DataFrame = self.History(symbol, self.period+1, Resolution.Daily)
if history.empty:
self.Log(f"Not enough data for {symbol} yet")
continue
closes:pd.Series = history.loc[symbol]
for time, row in closes.iterrows():
self.data[symbol].update(row['close'])
if self.data[symbol].is_ready():
month_performances[symbol] = self.data[symbol].performance(self.period)
week_performances[symbol] = self.data[symbol].performance(self.week_period)
if len(month_performances) > self.stock_selection * 2:
sorted_by_week_perf:List[Symbol] = [x[0] for x in sorted(week_performances.items(), key=lambda item: item[1])]
sorted_by_month_perf:List[Symbol] = [x[0] for x in sorted(month_performances.items(), key=lambda item: item[1], reverse=True)]
self.long = sorted_by_week_perf[:self.stock_selection]
self.short = sorted_by_month_perf[:self.stock_selection]
return self.long + self.short
def OnData(self, data: Slice) -> None:
if not self.selection_flag:
return
self.selection_flag = False
# order execution
invested: List[Symbol] = [x.Key for x in self.Portfolio if x.Value.Invested]
for symbol in invested:
if symbol not in self.long + self.short:
self.Liquidate(symbol)
for i, portfolio in enumerate([self.long, self.short]):
for symbol in portfolio:
if symbol in data and data[symbol]:
self.SetHoldings(symbol, ((-1) ** i) / len(portfolio))
self.long.clear()
self.short.clear()
def Selection(self) -> None:
if self.day == 5:
self.selection_flag = True
self.day += 1
if self.day > 5:
self.day = 1
class SymbolData():
def __init__(self, period:float) -> None:
self._daily_close = RollingWindow[float](period)
def update(self, close:float) -> None:
self._daily_close.Add(close)
def is_ready(self) -> bool:
return self._daily_close.IsReady
def performance(self, period:int) -> float:
return self._daily_close[0] / self._daily_close[period] - 1
# Custom fee model
class CustomFeeModel(FeeModel):
def GetOrderFee(self, parameters):
fee = parameters.Security.Price * parameters.Order.AbsoluteQuantity * 0.00005
return OrderFee(CashAmount(fee, "USD"))