forked from QuantConnect/Lean
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuantBook.cs
633 lines (561 loc) · 31.7 KB
/
QuantBook.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Python.Runtime;
using QuantConnect.Algorithm;
using QuantConnect.Configuration;
using QuantConnect.Data;
using QuantConnect.Data.Fundamental;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Securities;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using QuantConnect.Statistics;
using QuantConnect.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using QuantConnect.Logging;
using QuantConnect.Packets;
namespace QuantConnect.Jupyter
{
/// <summary>
/// Provides access to data for quantitative analysis
/// </summary>
public class QuantBook : QCAlgorithm
{
private dynamic _pandas;
private IDataCacheProvider _dataCacheProvider;
static QuantBook()
{
Logging.Log.LogHandler =
Composer.Instance.GetExportedValueByTypeName<ILogHandler>(Config.Get("log-handler", "CompositeLogHandler"));
}
/// <summary>
/// <see cref = "QuantBook" /> constructor.
/// Provides access to data for quantitative analysis
/// </summary>
public QuantBook() : base()
{
try
{
using (Py.GIL())
{
_pandas = Py.Import("pandas");
}
// By default, set start date to end data which is yesterday
SetStartDate(EndDate);
// Sets PandasConverter
SetPandasConverter();
// Initialize History Provider
var composer = new Composer();
var algorithmHandlers = LeanEngineAlgorithmHandlers.FromConfiguration(composer);
var systemHandlers = LeanEngineSystemHandlers.FromConfiguration(composer);
// init the API
systemHandlers.Initialize();
systemHandlers.LeanManager.Initialize(systemHandlers,
algorithmHandlers,
new BacktestNodePacket(),
new AlgorithmManager(false));
systemHandlers.LeanManager.SetAlgorithm(this);
_dataCacheProvider = new ZipDataCacheProvider(algorithmHandlers.DataProvider);
var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder();
var registeredTypes = new RegisteredSecurityDataTypesProvider();
var securityService = new SecurityService(Portfolio.CashBook,
MarketHoursDatabase,
symbolPropertiesDataBase,
this,
registeredTypes,
new SecurityCacheProvider(Portfolio));
Securities.SetSecurityService(securityService);
SubscriptionManager.SetDataManager(
new DataManager(new NullDataFeed(),
new UniverseSelection(this, securityService),
this,
TimeKeeper,
MarketHoursDatabase,
false,
registeredTypes));
var mapFileProvider = algorithmHandlers.MapFileProvider;
HistoryProvider = composer.GetExportedValueByTypeName<IHistoryProvider>(Config.Get("history-provider", "SubscriptionDataReaderHistoryProvider"));
HistoryProvider.Initialize(
new HistoryProviderInitializeParameters(
null,
null,
algorithmHandlers.DataProvider,
_dataCacheProvider,
mapFileProvider,
algorithmHandlers.FactorFileProvider,
null,
true
)
);
SetOptionChainProvider(new CachingOptionChainProvider(new BacktestingOptionChainProvider()));
SetFutureChainProvider(new CachingFutureChainProvider(new BacktestingFutureChainProvider()));
}
catch (Exception exception)
{
throw new Exception("QuantBook.Main(): " + exception);
}
}
/// <summary>
/// Get fundamental data from given symbols
/// </summary>
/// <param name="pyObject">The symbols to retrieve fundamental data for</param>
/// <param name="selector">Selects a value from the Fundamental data to filter the request output</param>
/// <param name="start">The start date of selected data</param>
/// <param name="end">The end date of selected data</param>
/// <returns></returns>
public PyObject GetFundamental(PyObject tickers, string selector, DateTime? start = null, DateTime? end = null)
{
if (string.IsNullOrWhiteSpace(selector))
{
return "Invalid selector. Cannot be None, empty or consist only of white-space characters".ToPython();
}
using (Py.GIL())
{
// If tickers are not a PyList, we create one
if (!PyList.IsListType(tickers))
{
var tmp = new PyList();
tmp.Append(tickers);
tickers = tmp;
}
var list = new List<Tuple<Symbol, DateTime, object>>();
foreach (var ticker in tickers)
{
var symbol = QuantConnect.Symbol.Create(ticker.ToString(), SecurityType.Equity, Market.USA);
var dir = new DirectoryInfo(Path.Combine(Globals.DataFolder, "equity", symbol.ID.Market, "fundamental", "fine", symbol.Value.ToLowerInvariant()));
if (!dir.Exists) continue;
var config = new SubscriptionDataConfig(typeof(FineFundamental), symbol, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork, false, false, false);
foreach (var fileName in dir.EnumerateFiles())
{
var date = DateTime.ParseExact(fileName.Name.Substring(0, 8), DateFormat.EightCharacter, CultureInfo.InvariantCulture);
if (date < start || date > end) continue;
var factory = new TextSubscriptionDataSourceReader(_dataCacheProvider, config, date, false);
var source = new SubscriptionDataSource(fileName.FullName, SubscriptionTransportMedium.LocalFile);
var value = factory.Read(source).Select(x => GetPropertyValue(x, selector)).First();
list.Add(Tuple.Create(symbol, date, value));
}
}
var data = new PyDict();
foreach (var item in list.GroupBy(x => x.Item1))
{
var index = item.Select(x => x.Item2);
data.SetItem(item.Key, _pandas.Series(item.Select(x => x.Item3).ToList(), index));
}
return _pandas.DataFrame(data);
}
}
/// <summary>
/// Gets <see cref="OptionHistory"/> object for a given symbol, date and resolution
/// </summary>
/// <param name="symbol">The symbol to retrieve historical option data for</param>
/// <param name="start">The history request start time</param>
/// <param name="end">The history request end time. Defaults to 1 day if null</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>A <see cref="OptionHistory"/> object that contains historical option data.</returns>
public OptionHistory GetOptionHistory(Symbol symbol, DateTime start, DateTime? end = null, Resolution? resolution = null)
{
if (!end.HasValue || end.Value == start)
{
end = start.AddDays(1);
}
IEnumerable<Symbol> symbols;
if (symbol.IsCanonical())
{
// canonical symbol, lets find the contracts
var option = Securities[symbol] as Option;
var resolutionToUseForUnderlying = resolution ?? SubscriptionManager.SubscriptionDataConfigService
.GetSubscriptionDataConfigs(symbol)
.GetHighestResolution();
if (!Securities.ContainsKey(symbol.Underlying))
{
// only add underlying if not present
AddEquity(symbol.Underlying.Value, resolutionToUseForUnderlying);
}
var allSymbols = new List<Symbol>();
for (var date = start; date < end; date = date.AddDays(1))
{
if (option.Exchange.DateIsOpen(date))
{
allSymbols.AddRange(OptionChainProvider.GetOptionContractList(symbol.Underlying, date));
}
}
symbols = base.History(symbol.Underlying, start, end.Value, resolution)
.SelectMany(x => option.ContractFilter.Filter(new OptionFilterUniverse(allSymbols.Distinct(), x)))
.Distinct().Concat(new[] { symbol.Underlying });
}
else
{
// the symbol is a contract
symbols = new List<Symbol>{ symbol };
}
return new OptionHistory(History(symbols, start, end.Value, resolution));
}
/// <summary>
/// Gets <see cref="FutureHistory"/> object for a given symbol, date and resolution
/// </summary>
/// <param name="symbol">The symbol to retrieve historical future data for</param>
/// <param name="start">The history request start time</param>
/// <param name="end">The history request end time. Defaults to 1 day if null</param>
/// <param name="resolution">The resolution to request</param>
/// <returns>A <see cref="FutureHistory"/> object that contains historical future data.</returns>
public FutureHistory GetFutureHistory(Symbol symbol, DateTime start, DateTime? end = null, Resolution? resolution = null)
{
if (!end.HasValue || end.Value == start)
{
end = start.AddDays(1);
}
var allSymbols = new HashSet<Symbol>();
if (symbol.IsCanonical())
{
// canonical symbol, lets find the contracts
var future = Securities[symbol] as Future;
for (var date = start; date < end; date = date.AddDays(1))
{
if (future.Exchange.DateIsOpen(date))
{
allSymbols.UnionWith(FutureChainProvider.GetFutureContractList(future.Symbol, date));
}
}
}
else
{
// the symbol is a contract
allSymbols.Add(symbol);
}
return new FutureHistory(History(allSymbols, start, end.Value, resolution));
}
/// <summary>
/// Gets the historical data of an indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of an indicator</returns>
public PyObject Indicator(IndicatorBase<IndicatorDataPoint> indicator, Symbol symbol, int period, Resolution? resolution = null, Func<IBaseData, decimal> selector = null)
{
var history = History(new[] { symbol }, period, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets the historical data of a bar indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of a bar indicator</returns>
public PyObject Indicator(IndicatorBase<IBaseDataBar> indicator, Symbol symbol, int period, Resolution? resolution = null, Func<IBaseData, IBaseDataBar> selector = null)
{
var history = History(new[] { symbol }, period, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets the historical data of a bar indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="periods">The number of bars to request</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of a bar indicator</returns>
public PyObject Indicator(IndicatorBase<TradeBar> indicator, Symbol symbol, int period, Resolution? resolution = null, Func<IBaseData, TradeBar> selector = null)
{
var history = History(new[] { symbol }, period, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets the historical data of an indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="indicator">Indicator</param>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of an indicator</returns>
public PyObject Indicator(IndicatorBase<IndicatorDataPoint> indicator, Symbol symbol, TimeSpan span, Resolution? resolution = null, Func<IBaseData, decimal> selector = null)
{
var history = History(new[] { symbol }, span, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets the historical data of a bar indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="indicator">Indicator</param>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of a bar indicator</returns>
public PyObject Indicator(IndicatorBase<IBaseDataBar> indicator, Symbol symbol, TimeSpan span, Resolution? resolution = null, Func<IBaseData, IBaseDataBar> selector = null)
{
var history = History(new[] { symbol }, span, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets the historical data of a bar indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="indicator">Indicator</param>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="span">The span over which to retrieve recent historical data</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of a bar indicator</returns>
public PyObject Indicator(IndicatorBase<TradeBar> indicator, Symbol symbol, TimeSpan span, Resolution? resolution = null, Func<IBaseData, TradeBar> selector = null)
{
var history = History(new[] { symbol }, span, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets the historical data of an indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="indicator">Indicator</param>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of an indicator</returns>
public PyObject Indicator(IndicatorBase<IndicatorDataPoint> indicator, Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null, Func<IBaseData, decimal> selector = null)
{
var history = History(new[] { symbol }, start, end, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets the historical data of a bar indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="indicator">Indicator</param>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of a bar indicator</returns>
public PyObject Indicator(IndicatorBase<IBaseDataBar> indicator, Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null, Func<IBaseData, IBaseDataBar> selector = null)
{
var history = History(new[] { symbol }, start, end, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets the historical data of a bar indicator for the specified symbol. The exact number of bars will be returned.
/// The symbol must exist in the Securities collection.
/// </summary>
/// <param name="indicator">Indicator</param>
/// <param name="symbol">The symbol to retrieve historical data for</param>
/// <param name="start">The start time in the algorithm's time zone</param>
/// <param name="end">The end time in the algorithm's time zone</param>
/// <param name="resolution">The resolution to request</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame of historical data of a bar indicator</returns>
public PyObject Indicator(IndicatorBase<TradeBar> indicator, Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null, Func<IBaseData, TradeBar> selector = null)
{
var history = History(new[] { symbol }, start, end, resolution);
return Indicator(indicator, history, selector);
}
/// <summary>
/// Gets Portfolio Statistics from a pandas.DataFrame with equity and benchmark values
/// </summary>
/// <param name="dataFrame">pandas.DataFrame with the information required to compute the Portfolio statistics</param>
/// <returns><see cref="PortfolioStatistics"/> object wrapped in a <see cref="PyDict"/> with the portfolio statistics.</returns>
public PyDict GetPortfolioStatistics(PyObject dataFrame)
{
var dictBenchmark = new SortedDictionary<DateTime, double>();
var dictEquity = new SortedDictionary<DateTime, double>();
var dictPL = new SortedDictionary<DateTime, double>();
using (Py.GIL())
{
var result = new PyDict();
try
{
// Converts the data from pandas.DataFrame into dictionaries keyed by time
var df = ((dynamic)dataFrame).dropna();
dictBenchmark = GetDictionaryFromSeries((PyObject)df["benchmark"]);
dictEquity = GetDictionaryFromSeries((PyObject)df["equity"]);
dictPL = GetDictionaryFromSeries((PyObject)df["equity"].pct_change());
}
catch (PythonException e)
{
result.SetItem("Runtime Error", e.Message.ToPython());
return result;
}
// Convert the double into decimal
var equity = new SortedDictionary<DateTime, decimal>(dictEquity.ToDictionary(kvp => kvp.Key, kvp => (decimal)kvp.Value));
var profitLoss = new SortedDictionary<DateTime, decimal>(dictPL.ToDictionary(kvp => kvp.Key, kvp => double.IsNaN(kvp.Value) ? 0 : (decimal)kvp.Value));
// Gets the last value of the day of the benchmark and equity
var listBenchmark = CalculateDailyRateOfChange(dictBenchmark);
var listPerformance = CalculateDailyRateOfChange(dictEquity);
// Gets the startting capital
var startingCapital = Convert.ToDecimal(dictEquity.FirstOrDefault().Value);
// Compute portfolio statistics
var stats = new PortfolioStatistics(profitLoss, equity, listPerformance, listBenchmark, startingCapital);
result.SetItem("Average Win (%)", Convert.ToDouble(stats.AverageWinRate * 100).ToPython());
result.SetItem("Average Loss (%)", Convert.ToDouble(stats.AverageLossRate * 100).ToPython());
result.SetItem("Compounding Annual Return (%)", Convert.ToDouble(stats.CompoundingAnnualReturn * 100m).ToPython());
result.SetItem("Drawdown (%)", Convert.ToDouble(stats.Drawdown * 100).ToPython());
result.SetItem("Expectancy", Convert.ToDouble(stats.Expectancy).ToPython());
result.SetItem("Net Profit (%)", Convert.ToDouble(stats.TotalNetProfit * 100).ToPython());
result.SetItem("Sharpe Ratio", Convert.ToDouble(stats.SharpeRatio).ToPython());
result.SetItem("Win Rate (%)", Convert.ToDouble(stats.WinRate * 100).ToPython());
result.SetItem("Loss Rate (%)", Convert.ToDouble(stats.LossRate * 100).ToPython());
result.SetItem("Profit-Loss Ratio", Convert.ToDouble(stats.ProfitLossRatio).ToPython());
result.SetItem("Alpha", Convert.ToDouble(stats.Alpha).ToPython());
result.SetItem("Beta", Convert.ToDouble(stats.Beta).ToPython());
result.SetItem("Annual Standard Deviation", Convert.ToDouble(stats.AnnualStandardDeviation).ToPython());
result.SetItem("Annual Variance", Convert.ToDouble(stats.AnnualVariance).ToPython());
result.SetItem("Information Ratio", Convert.ToDouble(stats.InformationRatio).ToPython());
result.SetItem("Tracking Error", Convert.ToDouble(stats.TrackingError).ToPython());
result.SetItem("Treynor Ratio", Convert.ToDouble(stats.TreynorRatio).ToPython());
return result;
}
}
/// <summary>
/// Converts a pandas.Series into a <see cref="SortedDictionary{DateTime, Double}"/>
/// </summary>
/// <param name="series">pandas.Series to be converted</param>
/// <returns><see cref="SortedDictionary{DateTime, Double}"/> with pandas.Series information</returns>
private SortedDictionary<DateTime, double> GetDictionaryFromSeries(PyObject series)
{
var dictionary = new SortedDictionary<DateTime, double>();
var pyDict = new PyDict(((dynamic)series).to_dict());
foreach (PyObject item in pyDict.Items())
{
var key = (DateTime)item[0].AsManagedObject(typeof(DateTime));
var value = (double)item[1].AsManagedObject(typeof(double));
dictionary.Add(key, value);
}
return dictionary;
}
/// <summary>
/// Calculates the daily rate of change
/// </summary>
/// <param name="dictionary"><see cref="IDictionary{DateTime, Double}"/> with prices keyed by time</param>
/// <returns><see cref="List{Double}"/> with daily rate of change</returns>
private List<double> CalculateDailyRateOfChange(IDictionary<DateTime, double> dictionary)
{
var daily = dictionary.GroupBy(kvp => kvp.Key.Date)
.ToDictionary(x => x.Key, v => v.LastOrDefault().Value)
.Values.ToArray();
var rocp = new double[daily.Length];
for (var i = 1; i < daily.Length; i++)
{
rocp[i] = (daily[i] - daily[i - 1]) / daily[i - 1];
}
rocp[0] = 0;
return rocp.ToList();
}
/// <summary>
/// Gets the historical data of an indicator and convert it into pandas.DataFrame
/// </summary>
/// <param name="indicator">Indicator</param>
/// <param name="history">Historical data used to calculate the indicator</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame containing the historical data of <param name="indicator"></returns>
private PyObject Indicator(IndicatorBase<IndicatorDataPoint> indicator, IEnumerable<Slice> history, Func<IBaseData, decimal> selector = null)
{
// Reset the indicator
indicator.Reset();
// Create a dictionary of the properties
var name = indicator.GetType().Name;
var properties = indicator.GetType().GetProperties()
.Where(x => x.PropertyType.IsGenericType)
.ToDictionary(x => x.Name, y => new List<IndicatorDataPoint>());
properties.Add(name, new List<IndicatorDataPoint>());
indicator.Updated += (s, e) =>
{
if (!indicator.IsReady)
{
return;
}
foreach (var kvp in properties)
{
var dataPoint = kvp.Key == name ? e : GetPropertyValue(s, kvp.Key + ".Current");
kvp.Value.Add((IndicatorDataPoint)dataPoint);
}
};
selector = selector ?? (x => x.Value);
history.PushThrough(bar =>
{
var value = selector(bar);
indicator.Update(bar.EndTime, value);
});
return PandasConverter.GetIndicatorDataFrame(properties);
}
/// <summary>
/// Gets the historical data of an bar indicator and convert it into pandas.DataFrame
/// </summary>
/// <param name="indicator">Bar indicator</param>
/// <param name="history">Historical data used to calculate the indicator</param>
/// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to the Value property of BaseData (x => x.Value)</param>
/// <returns>pandas.DataFrame containing the historical data of <param name="indicator"></returns>
private PyObject Indicator<T>(IndicatorBase<T> indicator, IEnumerable<Slice> history, Func<IBaseData, T> selector = null)
where T : IBaseData
{
// Reset the indicator
indicator.Reset();
// Create a dictionary of the properties
var name = indicator.GetType().Name;
var properties = indicator.GetType().GetProperties()
.Where(x => x.PropertyType.IsGenericType)
.ToDictionary(x => x.Name, y => new List<IndicatorDataPoint>());
properties.Add(name, new List<IndicatorDataPoint>());
indicator.Updated += (s, e) =>
{
if (!indicator.IsReady)
{
return;
}
foreach (var kvp in properties)
{
var dataPoint = kvp.Key == name ? e : GetPropertyValue(s, kvp.Key + ".Current");
kvp.Value.Add((IndicatorDataPoint)dataPoint);
}
};
selector = selector ?? (x => (T)x);
history.PushThrough(bar => indicator.Update(selector(bar)));
return PandasConverter.GetIndicatorDataFrame(properties);
}
/// <summary>
/// Gets a value of a property
/// </summary>
/// <param name="baseData">Object with the desired property</param>
/// <param name="fullName">Property name</param>
/// <returns>Property value</returns>
private object GetPropertyValue(object baseData, string fullName)
{
foreach (var name in fullName.Split('.'))
{
if (baseData == null) return null;
var info = baseData.GetType().GetProperty(name);
baseData = info?.GetValue(baseData, null);
}
return baseData;
}
}
}