-
Notifications
You must be signed in to change notification settings - Fork 107
/
DataSourceYahoo.cs
473 lines (401 loc) · 20.2 KB
/
DataSourceYahoo.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
//==============================================================================
// Project: TuringTrader, simulator core
// Name: DataSourceYahoo
// Description: Data source for Yahoo EOD Data.
// History: 2019vi02, FUB, created
//------------------------------------------------------------------------------
// Copyright: (c) 2011-2023, Bertram Enterprises LLC dba TuringTrader.
// https://www.turingtrader.org
// License: This file is part of TuringTrader, an open-source backtesting
// engine/ trading simulator.
// TuringTrader is free software: you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
// TuringTrader is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public
// License along with TuringTrader. If not, see
// https://www.gnu.org/licenses/agpl-3.0.
//==============================================================================
#if true
#region libraries
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
#endregion
namespace TuringTrader.Simulator
{
public partial class DataSourceCollection
{
private class DataSourceYahoo : DataSource
{
#region internal helpers
private static object _lockCache = new object();
private static readonly DateTime _epochOrigin
// it is important that the epoch here is DateTimeKind.Unspecified
// so that the v2 engine can convert this properly to the local timezone
//= new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // retired 2023vii23
= new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified); // new 2023vii23
private static DateTime fromUnixTime(long unixTime)
{
return _epochOrigin.AddSeconds(unixTime);
}
private static long toUnixTime(DateTime date)
{
return Convert.ToInt64((date - _epochOrigin).TotalSeconds);
}
private string convertSymbol(string ticker)
{
#if true
// new 2021vii01
return ticker;
#else
// retired 2021vii01
// this code was supposed to help with tickers like BRK.A, which
// Yahoo presents as BRK-A. However, it seems that with other stocks,
// e.g., IOZ.AX, Yahoo uses the colon. Ultimately, it seems better
// to substitute the symbols with a Data Source Descriptor file.
// For Yahoo's suffixes see https://au.help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html
return ticker.Replace('.', '-');
#endif
}
private JObject parsePrices(string raw)
{
JObject json = null;
if (raw == null)
return null;
if (raw.Length < 25)
return null;
try
{
json = JObject.Parse(raw);
}
catch
{
return null;
}
if (!json.HasValues)
return null;
return json;
}
private JObject getPrices(DateTime startTime, DateTime endTime)
{
string cachePath = Path.Combine(GlobalSettings.HomePath, "Cache", Info[DataSourceParam.nickName2]);
string timeStamps = Path.Combine(cachePath, "yahoo_timestamps");
string priceCache = Path.Combine(cachePath, "yahoo_prices");
bool writeToDisk = false;
string rawPrices = null;
JObject jsonPrices = null;
//--- 1) try to read raw json from disk
if (File.Exists(timeStamps) && File.Exists(priceCache))
{
using (BinaryReader pc = new BinaryReader(File.Open(priceCache, FileMode.Open)))
rawPrices = pc.ReadString();
using (BinaryReader ts = new BinaryReader(File.Open(timeStamps, FileMode.Open)))
{
DateTime cacheStartTime = new DateTime(ts.ReadInt64());
DateTime cacheEndTime = new DateTime(ts.ReadInt64());
// NOTE: yahoo delivers intraday data. When we write to the cache,
// we set the time of day to the expected end of the trading session.
// consequently, we might cache an intraday quote and store it as if
// it was the end-of-day quote. to fix that issue, we do not use the
// cache if our request reaches the last bar.
//if (cacheStartTime.Date <= startTime.Date && cacheEndTime.Date >= endTime.Date)
if (cacheStartTime.Date <= startTime.Date && cacheEndTime.Date > endTime.Date)
jsonPrices = parsePrices(rawPrices);
}
}
//--- 2) if failed, try to retrieve from web
if (jsonPrices == null)
{
#if true
// always request whole range here, to make
// offline behavior as pleasant as possible
DateTime DATA_START = DateTime.Parse("01/01/1970", CultureInfo.InvariantCulture);
//startTime = ((DateTime)FirstTime) < DATA_START
// ? DATA_START
// : (DateTime)FirstTime;
startTime = DATA_START;
endTime = DateTime.Now.Date + TimeSpan.FromDays(1);
#else
startTime = startTime.Date;
endTime = endTime.Date + TimeSpan.FromDays(5);
#endif
string url = string.Format(
@"http://query1.finance.yahoo.com/v8/finance/chart/"
+ "{0}"
+ "?interval=1d"
+ "&period1={1}"
+ "&period2={2}",
convertSymbol(Info[DataSourceParam.symbolYahoo]),
toUnixTime(startTime),
toUnixTime(endTime));
string tmpPrices = null;
#pragma warning disable SYSLIB0014 // Type or member is obsolete
using (var client = new WebClient())
tmpPrices = client.DownloadString(url);
#pragma warning restore SYSLIB0014 // Type or member is obsolete
jsonPrices = parsePrices(tmpPrices);
if (jsonPrices != null)
{
rawPrices = tmpPrices;
writeToDisk = true;
}
else
{
// we might have discarded the data from disk before,
// because the time frame wasn't what we were looking for.
// however, in case we can't load from web, e.g. because
// we don't have internet connectivity, it's still better
// to go with what we have cached before
jsonPrices = parsePrices(rawPrices);
}
jsonPrices = JObject.Parse(rawPrices);
}
//--- 3) if failed, return
if (jsonPrices == null)
return null;
//--- 4) write to disk
if (writeToDisk)
{
var timestamps = (JArray)jsonPrices["chart"]["result"][0]["timestamp"];
// FIXME: we should consider the data source's time here:
// timeOfDay = DateTime.Parse(Info[DataSourceParam.time]).TimeOfDay;
var firstTime = fromUnixTime((long)timestamps.First).Date
+ DateTime.Parse("16:00").TimeOfDay;
var lastTime = fromUnixTime((long)timestamps.Last).Date
+ DateTime.Parse("16:00").TimeOfDay;
Directory.CreateDirectory(cachePath);
using (BinaryWriter pc = new BinaryWriter(File.Open(priceCache, FileMode.Create)))
pc.Write(rawPrices);
using (BinaryWriter ts = new BinaryWriter(File.Open(timeStamps, FileMode.Create)))
{
//ts.Write(startTime.Ticks);
//ts.Write(endTime.Ticks);
ts.Write(firstTime.Ticks);
ts.Write(lastTime.Ticks);
}
}
return jsonPrices;
}
private string getMeta()
{
string cachePath = Path.Combine(GlobalSettings.HomePath, "Cache", Info[DataSourceParam.nickName2]);
string metaCache = Path.Combine(cachePath, "yahoo_meta");
bool writeToDisk = false;
string rawMeta = null;
bool validMeta()
{
if (rawMeta == null)
return false;
if (rawMeta.Length < 10)
return false;
return true;
}
//--- 1) try to read meta from disk
if (File.Exists(metaCache))
{
using (StreamReader mc = new StreamReader(File.Open(metaCache, FileMode.Open)))
rawMeta = mc.ReadToEnd();
}
//--- 2) if failed, try to retrieve from web
if (!validMeta())
{
Output.WriteLine("DataSourceYahoo: retrieving meta for {0}", Info[DataSourceParam.nickName]);
string url = string.Format(
@"http://finance.yahoo.com/quote/"
+ "{0}",
convertSymbol(Info[DataSourceParam.symbolYahoo]));
#pragma warning disable SYSLIB0014 // Type or member is obsolete
using (var client = new WebClient())
rawMeta = client.DownloadString(url);
#pragma warning restore SYSLIB0014 // Type or member is obsolete
writeToDisk = true;
}
//--- 3) if failed, return
if (!validMeta())
return null;
//--- 4) write to disk
if (writeToDisk)
{
Directory.CreateDirectory(cachePath);
using (StreamWriter mc = new StreamWriter(File.Open(metaCache, FileMode.Create)))
mc.Write(rawMeta);
}
return rawMeta;
}
#endregion
//---------- API
#region public DataSourceYahoo(Dictionary<DataSourceValue, string> info)
/// <summary>
/// Create and initialize new data source for Yahoo Data.
/// </summary>
/// <param name="info">info dictionary</param>
public DataSourceYahoo(Dictionary<DataSourceParam, string> info) : base(info)
{
// Yahoo does not provide meta data
// we extract them from the instrument's web page
lock (_lockCache)
{
string meta = getMeta();
try
{
string tmp1 = meta.Substring(meta.IndexOf("<h1"));
string tmp2 = tmp1.Substring(0, tmp1.IndexOf("h1>"));
string tmp3 = tmp2.Substring(tmp2.IndexOf(">") + 1);
string tmp4 = tmp3.Substring(0, tmp3.IndexOf("<"));
tmp4 = tmp4.Replace("&", "&");
Info[DataSourceParam.name] = tmp4;
}
catch
{
// failed to load/parse website
Output.WriteLine("{0}: failed to parse meta for {1}", GetType().Name, Info[DataSourceParam.symbolYahoo]);
Info[DataSourceParam.name] = info[DataSourceParam.ticker];
}
}
}
#endregion
#region public override IEnumerable<Bar> LoadData(DateTime startTime, DateTime endTime)
/// <summary>
/// Load data into memory.
/// </summary>
/// <param name="startTime">start of load range</param>
/// <param name="endTime">end of load range</param>
public override IEnumerable<Bar> LoadData(DateTime startTime, DateTime endTime)
{
List<Bar> data = new List<Bar>();
try
{
//if (startTime < (DateTime)FirstTime)
// startTime = (DateTime)FirstTime;
//if (endTime > (DateTime)LastTime)
// endTime = (DateTime)LastTime;
var cacheKey = new CacheId().AddParameters(
Info[DataSourceParam.nickName].GetHashCode(),
startTime.GetHashCode(),
endTime.GetHashCode());
List<Bar> retrievalFunction()
{
DateTime t1 = DateTime.Now;
Output.Write(string.Format("DataSourceYahoo: loading data for {0}...", Info[DataSourceParam.nickName]));
JObject jsonData = getPrices(startTime, endTime);
/*
Yahoo JSON format, as of 07/02/2019
[JSON]
chart
result
[0]
meta
currency
symbol
...
timestamp
[0]: 511108200
[1]: 511194600
...
indicators
quote
[0]
low
[0]: 0.08854
[1]: 0.09722
...
close
volume
open
high
adjclose
[0]
adjclose
[0]: 0.06999
[1]: 0.07249
*/
List<Bar> bars = new List<Bar>();
var timestamps = (JArray)jsonData["chart"]["result"][0]["timestamp"];
var opens = (JArray)jsonData["chart"]["result"][0]["indicators"]["quote"][0]["open"];
var highs = (JArray)jsonData["chart"]["result"][0]["indicators"]["quote"][0]["high"];
var lows = (JArray)jsonData["chart"]["result"][0]["indicators"]["quote"][0]["low"];
var closes = (JArray)jsonData["chart"]["result"][0]["indicators"]["quote"][0]["close"];
var volumes = (JArray)jsonData["chart"]["result"][0]["indicators"]["quote"][0]["volume"];
var adjcloses = (JArray)jsonData["chart"]["result"][0]["indicators"]["adjclose"][0]["adjclose"];
var eT = timestamps.GetEnumerator();
var eO = opens.GetEnumerator();
var eH = highs.GetEnumerator();
var eL = lows.GetEnumerator();
var eC = closes.GetEnumerator();
var eV = volumes.GetEnumerator();
var eAC = adjcloses.GetEnumerator();
while (eT.MoveNext() && eO.MoveNext() && eH.MoveNext()
&& eL.MoveNext() && eC.MoveNext() && eV.MoveNext() && eAC.MoveNext())
{
DateTime t = fromUnixTime((long)eT.Current).Date
+ DateTime.Parse("16:00").TimeOfDay;
Bar bar = null;
try
{
// Yahoo taints the results by filling in null values
// we try to handle this gracefully in the catch block
double o = (double)eO.Current;
double h = (double)eH.Current;
double l = (double)eL.Current;
double c = (double)eC.Current;
long v = (long)eV.Current;
double ac = (double)eAC.Current;
// adjust prices according to the adjusted close.
// note the volume is adjusted the opposite way.
double ao = o * ac / c;
double ah = h * ac / c;
double al = l * ac / c;
long av = (long)(v * c / ac);
bar = Bar.NewOHLC(
Info[DataSourceParam.ticker],
t,
ao, ah, al, ac,
av);
}
catch
{
if (bars.Count < 1)
continue;
Bar prevBar = bars.Last();
bar = Bar.NewOHLC(
Info[DataSourceParam.ticker],
t,
prevBar.Open, prevBar.High, prevBar.Low, prevBar.Close,
prevBar.Volume);
}
if (t >= startTime && t <= endTime)
bars.Add(bar);
}
DateTime t2 = DateTime.Now;
Output.WriteLine(string.Format(" finished after {0:F1} seconds", (t2 - t1).TotalSeconds));
return bars;
};
data = Cache<List<Bar>>.GetData(cacheKey, retrievalFunction, true);
}
catch (Exception e)
{
throw new Exception(
string.Format("DataSourceYahoo: failed to load quotes for {0}, {1}",
Info[DataSourceParam.nickName], e.Message));
}
if (data.Count == 0)
throw new Exception(string.Format("DataSourceYahoo: no data for {0}", Info[DataSourceParam.nickName]));
CachedData = data;
return data;
}
#endregion
}
}
}
#endif
//==============================================================================
// end of file