Lean  $LEAN_TAG$
MapFileZipHelper.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using System.IO;
18 using System.Linq;
19 using System.Collections.Generic;
20 
22 {
23  /// <summary>
24  /// Helper class for handling mapfile zip files
25  /// </summary>
26  public static class MapFileZipHelper
27  {
28  /// <summary>
29  /// Gets the mapfile zip filename for the specified date
30  /// </summary>
31  public static string GetMapFileZipFileName(string market, DateTime date, SecurityType securityType)
32  {
33  return Path.Combine(Globals.DataFolder, MapFile.GetRelativeMapFilePath(market, securityType), $"map_files_{date:yyyyMMdd}.zip");
34  }
35 
36  /// <summary>
37  /// Reads the zip bytes as text and parses as MapFileRows to create MapFiles
38  /// </summary>
39  public static IEnumerable<MapFile> ReadMapFileZip(Stream file, string market, SecurityType securityType)
40  {
41  if (file == null || file.Length == 0)
42  {
43  return Enumerable.Empty<MapFile>();
44  }
45 
46  var result = from kvp in Compression.Unzip(file)
47  let filename = kvp.Key
48  where filename.EndsWith(".csv", StringComparison.InvariantCultureIgnoreCase)
49  let lines = kvp.Value.Where(line => !string.IsNullOrEmpty(line))
50  let mapFile = SafeRead(filename, lines, market, securityType)
51  select mapFile;
52  return result;
53  }
54 
55  /// <summary>
56  /// Parses the contents as a MapFile, if error returns a new empty map file
57  /// </summary>
58  private static MapFile SafeRead(string filename, IEnumerable<string> contents, string market, SecurityType securityType)
59  {
60  var permtick = Path.GetFileNameWithoutExtension(filename);
61  try
62  {
63  return new MapFile(permtick, contents.Select(s => MapFileRow.Parse(s, market, securityType)));
64  }
65  catch
66  {
67  return new MapFile(permtick, Enumerable.Empty<MapFileRow>());
68  }
69  }
70  }
71 }