F-Score Reversal
Trading rules
At each monthly review calculate Lookback-day return P[d] / P[d−Lookback] − 1. Among published FScore >= FHi buy the lowest return; if IsShortEnabled, among FScore <= FLo short the highest return. Thresholds are inclusive and FHi must exceed FLo. Scores are genuine published Piotroski inputs, integers 0..9, with the latest known period/revision and MaxReportAgeDays limit. Each selected leg receives half the gross budget; a missing or disabled side stays in cash. Close the whole old portfolio and wait for fills before opening the new monthly legs.
Evaluate only synchronized finished candles. Statistics count distinct UTC dates, replacing earlier intraday closes of the same date. Rebalance once on the first eligible synchronized candle of each month; an unformed input delays the decision. Equal scores are ordered by Security.Id.
All observations must be published by the signal candle close. Intraday execution uses daily prices strictly before its UTC date; a finished one-day candle contributes its own completed date. Never warm a decision with future CSV dates.
The publication cutoff is the latest actual CloseTime among synchronized finished candles. A trading session can finish before the configured candle interval has elapsed.
Input data
PriceHistoryFile is an optional CSV of positive daily closes: SecurityId,Date,Close. Dates use yyyy-MM-dd. Current and future dates cannot prefill a decision; live finished closes replace each UTC date. Duplicate dates are rejected. It is needed to warm long lookbacks when the execution archive is short.
FScoreFile is required CSV: SecurityId,PeriodEnd,PublishedAt,FScore. PeriodEnd is yyyy-MM-dd, PublishedAt is UTC yyyy-MM-ddTHH:mm:ssZ. Reject scores outside integer 0..9, duplicate revisions and publications before PeriodEnd. Choose the newest fiscal period and its latest published revision; MaxReportAgeDays counts from PeriodEnd.
Parameters
| Parameter | Default |
|---|---|
Universe |
required |
Capital |
100000 |
Leverage |
1 |
MinTradeUsd |
100 |
CandleType |
TimeSpan.FromDays(1).TimeFrame() |
PriceHistoryFile |
optional — not supplied |
Lookback |
21 |
FHi |
7 |
FLo |
3 |
IsShortEnabled |
true |
MaxReportAgeDays |
550 |
FScoreFile |
required |
Execution
Set Universe explicitly. Prices and Capital use USD, with one price unit per traded unit. Capital is a fixed budget; Leverage controls gross exposure. No stop loss or take profit is added.
Round target quantities toward zero to VolumeStep. Wait for actual liquidation fills before opening new positions; reconcile actual positions, respect MinVolume/MaxVolume and split large adjustments across later candles. MinTradeUsd filters nonzero target adjustments, while full liquidation bypasses it.
Verification
Tests run both languages using packaged BTC/TON execution data and explicit rate, financial, score, text and warmup fixtures. Calendar fixtures relocate archive OHLC/volume and provide deterministic execution quotes; they are not multi-year market history. Independent formulas, order direction/size, actual fills, residual positions and forbidden decision dates are checked. Two buckets, K=1 and AssetDecile=1 are declared mechanics profiles, not evidence of the complete production universe. No profitability claim is made.
namespace StockSharp.Samples.Strategies;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Ecng.Common;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>F-Score Reversal with point-in-time inputs and execution-based portfolio accounting.</summary>
public class FScoreReversalStrategy : Strategy
{
private readonly StrategyParam<IEnumerable<Security>> _universe;
private readonly StrategyParam<decimal> _capital;
private readonly StrategyParam<decimal> _leverage;
private readonly StrategyParam<decimal> _minTradeUsd;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<string> _priceHistoryFile;
private readonly StrategyParam<int> _lookback;
private readonly StrategyParam<int> _fHi;
private readonly StrategyParam<int> _fLo;
private readonly StrategyParam<bool> _isShortEnabled;
private readonly StrategyParam<int> _maxReportAgeDays;
private readonly StrategyParam<string> _fScoreFile;
private Security[] _securities = [];
private readonly Dictionary<Security, (DateTime time, decimal price, DateTime closed)> _latest = [];
private readonly Dictionary<Security, SortedDictionary<DateTime, decimal>> _history = [];
private readonly Dictionary<Security, decimal> _targets = [];
private readonly List<Order> _pending = [];
private int _lastRebalance;
private DateTime? _lastBar;
private readonly Dictionary<Security, decimal> _nextTargets = [];
private bool _isRotating;
private bool _isReconciling;
private sealed record Score(Security Security, DateTime Period, DateTime Published, int Value);
private readonly List<Score> _scores = [];
/// <summary>Explicit execution securities with valid native volume metadata.</summary>
public IEnumerable<Security> Universe { get => _universe.Value; set => _universe.Value = value; }
/// <summary>Fixed capital budget in USD.</summary>
public decimal Capital { get => _capital.Value; set => _capital.Value = value; }
/// <summary>Gross target exposure divided by the capital budget.</summary>
public decimal Leverage { get => _leverage.Value; set => _leverage.Value = value; }
/// <summary>Minimum USD adjustment; complete liquidation bypasses this filter.</summary>
public decimal MinTradeUsd { get => _minTradeUsd.Value; set => _minTradeUsd.Value = value; }
/// <summary>Finished execution candle type.</summary>
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
/// <summary>Optional daily close CSV; future dates cannot prefill a decision.</summary>
public string PriceHistoryFile { get => _priceHistoryFile.Value; set => _priceHistoryFile.Value = value; }
/// <summary>Completed daily returns in the reversal window.</summary>
public int Lookback { get => _lookback.Value; set => _lookback.Value = value; }
/// <summary>Inclusive minimum published Piotroski score for the long leg.</summary>
public int FHi { get => _fHi.Value; set => _fHi.Value = value; }
/// <summary>Inclusive maximum published Piotroski score for the short leg.</summary>
public int FLo { get => _fLo.Value; set => _fLo.Value = value; }
/// <summary>Whether to allocate the optional weak-score short leg.</summary>
public bool IsShortEnabled { get => _isShortEnabled.Value; set => _isShortEnabled.Value = value; }
/// <summary>Maximum age of the latest fiscal report in calendar days.</summary>
public int MaxReportAgeDays { get => _maxReportAgeDays.Value; set => _maxReportAgeDays.Value = value; }
/// <summary>Required published integer Piotroski scores from zero through nine.</summary>
public string FScoreFile { get => _fScoreFile.Value; set => _fScoreFile.Value = value; }
/// <summary>Initialize the strategy parameters.</summary>
public FScoreReversalStrategy()
{
_universe = Param<IEnumerable<Security>>(nameof(Universe)).SetRequired()
.SetDisplay("Universe", "Explicit execution securities with valid native volume metadata", "Parameters");
_capital = Param(nameof(Capital), 100000m).SetGreaterThanZero()
.SetDisplay("Capital", "Fixed capital budget in USD", "Parameters");
_leverage = Param(nameof(Leverage), 1m).SetGreaterThanZero()
.SetDisplay("Leverage", "Gross target exposure divided by the capital budget", "Parameters");
_minTradeUsd = Param(nameof(MinTradeUsd), 100m).SetRange(0m, decimal.MaxValue)
.SetDisplay("MinTradeUsd", "Minimum USD adjustment; complete liquidation bypasses this filter", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1440).TimeFrame())
.SetDisplay("CandleType", "Finished execution candle type", "Parameters");
_priceHistoryFile = Param<string>(nameof(PriceHistoryFile))
.SetDisplay("PriceHistoryFile", "Optional daily close CSV; future dates cannot prefill a decision", "Parameters");
_lookback = Param(nameof(Lookback), 21).SetRange(1, int.MaxValue)
.SetDisplay("Lookback", "Completed daily returns in the reversal window", "Parameters");
_fHi = Param(nameof(FHi), 7).SetRange(0, 9)
.SetDisplay("FHi", "Inclusive minimum published Piotroski score for the long leg", "Parameters");
_fLo = Param(nameof(FLo), 3).SetRange(0, 9)
.SetDisplay("FLo", "Inclusive maximum published Piotroski score for the short leg", "Parameters");
_isShortEnabled = Param(nameof(IsShortEnabled), true)
.SetDisplay("IsShortEnabled", "Whether to allocate the optional weak-score short leg", "Parameters");
_maxReportAgeDays = Param(nameof(MaxReportAgeDays), 550).SetRange(1, int.MaxValue)
.SetDisplay("MaxReportAgeDays", "Maximum age of the latest fiscal report in calendar days", "Parameters");
_fScoreFile = Param<string>(nameof(FScoreFile)).SetRequired()
.SetDisplay("FScoreFile", "Required published integer Piotroski scores from zero through nine", "Parameters");
Trades.TradeAdded += _ => ContinueRotation();
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> (Universe ?? []).Where(s => s is not null).DistinctBy(s => s.Id, StringComparer.OrdinalIgnoreCase).Select(s => (s, CandleType));
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_securities = [];
_latest.Clear();
_history.Clear();
_targets.Clear();
_pending.Clear();
_lastRebalance = 0;
_lastBar = null;
_nextTargets.Clear();
_isRotating = false;
_isReconciling = false;
_scores.Clear();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
_securities = (Universe ?? []).ToArray();
if (_securities.Length == 0 || _securities.Any(s => s is null || string.IsNullOrWhiteSpace(s.Id))
|| _securities.Select(s => s.Id).Distinct(StringComparer.OrdinalIgnoreCase).Count() != _securities.Length)
throw new InvalidOperationException("Universe must contain distinct execution securities.");
foreach (var security in _securities)
{
if (security.VolumeStep is not > 0m || security.MinVolume is not > 0m || security.MaxVolume is not > 0m)
throw new InvalidOperationException("Every security needs positive VolumeStep, MinVolume and MaxVolume.");
_history[security] = [];
}
LoadPriceHistory();
if (FHi <= FLo) throw new InvalidOperationException("FHi must be greater than FLo.");
LoadScores();
base.OnStarted2(time);
foreach (var security in _securities)
SubscribeCandles(CandleType, security: security).Bind(candle => ProcessCandle(security, candle)).Start();
}
private void ProcessCandle(Security security, ICandleMessage candle)
{
if (candle.State != CandleStates.Finished || candle.ClosePrice <= 0m) return;
_latest[security] = (candle.OpenTime, candle.ClosePrice, candle.CloseTime);
_history[security][candle.OpenTime.Date] = candle.ClosePrice;
if (_latest.Count != _securities.Length || _latest.Values.Any(v => v.time != candle.OpenTime)
|| _lastBar == candle.OpenTime || !IsFormedAndOnlineAndAllowTrading()) return;
_lastBar = candle.OpenTime;
var month = candle.OpenTime.Year * 100 + candle.OpenTime.Month;
if (!_isRotating && _lastRebalance != month && SelectTargets(candle.OpenTime, _latest.Values.Max(v => v.closed)))
_lastRebalance = month;
ReconcileTargets();
}
private decimal Budget => Capital * Leverage;
private decimal UnitPrice(Security security) => _latest[security].price;
private decimal Units(Security security, decimal notional)
=> Math.Floor(notional / UnitPrice(security) / security.VolumeStep.Value) * security.VolumeStep.Value;
private void ReconcileTargets()
{
if (_isReconciling) return;
if (_pending.Any(o => o.State is not (OrderStates.Done or OrderStates.Failed))) return;
_pending.Clear();
_isReconciling = true;
try
{
foreach (var security in _securities)
{
if (!_targets.TryGetValue(security, out var target)) continue;
var delta = target - GetPositionValue(security, Portfolio).GetValueOrDefault();
if (delta == 0m || (target != 0m && Math.Abs(delta) * UnitPrice(security) < MinTradeUsd)) continue;
var step = security.VolumeStep.Value;
var quantity = Math.Floor(Math.Min(Math.Abs(delta), security.MaxVolume.Value) / step) * step;
if (quantity < security.MinVolume.Value) continue;
var order = new Order
{
Security = security, Portfolio = Portfolio, Type = OrderTypes.Market,
Side = delta > 0m ? Sides.Buy : Sides.Sell, Volume = quantity, Comment = "0373Rebalance",
};
_pending.Add(order);
RegisterOrder(order);
}
}
finally
{
_isReconciling = false;
}
ContinueRotation();
}
private void BeginRotation(Dictionary<Security, decimal> targets)
{
_nextTargets.Clear();
foreach (var target in targets) _nextTargets[target.Key] = target.Value;
foreach (var security in _securities) _targets[security] = 0m;
_isRotating = true;
}
private void ContinueRotation()
{
if (!_isRotating || _isReconciling || !IsFormedAndOnlineAndAllowTrading()
|| _pending.Any(o => o.State is not (OrderStates.Done or OrderStates.Failed))
|| _securities.Any(s => GetPositionValue(s, Portfolio).GetValueOrDefault() != 0m)) return;
_isRotating = false;
foreach (var security in _securities) _targets[security] = _nextTargets.GetValueOrDefault(security);
_nextTargets.Clear();
ReconcileTargets();
}
private static DateTime ParseUtc(string value)
=> DateTime.ParseExact(value.Trim(), "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
private static IEnumerable<string[]> ReadRows(string path, string header, int fields)
{
using var lines = File.ReadLines(path).GetEnumerator();
if (!lines.MoveNext() || lines.Current.Trim() != header)
throw new InvalidOperationException("Invalid CSV header: expected " + header + ".");
while (lines.MoveNext())
{
if (string.IsNullOrWhiteSpace(lines.Current)) continue;
var row = lines.Current.Split(',');
if (row.Length != fields) throw new InvalidOperationException("Invalid CSV field count.");
yield return row;
}
}
private DateTime LastClosedDate(DateTime time)
=> CandleType.Arg is TimeSpan frame && frame == TimeSpan.FromDays(1) ? time.Date : time.Date.AddDays(-1);
private decimal[] Daily(Security security, DateTime time, int count, DateTime cutoff)
=> _history[security].Where(x => x.Key <= LastClosedDate(time) && x.Key < cutoff).Select(x => x.Value).TakeLast(count).ToArray();
private void LoadPriceHistory()
{
if (string.IsNullOrWhiteSpace(PriceHistoryFile)) return;
foreach (var row in ReadRows(PriceHistoryFile, "SecurityId,Date,Close", 3))
{
var security = _securities.SingleOrDefault(s => string.Equals(s.Id, row[0].Trim(), StringComparison.OrdinalIgnoreCase));
if (security is null) continue;
var date = DateTime.ParseExact(row[1].Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
var price = decimal.Parse(row[2], CultureInfo.InvariantCulture);
if (price <= 0m || !_history[security].TryAdd(date, price))
throw new InvalidOperationException("Daily prices must be positive and unique per security and UTC date.");
}
}
private void LoadScores()
{
var keys = new HashSet<(Security, DateTime, DateTime)>();
foreach (var row in ReadRows(FScoreFile, "SecurityId,PeriodEnd,PublishedAt,FScore", 4))
{
var security = _securities.SingleOrDefault(s => string.Equals(s.Id, row[0].Trim(), StringComparison.OrdinalIgnoreCase));
if (security is null) continue;
var period = DateTime.ParseExact(row[1].Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture);
var published = ParseUtc(row[2]);
var score = int.Parse(row[3], CultureInfo.InvariantCulture);
if (score is < 0 or > 9 || published.Date < period || !keys.Add((security, period, published)))
throw new InvalidOperationException("Piotroski scores must be integers 0..9 with causal, unique publication dates.");
_scores.Add(new(security, period, published, score));
}
}
private bool SelectTargets(DateTime time, DateTime asOf)
{
var candidates = new List<(Security security, int score, decimal momentum)>();
foreach (var security in _securities)
{
var report = _scores.Where(r => r.Security == security && r.Published <= asOf)
.OrderByDescending(r => r.Period).ThenByDescending(r => r.Published).FirstOrDefault();
var prices = Daily(security, time, Lookback + 1, DateTime.MaxValue);
if (report is null || (time.Date - report.Period).TotalDays > MaxReportAgeDays || prices.Length != Lookback + 1) continue;
candidates.Add((security, report.Value, prices[^1] / prices[0] - 1m));
}
if (candidates.Count == 0) return false;
var longLeg = candidates.Where(x => x.score >= FHi).OrderBy(x => x.momentum).ThenBy(x => x.security.Id, StringComparer.Ordinal).FirstOrDefault().security;
var shortLeg = IsShortEnabled ? candidates.Where(x => x.score <= FLo).OrderByDescending(x => x.momentum).ThenBy(x => x.security.Id, StringComparer.Ordinal).FirstOrDefault().security : null;
var targets = new Dictionary<Security, decimal>();
if (longLeg is not null) targets[longLeg] = Units(longLeg, Budget / 2m);
if (shortLeg is not null) targets[shortLeg] = -Units(shortLeg, Budget / 2m);
BeginRotation(targets);
return true;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.BusinessEntities")
clr.AddReference("StockSharp.Algo.Strategies")
from System import Boolean, DateTime, Decimal, Int32, Math, TimeSpan, InvalidOperationException
from System.Collections.Generic import IEnumerable
from System.Globalization import CultureInfo, DateTimeStyles
from System.IO import File, Path
from StockSharp.Algo.Strategies import Strategy
from StockSharp.BusinessEntities import Order, Security
from StockSharp.Messages import CandleStates, DataType, OrderStates, OrderTypes, Sides
class fscore_reversal_strategy(Strategy):
"""F-Score Reversal with point-in-time inputs and execution-based portfolio accounting."""
def __init__(self):
super(fscore_reversal_strategy, self).__init__()
self._universe = self.Param[IEnumerable[Security]]("Universe", None).SetRequired() \
.SetDisplay("Universe", "Explicit execution securities with valid native volume metadata", "Parameters")
self._capital = self.Param("Capital", Decimal(100000)).SetGreaterThanZero() \
.SetDisplay("Capital", "Fixed capital budget in USD", "Parameters")
self._leverage = self.Param("Leverage", Decimal(1)).SetGreaterThanZero() \
.SetDisplay("Leverage", "Gross target exposure divided by the capital budget", "Parameters")
self._min_trade_usd = self.Param("MinTradeUsd", Decimal(100)).SetRange(Decimal(0), Decimal.MaxValue) \
.SetDisplay("MinTradeUsd", "Minimum USD adjustment; complete liquidation bypasses this filter", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1440))) \
.SetDisplay("CandleType", "Finished execution candle type", "Parameters")
self._price_history_file = self.Param[str]("PriceHistoryFile", None) \
.SetDisplay("PriceHistoryFile", "Optional daily close CSV; future dates cannot prefill a decision", "Parameters")
self._lookback = self.Param("Lookback", 21).SetRange(1, 2147483647) \
.SetDisplay("Lookback", "Completed daily returns in the reversal window", "Parameters")
self._fhi = self.Param("FHi", 7).SetRange(0, 9) \
.SetDisplay("FHi", "Inclusive minimum published Piotroski score for the long leg", "Parameters")
self._flo = self.Param("FLo", 3).SetRange(0, 9) \
.SetDisplay("FLo", "Inclusive maximum published Piotroski score for the short leg", "Parameters")
self._is_short_enabled = self.Param("IsShortEnabled", True) \
.SetDisplay("IsShortEnabled", "Whether to allocate the optional weak-score short leg", "Parameters")
self._max_report_age_days = self.Param("MaxReportAgeDays", 550).SetRange(1, 2147483647) \
.SetDisplay("MaxReportAgeDays", "Maximum age of the latest fiscal report in calendar days", "Parameters")
self._fscore_file = self.Param[str]("FScoreFile", None).SetRequired() \
.SetDisplay("FScoreFile", "Required published integer Piotroski scores from zero through nine", "Parameters")
self._clear_state()
self.Trades.TradeAdded += self._on_trade
def _clear_state(self):
self._securities = []
self._latest = {}
self._history = {}
self._targets = {}
self._pending = []
self._last_rebalance = 0
self._last_bar = None
self._next_targets = {}
self._is_rotating = False
self._is_reconciling = False
self._scores = []
@property
def Universe(self):
return self._universe.Value
@Universe.setter
def Universe(self, value):
self._universe.Value = value
@property
def Capital(self):
return self._capital.Value
@Capital.setter
def Capital(self, value):
self._capital.Value = value
@property
def Leverage(self):
return self._leverage.Value
@Leverage.setter
def Leverage(self, value):
self._leverage.Value = value
@property
def MinTradeUsd(self):
return self._min_trade_usd.Value
@MinTradeUsd.setter
def MinTradeUsd(self, value):
self._min_trade_usd.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def PriceHistoryFile(self):
return self._price_history_file.Value
@PriceHistoryFile.setter
def PriceHistoryFile(self, value):
self._price_history_file.Value = value
@property
def Lookback(self):
return self._lookback.Value
@Lookback.setter
def Lookback(self, value):
self._lookback.Value = value
@property
def FHi(self):
return self._fhi.Value
@FHi.setter
def FHi(self, value):
self._fhi.Value = value
@property
def FLo(self):
return self._flo.Value
@FLo.setter
def FLo(self, value):
self._flo.Value = value
@property
def IsShortEnabled(self):
return self._is_short_enabled.Value
@IsShortEnabled.setter
def IsShortEnabled(self, value):
self._is_short_enabled.Value = value
@property
def MaxReportAgeDays(self):
return self._max_report_age_days.Value
@MaxReportAgeDays.setter
def MaxReportAgeDays(self, value):
self._max_report_age_days.Value = value
@property
def FScoreFile(self):
return self._fscore_file.Value
@FScoreFile.setter
def FScoreFile(self, value):
self._fscore_file.Value = value
def GetWorkingSecurities(self):
return [(s, self.CandleType) for s in self.Universe] if self.Universe is not None else []
def OnReseted(self):
super(fscore_reversal_strategy, self).OnReseted()
self._clear_state()
def OnStarted2(self, time):
self._securities = list(self.Universe) if self.Universe is not None else []
if not self._securities or any(s is None or not s.Id for s in self._securities) or len(set(s.Id.upper() for s in self._securities)) != len(self._securities):
raise InvalidOperationException("Universe must contain distinct execution securities.")
for security in self._securities:
if security.VolumeStep is None or security.MinVolume is None or security.MaxVolume is None or security.VolumeStep <= 0 or security.MinVolume <= 0 or security.MaxVolume <= 0:
raise InvalidOperationException("Every security needs positive VolumeStep, MinVolume and MaxVolume.")
self._history[security] = {}
self._load_price_history()
if self.FHi <= self.FLo:
raise InvalidOperationException("FHi must be greater than FLo.")
self._load_scores()
super(fscore_reversal_strategy, self).OnStarted2(time)
for security in self._securities:
self.SubscribeCandles(self.CandleType, True, security).Bind(lambda candle, s=security: self._process_candle(s, candle)).Start()
def _process_candle(self, security, candle):
if candle.State != CandleStates.Finished or candle.ClosePrice <= 0:
return
self._latest[security] = (candle.OpenTime, candle.ClosePrice, candle.CloseTime)
self._history[security][candle.OpenTime.Date] = candle.ClosePrice
if len(self._latest) != len(self._securities) or any(value[0] != candle.OpenTime for value in self._latest.values()) or self._last_bar == candle.OpenTime or not self.IsFormedAndOnlineAndAllowTrading():
return
self._last_bar = candle.OpenTime
month = candle.OpenTime.Year * 100 + candle.OpenTime.Month
if not self._is_rotating and self._last_rebalance != month and self._select_targets(candle.OpenTime, max(value[2] for value in self._latest.values())):
self._last_rebalance = month
self._reconcile_targets()
def _budget(self):
return self.Capital * self.Leverage
def _unit_price(self, security):
return self._latest[security][1]
def _units(self, security, notional):
return Math.Floor(notional / self._unit_price(security) / security.VolumeStep) * security.VolumeStep
def _reconcile_targets(self):
if self._is_reconciling:
return
if any(o.State != OrderStates.Done and o.State != OrderStates.Failed for o in self._pending):
return
self._pending = []
self._is_reconciling = True
try:
for security in self._securities:
if security not in self._targets:
continue
target = self._targets[security]
position = self.GetPositionValue(security, self.Portfolio)
delta = target - (position if position is not None else Decimal(0))
if delta == 0 or (target != 0 and abs(delta) * self._unit_price(security) < self.MinTradeUsd):
continue
quantity = Math.Floor(min(abs(delta), security.MaxVolume) / security.VolumeStep) * security.VolumeStep
if quantity < security.MinVolume:
continue
order = Order()
order.Security = security
order.Portfolio = self.Portfolio
order.Type = OrderTypes.Market
order.Side = Sides.Buy if delta > 0 else Sides.Sell
order.Volume = quantity
order.Comment = "0373Rebalance"
self._pending.append(order)
self.RegisterOrder(order)
finally:
self._is_reconciling = False
self._continue_rotation()
def _begin_rotation(self, targets):
self._next_targets = targets
self._targets = {s: Decimal(0) for s in self._securities}
self._is_rotating = True
def _on_trade(self, trade):
self._continue_rotation()
def _continue_rotation(self):
if not self._is_rotating or self._is_reconciling or not self.IsFormedAndOnlineAndAllowTrading():
return
if any(o.State != OrderStates.Done and o.State != OrderStates.Failed for o in self._pending):
return
if any((self.GetPositionValue(s, self.Portfolio) or Decimal(0)) != 0 for s in self._securities):
return
self._is_rotating = False
self._targets = {s: self._next_targets.get(s, Decimal(0)) for s in self._securities}
self._next_targets = {}
self._reconcile_targets()
@staticmethod
def _parse_utc(value):
return DateTime.ParseExact(value.strip(), "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)
@staticmethod
def _read_rows(path, header, fields):
lines = list(File.ReadLines(path))
if not lines or lines[0].strip() != header:
raise InvalidOperationException("Invalid CSV header: expected " + header + ".")
for line in lines[1:]:
if not line.strip():
continue
row = line.split(",")
if len(row) != fields:
raise InvalidOperationException("Invalid CSV field count.")
yield row
def _last_closed_date(self, time):
return time.Date if self.CandleType.Arg == TimeSpan.FromDays(1) else time.Date.AddDays(-1)
def _daily(self, security, time, count, cutoff):
dates = [d for d in sorted(self._history[security]) if d <= self._last_closed_date(time) and d < cutoff]
return [self._history[security][d] for d in dates[-count:]]
def _load_price_history(self):
if not self.PriceHistoryFile:
return
for row in self._read_rows(self.PriceHistoryFile, "SecurityId,Date,Close", 3):
security = next((s for s in self._securities if s.Id.upper() == row[0].strip().upper()), None)
if security is None:
continue
date = DateTime.ParseExact(row[1].strip(), "yyyy-MM-dd", CultureInfo.InvariantCulture)
price = Decimal.Parse(row[2], CultureInfo.InvariantCulture)
if price <= 0 or date in self._history[security]:
raise InvalidOperationException("Daily prices must be positive and unique per security and UTC date.")
self._history[security][date] = price
def _load_scores(self):
keys = set()
for row in self._read_rows(self.FScoreFile, "SecurityId,PeriodEnd,PublishedAt,FScore", 4):
security = next((s for s in self._securities if s.Id.upper() == row[0].strip().upper()), None)
if security is None:
continue
period = DateTime.ParseExact(row[1].strip(), "yyyy-MM-dd", CultureInfo.InvariantCulture)
published = self._parse_utc(row[2])
score = Int32.Parse(row[3], CultureInfo.InvariantCulture)
key = (security, period, published)
if score < 0 or score > 9 or published.Date < period or key in keys:
raise InvalidOperationException("Piotroski scores must be integers 0..9 with causal, unique publication dates.")
keys.add(key)
self._scores.append((security, period, published, score))
def _select_targets(self, time, as_of):
candidates = []
for security in self._securities:
available = [r for r in self._scores if r[0] == security and r[2] <= as_of]
report = max(available, key=lambda r: (r[1], r[2])) if available else None
prices = self._daily(security, time, self.Lookback + 1, DateTime.MaxValue)
if report is None or (time.Date - report[1]).TotalDays > self.MaxReportAgeDays or len(prices) != self.Lookback + 1:
continue
candidates.append((security, report[3], prices[-1] / prices[0] - Decimal(1)))
if not candidates:
return False
longs = sorted([c for c in candidates if c[1] >= self.FHi], key=lambda c: (c[2], c[0].Id))
shorts = sorted([c for c in candidates if c[1] <= self.FLo], key=lambda c: (-c[2], c[0].Id)) if self.IsShortEnabled else []
targets = {}
if longs:
targets[longs[0][0]] = self._units(longs[0][0], self._budget() / Decimal(2))
if shorts:
targets[shorts[0][0]] = -self._units(shorts[0][0], self._budget() / Decimal(2))
self._begin_rotation(targets)
return True
def CreateClone(self):
return fscore_reversal_strategy()