Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#75 all tests from class historical tests are failing #77

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions YahooFinanceApi.Tests/DecimalComparerWithPrecision.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;

namespace YahooFinanceApi.Tests;

public class DecimalComparerWithPrecision : IEqualityComparer<decimal>
{
private readonly decimal precision;

public DecimalComparerWithPrecision(decimal precision)
{
this.precision = precision;
}

public bool Equals(decimal x, decimal y)
{
return Math.Abs(x - y) < precision;
}

public int GetHashCode(decimal obj)
{
return obj.GetHashCode();
}

public static DecimalComparerWithPrecision defaultComparer = new DecimalComparerWithPrecision(0.00001m);
public static DecimalComparerWithPrecision Default => defaultComparer;
}
60 changes: 33 additions & 27 deletions YahooFinanceApi.Tests/HistoricalTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Flurl.Http;
using Xunit;
using Xunit.Abstractions;

Expand All @@ -17,12 +19,10 @@ public HistoricalTests(ITestOutputHelper output)
[Fact]
public async Task InvalidSymbolTest()
{
var exception = await Assert.ThrowsAsync<Exception>(async () =>
var exception = await Assert.ThrowsAsync<FlurlHttpException>(async () =>
await Yahoo.GetHistoricalAsync("invalidSymbol", new DateTime(2017, 1, 3), new DateTime(2017, 1, 4)));

Write(exception.ToString());

Assert.Contains("Not Found", exception.InnerException.Message);
Assert.Equal((int)HttpStatusCode.NotFound, exception.StatusCode);
}

[Fact]
Expand All @@ -31,13 +31,13 @@ public async Task PeriodTest()
var date = new DateTime(2023, 1, 9);

var candles = await Yahoo.GetHistoricalAsync("AAPL", date, date.AddDays(1), Period.Daily);
Assert.Equal(130.470001m, candles.First().Open);
Assert.Equal(130.470001m, candles.First().Open, DecimalComparerWithPrecision.Default);

candles = await Yahoo.GetHistoricalAsync("AAPL", date, date.AddDays(7), Period.Weekly);
Assert.Equal(130.470001m, candles.First().Open);
Assert.Equal(130.470001m, candles.First().Open, DecimalComparerWithPrecision.Default);

candles = await Yahoo.GetHistoricalAsync("AAPL", new DateTime(2023, 1, 1), new DateTime(2023, 2, 1), Period.Monthly);
Assert.Equal(130.279999m, candles.First().Open);
Assert.Equal(130.279999m, candles.First().Open, DecimalComparerWithPrecision.Default);
}

[Fact]
Expand All @@ -46,18 +46,25 @@ public async Task HistoricalTest()
var candles = await Yahoo.GetHistoricalAsync("AAPL", new DateTime(2023, 1, 3), new DateTime(2023, 1, 4), Period.Daily);

var candle = candles.First();
Assert.Equal(130.279999m, candle.Open);
Assert.Equal(130.899994m, candle.High);
Assert.Equal(124.169998m, candle.Low);
Assert.Equal(125.070000m, candle.Close);
Assert.Equal(112_117_500, candle.Volume);
Assert.Equal(130.279999m, candle.Open, DecimalComparerWithPrecision.Default);
Assert.Equal(130.899994m, candle.High, DecimalComparerWithPrecision.Default);
Assert.Equal(124.169998m, candle.Low, DecimalComparerWithPrecision.Default);
Assert.Equal(125.070000m, candle.Close, DecimalComparerWithPrecision.Default);
Assert.Equal(112_117_500, candle.Volume, DecimalComparerWithPrecision.Default);
}

[Fact]
public async Task DividendTest()
{
var dividends = await Yahoo.GetDividendsAsync("AAPL", new DateTime(2016, 2, 4), new DateTime(2016, 2, 5));
Assert.Equal(0.130000m, dividends.First().Dividend);
Assert.Equal(0.130000m, dividends.First().Dividend, DecimalComparerWithPrecision.Default);
}

[Fact]
public async Task NoDividendTest()
{
var dividends = await Yahoo.GetDividendsAsync("ADXN.SW", new DateTime(2000, 1, 1), new DateTime(2024, 09, 10));
Assert.Empty(dividends);
}

[Fact]
Expand All @@ -82,23 +89,23 @@ public async Task DatesTest_US()
Assert.Equal(from, candles.First().DateTime);
Assert.Equal(to.Date, candles.Last().DateTime);

Assert.Equal(75.18m, candles[0].Close);
Assert.Equal(74.940002m, candles[1].Close);
Assert.Equal(72.370003m, candles[2].Close);
Assert.Equal(75.18m, candles[0].Close, DecimalComparerWithPrecision.Default);
Assert.Equal(74.940002m, candles[1].Close, DecimalComparerWithPrecision.Default);
Assert.Equal(72.370003m, candles[2].Close, DecimalComparerWithPrecision.Default);
}

[Fact]
public async Task Test_UK()
{
var from = new DateTime(2017, 10, 10);
var to = new DateTime(2017, 10, 13);
var to = new DateTime(2017, 10, 12);

var candles = await Yahoo.GetHistoricalAsync("BA.L", from, to, Period.Daily);

Assert.Equal(3, candles.Count());

Assert.Equal(from, candles.First().DateTime);
Assert.Equal(to, candles.Last().DateTime.AddDays(1));
Assert.Equal(to, candles.Last().DateTime);

Assert.Equal(616.50m, candles[0].Close);
Assert.Equal(615.00m, candles[1].Close);
Expand All @@ -118,9 +125,9 @@ public async Task DatesTest_TW()
Assert.Equal(from, candles.First().DateTime);
Assert.Equal(to, candles.Last().DateTime);

Assert.Equal(71.599998m, candles[0].Close);
Assert.Equal(71.599998m, candles[1].Close);
Assert.Equal(73.099998m, candles[2].Close);
Assert.Equal(71.599998m, candles[0].Close, DecimalComparerWithPrecision.Default);
Assert.Equal(71.599998m, candles[1].Close, DecimalComparerWithPrecision.Default);
Assert.Equal(73.099998m, candles[2].Close, DecimalComparerWithPrecision.Default);
}

[Theory]
Expand All @@ -141,7 +148,7 @@ public async Task DatesTest(params string[] symbols)
var to = from.AddDays(2).AddHours(12);

// start tasks
var tasks = symbols.Select(symbol => Yahoo.GetHistoricalAsync(symbol, from, to));
var tasks = symbols.Select(symbol => Yahoo.GetHistoricalAsync(symbol, from, to, Period.Daily));

// wait for all tasks to complete
var results = await Task.WhenAll(tasks.ToArray());
Expand Down Expand Up @@ -176,11 +183,10 @@ public async Task CurrencyTest()

Assert.Equal(3, candles.Count());

Assert.Equal(1.174164m, candles[0].Close);
Assert.Equal(1.181488m, candles[1].Close);
Assert.Equal(1.186549m, candles[2].Close);
Assert.Equal(1.174164m, candles[0].Close, DecimalComparerWithPrecision.Default);
Assert.Equal(1.181488m, candles[1].Close, DecimalComparerWithPrecision.Default);
Assert.Equal(1.186549m, candles[2].Close, DecimalComparerWithPrecision.Default);

// Note: Forex seems to return date = (requested date - 1 day)
Assert.Equal(from, candles.First().DateTime);
Assert.Equal(to, candles.Last().DateTime);
}
Expand Down
44 changes: 44 additions & 0 deletions YahooFinanceApi.Tests/ProfileTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace YahooFinanceApi.Tests;

public class ProfileTests
{
[Fact]
public async Task TestProfileAsync()
{
const string AAPL = "AAPL";

var aaplProfile = await Yahoo.QueryProfileAsync(AAPL);

Assert.NotNull(aaplProfile.Address1);
Assert.NotNull(aaplProfile.AuditRisk);
Assert.NotNull(aaplProfile.BoardRisk);
Assert.NotNull(aaplProfile.City);
Assert.NotNull(aaplProfile.CompanyOfficers);
Assert.NotNull(aaplProfile.CompensationAsOfEpochDate);
Assert.NotNull(aaplProfile.CompensationRisk);
Assert.NotNull(aaplProfile.Country);
Assert.NotNull(aaplProfile.FullTimeEmployees);
Assert.NotNull(aaplProfile.GovernanceEpochDate);
Assert.NotNull(aaplProfile.Industry);
Assert.NotNull(aaplProfile.IndustryDisp);
Assert.NotNull(aaplProfile.IndustryKey);
Assert.NotNull(aaplProfile.LongBusinessSummary);
Assert.NotNull(aaplProfile.MaxAge);
Assert.NotNull(aaplProfile.State);
Assert.NotNull(aaplProfile.Zip);
Assert.NotNull(aaplProfile.Phone);
Assert.NotNull(aaplProfile.Website);
Assert.NotNull(aaplProfile.Sector);
Assert.NotNull(aaplProfile.SectorKey);
Assert.NotNull(aaplProfile.SectorDisp);
Assert.NotNull(aaplProfile.ShareHolderRightsRisk);
Assert.NotNull(aaplProfile.OverallRisk);
}
}
37 changes: 37 additions & 0 deletions YahooFinanceApi/Cache.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace YahooFinanceApi;

public static class Cache
{
private static Dictionary<string, TimeZoneInfo> timeZoneCache = new Dictionary<string, TimeZoneInfo>();

public static async Task<TimeZoneInfo> GetTimeZone(string ticker)
{
if (timeZoneCache.TryGetValue(ticker, out var zone))
return zone;

var timeZone = await RequestTimeZone(ticker);
timeZoneCache[ticker] = timeZone;
return timeZone;
}

private static async Task<TimeZoneInfo> RequestTimeZone(string ticker)
{
var startTime = DateTime.Now.AddDays(-2);
var endTime = DateTime.Now;
var data = await ChartDataLoader.GetResponseStreamAsync(ticker, startTime, endTime, Period.Daily, ShowOption.History.Name(), CancellationToken.None);
var timeZoneName = data.chart.result[0].meta.exchangeTimezoneName;
try
{
return TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
}
catch (TimeZoneNotFoundException e)
{
return TimeZoneInfo.Utc;
}
}
}
42 changes: 21 additions & 21 deletions YahooFinanceApi/Candle.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
using System;
namespace YahooFinanceApi
{
public sealed class Candle: ITick
{
public DateTime DateTime { get; internal set; }
public decimal Open { get; internal set; }
public decimal High { get; internal set; }
public decimal Low { get; internal set; }
public decimal Close { get; internal set; }
public long Volume { get; internal set; }
public decimal AdjustedClose { get; internal set; }
}
}
using System;

namespace YahooFinanceApi
{
public sealed class Candle: ITick
{
public DateTime DateTime { get; internal set; }

public decimal Open { get; internal set; }

public decimal High { get; internal set; }

public decimal Low { get; internal set; }

public decimal Close { get; internal set; }

public long Volume { get; internal set; }

public decimal AdjustedClose { get; internal set; }
}
}
41 changes: 41 additions & 0 deletions YahooFinanceApi/ChartDataLoader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;

namespace YahooFinanceApi;

public static class ChartDataLoader
{
public static async Task<dynamic> GetResponseStreamAsync(string symbol, DateTime startTime, DateTime endTime, Period period, string events, CancellationToken token)
{
var url = "https://query2.finance.yahoo.com/v8/finance/chart/"
.AppendPathSegment(symbol)
.SetQueryParam("period1", startTime.ToUnixTimestamp())
.SetQueryParam("period2", endTime.ToUnixTimestamp())
.SetQueryParam("interval", $"1{period.Name()}")
.SetQueryParam("events", events)
.SetQueryParam("crumb", YahooSession.Crumb);

Debug.WriteLine(url);

var response = await url
.WithCookie(YahooSession.Cookie.Name, YahooSession.Cookie.Value)
.WithHeader(YahooSession.UserAgentKey, YahooSession.UserAgentValue)
// .AllowHttpStatus("500")
.GetAsync(token);

var json = await response.GetJsonAsync();

var error = json.chart?.error?.description;
if (error != null)
{
throw new InvalidDataException($"An error was returned by Yahoo: {error}");
}

return json;
}
}
Loading