20 using System.Collections.Generic;
21 using System.Globalization;
32 private static readonly DateTime _firstInterestRateDate =
new DateTime(1998, 1, 1);
33 private static DateTime _lastInterestRateDate;
34 private static Dictionary<DateTime, decimal> _riskFreeRateProvider;
35 private static readonly
object _lock =
new();
45 private IReadOnlyDictionary<DateTime, decimal> RiskFreeRateProvider
50 if (_riskFreeRateProvider !=
null)
52 return _riskFreeRateProvider;
58 return _riskFreeRateProvider;
70 if (!RiskFreeRateProvider.TryGetValue(date.Date, out var interestRate))
72 return date < _firstInterestRateDate
73 ? RiskFreeRateProvider[_firstInterestRateDate]
74 : RiskFreeRateProvider[_lastInterestRateDate];
85 var directory = Path.Combine(
Globals.
DataFolder,
"alternative",
"interest-rate",
"usa",
87 var riskFreeRateProvider =
FromCsvFile(directory, out var previousInterestRate);
89 _lastInterestRateDate = DateTime.UtcNow.Date;
92 for (var date = _firstInterestRateDate; date <= _lastInterestRateDate; date = date.AddDays(1))
94 if (!riskFreeRateProvider.TryGetValue(date, out var currentRate))
96 riskFreeRateProvider[date] = previousInterestRate;
100 previousInterestRate = currentRate;
103 return riskFreeRateProvider;
112 public static Dictionary<DateTime, decimal>
FromCsvFile(
string file, out decimal firstInterestRate)
116 var firstInterestRateSet =
false;
120 var interestRateProvider =
new Dictionary<DateTime, decimal>();
121 foreach (var line
in dataProvider.ReadLines(file).Skip(1)
122 .Where(x => !
string.IsNullOrWhiteSpace(x)))
124 if (
TryParse(line, out var date, out var interestRate))
126 if (!firstInterestRateSet)
128 firstInterestRate = interestRate;
129 firstInterestRateSet =
true;
132 interestRateProvider[date] = interestRate;
136 if (interestRateProvider.Count == 0)
138 Log.
Error($
"InterestRateProvider.FromCsvFile(): no interest rates were loaded, please make sure the file is present '{file}'");
141 return interestRateProvider;
150 public static bool TryParse(
string csvLine, out DateTime date, out decimal interestRate)
152 var line = csvLine.Split(
',');
154 if (!DateTime.TryParseExact(line[0],
"yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
156 Log.
Error($
"Couldn't parse date/time while reading FED primary credit rate file. Line: {csvLine}");
161 if (!decimal.TryParse(line[1], NumberStyles.Any, CultureInfo.InvariantCulture, out interestRate))
163 Log.
Error($
"Couldn't parse primary credit rate while reading FED primary credit rate file. Line: {csvLine}");