18 using System.Collections.Concurrent;
19 using System.Collections.Generic;
20 using System.Diagnostics;
23 using Newtonsoft.Json;
43 private DateTime _testStartTime;
44 private DateTime _lastRuntimeStatisticsDate;
46 private TextWriter _writer;
47 private readonly
object _sync =
new object();
48 private readonly ConcurrentQueue<string> _preInitializeLines;
49 private readonly Dictionary<string, string> _currentRuntimeStatistics;
50 private readonly Dictionary<string, string> _currentAlphaRuntimeStatistics;
54 private static readonly
bool HighFidelityLogging =
Config.
GetBool(
"regression-high-fidelity-logging",
false);
56 private static readonly
bool IsTest = !Process.GetCurrentProcess().ProcessName.Contains(
"Lean.Launcher");
62 ? $
"./regression/{AlgorithmId}.{Language.ToLower()}.details.log"
63 : $
"./{AlgorithmId}/{DateTime.Now:yyyy-MM-dd-hh-mm-ss}.{Language.ToLower()}.details.log";
75 _testStartTime = DateTime.UtcNow;
76 _preInitializeLines =
new ConcurrentQueue<string>();
77 _currentRuntimeStatistics =
new Dictionary<string, string>();
78 _currentAlphaRuntimeStatistics =
new Dictionary<string, string>();
86 base.SetAlgorithm(algorithm, startingPortfolioValue);
89 Directory.CreateDirectory(fileInfo.DirectoryName);
98 WriteLine($
"{_testStartTime}: Starting regression test");
101 while (_preInitializeLines.TryDequeue(out line))
115 WriteLine($
"{Algorithm.UtcTime}: Total Portfolio Value: {Algorithm.Portfolio.TotalPortfolioValue}");
118 WriteLine($
"{Environment.NewLine}{Algorithm.Portfolio.CashBook}");
122 var symbol = kvp.Key;
123 var security = kvp.Value;
124 if (!security.HoldStock)
131 $
"{Algorithm.UtcTime}: " +
132 $
"Holdings: {symbol.Value} ({symbol.ID}): " +
133 $
"Price: {security.Price} " +
134 $
"Quantity: {security.Holdings.Quantity} " +
135 $
"Value: {security.Holdings.HoldingsValue} " +
136 $
"LastData: {security.GetLastData()}"
141 base.SamplePerformance(time, value);
156 WriteLine(
"==============================================================");
157 WriteLine($
" Symbol: {order.Symbol}");
158 WriteLine($
" Order: {order}");
159 WriteLine($
" Event: {newEvent}");
160 WriteLine($
" Position: {Algorithm.Portfolio[newEvent.Symbol].Quantity}");
164 WriteLine($
"Underlying: {underlyingHolding.Quantity}");
166 WriteLine($
" Cash: {Algorithm.Portfolio.Cash:0.00}");
167 WriteLine($
" Portfolio: {Algorithm.Portfolio.TotalPortfolioValue:0.00}");
168 WriteLine(
"==============================================================");
171 base.OrderEvent(newEvent);
179 base.SecurityType(types);
181 var sorted = types.Select(type => type.ToString()).OrderBy(type => type);
182 WriteLine($
"SecurityTypes: {string.Join("|
", sorted)}");
191 base.DebugMessage(message);
193 WriteLine($
"DebugMessage: {message}");
201 public override void ErrorMessage(
string message,
string stacktrace =
"")
203 base.ErrorMessage(message, stacktrace);
205 stacktrace =
string.IsNullOrEmpty(stacktrace) ? null : Environment.NewLine + stacktrace;
206 WriteLine($
"ErrorMessage: {message}{stacktrace}");
215 base.LogMessage(message);
217 WriteLine($
"LogMessage: {message}");
225 public override void RuntimeError(
string message,
string stacktrace =
"")
228 base.RuntimeError(message, stacktrace);
230 stacktrace =
string.IsNullOrEmpty(stacktrace) ? null : Environment.NewLine + stacktrace;
231 WriteLine($
"RuntimeError: {message}{stacktrace}");
240 base.SystemDebugMessage(message);
242 WriteLine($
"SystemDebugMessage: {message}");
255 if (HighFidelityLogging || _lastRuntimeStatisticsDate !=
Algorithm.
Time.Date)
259 string existingValue;
260 if (!_currentRuntimeStatistics.TryGetValue(key, out existingValue) || existingValue != value)
262 _currentRuntimeStatistics[key] = value;
263 WriteLine($
"RuntimeStatistic: {key}: {value}");
267 base.RuntimeStatistic(key, value);
269 catch (Exception exception)
281 base.AddToLogStore(message);
283 WriteLine($
"AddToLogStore: {message}");
291 base.OnSecuritiesChanged(changes);
296 .Select(security => security.Symbol.ToString())
297 .OrderBy(symbol => symbol);
299 WriteLine($
"OnSecuritiesChanged:ADD: {string.Join("|
", added)}");
305 .Select(security => security.Symbol.ToString())
306 .OrderBy(symbol => symbol);
308 WriteLine($
"OnSecuritiesChanged:REM: {string.Join("|
", removed)}");
318 if (HighFidelityLogging)
326 WriteLine($
"Slice Time: {slice.Time:o} Slice Count: {slice.Count}");
327 var data =
new Dictionary<Symbol, List<BaseData>>();
328 foreach (var kvp
in slice.Bars)
330 data.Add(kvp.Key, (
BaseData) kvp.Value);
333 foreach (var kvp
in slice.QuoteBars)
335 data.Add(kvp.Key, (
BaseData)kvp.Value);
338 foreach (var kvp
in slice.Ticks)
340 foreach (var tick
in kvp.Value)
346 foreach (var kvp
in slice.Delistings)
348 data.Add(kvp.Key, (
BaseData) kvp.Value);
351 foreach (var kvp
in slice.Splits)
353 data.Add(kvp.Key, (
BaseData) kvp.Value);
356 foreach (var kvp
in slice.SymbolChangedEvents)
358 data.Add(kvp.Key, (
BaseData) kvp.Value);
361 foreach (var kvp
in slice.Dividends)
363 data.Add(kvp.Key, (
BaseData) kvp.Value);
366 foreach (var kvp
in data.OrderBy(kvp => kvp.Key))
368 foreach (var item
in kvp.Value)
370 WriteLine($
"{Algorithm.UtcTime}: Slice: DataTime: {item.EndTime} {item}");
377 base.ProcessSynchronousEvents(forceProcess);
385 File.WriteAllText(
GetResultsPath(name), JsonConvert.SerializeObject(result));
396 var holdings =
Algorithm.
Portfolio.
Values.Where(holding => holding.Invested).Select(holding => $
"HOLDINGS:: {holding}").ToList();
397 if(holdings.Count > 0)
399 Log.
Trace($
"{Environment.NewLine}{string.Join(Environment.NewLine, holdings)}");
405 Log.
Trace($
"{Environment.NewLine}{Algorithm.Portfolio.CashBook}");
416 WriteLine($
"{kvp.Key,-15}\t{kvp.Value}");
419 var end = DateTime.UtcNow;
420 var delta = end - _testStartTime;
421 WriteLine($
"{end}: Completed regression test, took: {delta.TotalSeconds:0.0} seconds");
422 _writer.DisposeSafely();
428 while (_preInitializeLines.TryDequeue(out line))
430 Console.WriteLine(line);
451 algorithm.
Debug(msg);
452 WriteLine($
"DEBUG: {msg}");
456 algorithm.
Error(msg);
457 WriteLine($
"ERROR: {msg}");
466 WriteLine($
"DEBUG: {msg}");
471 WriteLine($
"ERROR: {msg}");
476 private void WriteLine(
string message)
487 _preInitializeLines.Enqueue(message);
491 _writer.WriteLine($
"{Algorithm.Time:O}: {message}");