QuantConnect / Lean.DataSource.Polygon

LEAN Polygon Data Source
3 stars 5 forks source link

Polygon DataDownloader fails to download historical option quotes #17

Closed omidkrad closed 3 weeks ago

omidkrad commented 1 month ago

Expected Behavior

Able to download options quote data with Polygon

Actual Behavior

Polygon downloader waits for extended time for quote data which causes the runtime to time out and exit.

Potential Solution

Review and address

Reproducing the Problem

See details in the next post below.

System Information

Windows 10

Checklist

omidkrad commented 1 month ago

---- REPRO STEPS ---- Using Polygon data downloader fails for querying options quote data. Here's the algo to reproduce:

using System;
using QuantConnect;
using QuantConnect.Algorithm;
using QuantConnect.Brokerages;
using QuantConnect.Data;

public class SampleOptionAlgo : QCAlgorithm
{
    public override void Initialize()
    {
        var endDate = DateTime.Today.AddDays(-1);
        var startDate = endDate.AddDays(-3);
        SetStartDate(startDate);
        SetEndDate(endDate);

        SetCash(100000);
        SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin);

        var equity = AddEquity("SPY", Resolution.Minute).Symbol;
        Securities[equity].SetDataNormalizationMode(DataNormalizationMode.Raw);
        SetBenchmark(equity);

        var option = AddOption(equity, Resolution.Minute);
        option.SetFilter(-5, 5, TimeSpan.FromDays(20), TimeSpan.FromDays(60));
    }

    public override void OnData(Slice data)
    {
        foreach (var (symbol, optionChain) in data.OptionChains)
        {
            foreach (var option in optionChain)
            {
                Log($"Received {option}");
            }
        }
    }

}

(1) I made sure to have correct data subscriptions with Polygon.io and that they are active.

(4) After setting up Lean CLI to use Polygon, lean.json has the followings set:

    "id": "Polygon",
    "data-provider": "QuantConnect.Lean.Engine.DataFeeds.DownloaderDataProvider",
    "data-downloader": "QuantConnect.Lean.DataSource.Polygon.PolygonDataDownloader",
    "polygon-api-key": "<api key>",

(3) I run the algo with the following command:

lean backtest SampleOptionAlgo --data-provider-historical "Polygon"

Log shows that Advanced Polygon.io subscription plan is needed:

20240721 19:04:51.722 TRACE:: PolygonDataProvider.IsSupported(): Subscription for
Option-QuantConnect.Data.Market.QuoteBar-Quote-Minute will be attempted. An Advanced Polygon.io subscription plan is
required to stream quote data.

We have Advanced subscription plan but for some reason it still uses Isolator.ExecuteWithTimeLimit() that I think it's there to delay download requests. The algo fails after 20 minutes.

20240721 19:24:20.862 ERROR:: Security.ExecuteWithTimeLimit(): Algorithm took longer than 20 minutes on a
single time loop. CurrentTimeStepElapsed: 20.0 minutes

Log shows that the stock data for the last 3 days get downloaded but option data fails to download. Also can confirm that from the downloaded files in the data folder.

From the logs:

DATA USAGE:: Total data requests 10
DATA USAGE:: Succeeded data requests 3
DATA USAGE:: Failed data requests 7
Martin-Molinero commented 1 month ago

Hey @omidkrad! Please use the lean cli download functionality https://github.com/QuantConnect/lean-cli?tab=readme-ov-file#lean-data-download, the option chains are big so it can happen that it times out

omidkrad commented 1 month ago

Hi @Martin-Molinero, I don't see almost any download traffic on the internet, so not sure if it's downloading anything.

I have also tried the downloader to no avail.

Requesting Trade data:

lean data download --data-provider-historical "Polygon" --market USA --data-type Trade --resolution Minute --security-type Option --ticker SPY241220P00550000 --start 20240718 --end 20240719

I have tried passing the ticker in different ways:

20240722 18:51:04.513 TRACE:: DownloaderDataProvider.Main(): No data available for the following parameters: Symbol:
SPY241220P00550000 2U|SPY241220P00550000 2T, Resolution: Minute, StartUtc: 7/18/2024 12:00:00 AM, EndUtc: 7/19/2024
12:00:00 AM, TickType: Trade

Requesting Quote data:

lean data download --data-provider-historical "Polygon" --market USA --data-type Quote --resolution Minute --security-type Option --ticker SPY241220P00550000 --start 20240718 --end 20240719

Same as above tried different ways to specify ticker, none worked.

omidkrad commented 1 month ago

I tried a bit more, I had to correct something in lean.json:

lean.json

    "id": "Polygon",
    "data-provider": "QuantConnect.Lean.Engine.DataFeeds.DownloaderDataProvider",
    "data-downloader": "QuantConnect.Lean.DataSource.Polygon.PolygonDataDownloader",
    "polygon-api-key": "<api key>",

Trying to get option quotes only for one day on OXY.

SampleOptionAlgo.cs

public class SampleOptionAlgo : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2024, 7, 18);
        SetEndDate(2024, 7, 19);
        SetCash(100000);

        SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin);
        var equity = AddEquity("OXY", Resolution.Minute).Symbol;
        Securities[equity].SetDataNormalizationMode(DataNormalizationMode.Raw);
        SetBenchmark(equity);

        var option = AddOption(equity, Resolution.Minute);
        option.SetFilter(-1, 1, TimeSpan.FromDays(20), TimeSpan.FromDays(60));
    }

    public override void OnData(Slice data)
    {
        foreach (var (symbol, optionChain) in data.OptionChains)
        {
            foreach (var option in optionChain)
            {
                Log($"Received {option}");
            }
        }
    }

}

Command

lean backtest SampleOptionAlgo --data-provider-historical "Polygon" --verbose

I get a new error:

.
.
.
20240723 21:47:32.027 DEBUG:: LeanDataWriter.Write(OXY YK98T98Y34YU|OXY 2T): Appended:
/Lean/Data/option/usa/minute/oxy/20240719_trade_american.zip @
20240719_oxy_minute_trade_american_call_620000_20240719.csv 20240719->20240719
20240723 21:47:32.110 ERROR:: <>c__DisplayClass9_0.<Fetch>b__0():  System.Exception: The data must be
pre-sorted from oldest to newest
   at QuantConnect.Data.LeanDataWriter.Write(IEnumerable`1 source) in
/LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/Lean/Common/Data/LeanDataWriter.cs:line 134
   at QuantConnect.Lean.Engine.DataFeeds.DownloaderDataProvider.<>c__DisplayClass9_0.<Fetch>b__0(String s) in
/LeanCloud/CI.Builder/bin/Debug/src/QuantConnect/Lean/Engine/DataFeeds/DownloaderDataProvider.cs:line 185
20240723 21:47:32.140 DEBUG:: LeanData.TryParsePath(): Failed to parse
'/Lean/Data/equity/usa/factor_files/oxy.csv' unexpected Resolution
20240723 21:47:32.314 DEBUG:: DataManager.AddSubscription(): Added OXY,#0,OXY,Minute,TradeBar,Trade,Raw,OpenInterest.
Start: 7/18/2024 4:00:00 AM. End: 7/20/2024 3:59:59 AM
20240723 21:47:32.319 DEBUG:: DataManager.AddSubscription(): Added OXY,#0,OXY,Minute,QuoteBar,Quote,Raw,OpenInterest.
Start: 7/18/2024 4:00:00 AM. End: 7/20/2024 3:59:59 AM
20240723 21:47:32.324 DEBUG:: DataMonitor.OnNewDataRequest(): Data from /equity/usa/minute/oxy/20240718_quote.zip could
not be fetched
20240723 21:47:32.327 DEBUG:: UniverseSelection.ApplyUniverseSelection(): 7/18/2024 4:00:00 AM: SecurityChanges:  Added:
OXY 2T
20240723 21:47:32.331 DEBUG:: DataMonitor.OnNewDataRequest(): Data from /equity/usa/minute/oxy/20240719_quote.zip could
not be fetched
20240723 21:47:32.337 DEBUG:: DataManager.RemoveSubscription(): Removed
OXY,#0,OXY,Minute,QuoteBar,Quote,Raw,OpenInterest
20240723 21:47:32.338 DEBUG:: Synchronizer.SubscriptionFinished(): Finished
subscription:OXY,#0,OXY,Minute,QuoteBar,Quote,Raw,OpenInterest at 7/18/2024 4:00:00 AM UTC
20240723 21:47:32.353 DEBUG:: DataManager.AddSubscription(): Added
OXY,#0,OXY,Hour,TradeBar,Trade,Adjusted,OpenInterest,Internal. Start: 7/17/2024 4:00:00 AM. End: 7/20/2024 3:59:59 AM
20240723 21:47:32.354 TRACE:: UniverseSelection.AddPendingInternalDataFeeds(): Adding internal benchmark data feed
OXY,#0,OXY,Hour,TradeBar,Trade,Adjusted,OpenInterest,Internal
20240723 21:47:32.371 DEBUG:: PolygonRestApi.DownloadAndParseData(): Downloading
v2/aggs/ticker/OXY/range/1/hour/883699200000/1721606400000
20240723 21:47:32.699 DEBUG:: PolygonRestApi.DownloadAndParseData(): Downloading
https://api.polygon.io/v2/aggs/ticker/OXY/range/1/hour/1659549600000/1721606400000
20240723 21:47:33.108 DEBUG:: PolygonRestApi.DownloadAndParseData(): Downloading
https://api.polygon.io/v2/aggs/ticker/OXY/range/1/hour/1660575600000/1721606400000
20240723 21:47:33.394 DEBUG:: PolygonRestApi.DownloadAndParseData(): Downloading
https://api.polygon.io/v2/aggs/ticker/OXY/range/1/hour/1661378400000/1721606400000
20240723 21:47:33.820 DEBUG:: PolygonRestApi.DownloadAndParseData(): Downloading
https://api.polygon.io/v2/aggs/ticker/OXY/range/1/hour/1662483600000/1721606400000
20240723 21:47:34.145 DEBUG:: PolygonRestApi.DownloadAndParseData(): Downloading
https://api.polygon.io/v2/aggs/ticker/OXY/range/1/hour/1663333200000/1721606400000
20240723 21:47:34.549 DEBUG:: LeanDataWriter.Write(OXY 2T): Appended: /Lean/Data/equity/usa/hour/oxy.zip @ oxy.csv
20220725->20220916
20240723 21:47:34.567 DEBUG:: DataManager.RemoveSubscription(): Removed
OXY,#0,OXY,Hour,TradeBar,Trade,Adjusted,OpenInterest,Internal
20240723 21:47:34.567 DEBUG:: Synchronizer.SubscriptionFinished(): Finished
subscription:OXY,#0,OXY,Hour,TradeBar,Trade,Adjusted,OpenInterest,Internal at 7/18/2024 4:00:00 AM UTC
20240723 21:47:34.652 TRACE:: ScheduledEvent.Daily Sampling: Firing at 2024-07-18 04:00:00 UTC Scheduled at 2024-07-18
04:00:00 UTC
20240723 21:47:34.665 DEBUG:: BaseResultsHandler.SamplePerformance(): 4:00 AM >0.0
20240723 21:47:34.691 TRACE:: ScheduledEvent.Daily Sampling: Next event: 2024-07-19 04:00:00 UTC
20240723 21:47:34.770 DEBUG:: DataManager.SubscriptionManagerGetOrAdd(): subscription already added:
OXY,#0,OXY,Minute,TradeBar,Trade,Raw,OpenInterest
20240723 21:47:34.770 DEBUG:: DataManager.SubscriptionManagerGetOrAdd(): subscription already added:
OXY,#0,OXY,Minute,QuoteBar,Quote,Raw,OpenInterest
20240723 21:47:34.772 DEBUG:: DataManager.AddSubscription(): Added OXY,#0,OXY,Minute,QuoteBar,Quote,Raw,OpenInterest.
Start: 7/18/2024 1:31:00 PM. End: 7/20/2024 3:59:59 AM
20240723 21:47:34.774 DEBUG:: UniverseSelection.ApplyUniverseSelection(): 7/18/2024 1:31:00 PM: SecurityChanges:  Added:
OXY 2T
20240723 21:47:34.775 DEBUG:: DataMonitor.OnNewDataRequest(): Data from /equity/usa/minute/oxy/20240718_quote.zip could not be fetched
20240723 21:47:34.780 DEBUG:: DataMonitor.OnNewDataRequest(): Data from /equity/usa/minute/oxy/20240719_quote.zip could not be fetched
20240723 21:47:34.782 DEBUG:: DataManager.RemoveSubscription(): Removed
OXY,#0,OXY,Minute,QuoteBar,Quote,Raw,OpenInterest
20240723 21:47:34.783 DEBUG:: Synchronizer.SubscriptionFinished(): Finished
subscription:OXY,#0,OXY,Minute,QuoteBar,Quote,Raw,OpenInterest at 7/18/2024 1:31:00 PM UTC
20240723 21:47:34.807 TRACE:: ScheduledEvent.Daily Sampling: Firing at 2024-07-19 04:00:00 UTC Scheduled at 2024-07-19
04:00:00 UTC
20240723 21:47:34.808 DEBUG:: BaseResultsHandler.SamplePerformance(): 4:00 AM >0
20240723 21:47:34.810 TRACE:: ScheduledEvent.Daily Sampling: Next event: 2024-07-20 04:00:00 UTC
20240723 21:47:34.831 DEBUG:: DataManager.RemoveSubscription(): Removed
OXY,#0,OXY,Minute,TradeBar,Trade,Raw,OpenInterest
20240723 21:47:34.832 DEBUG:: Synchronizer.SubscriptionFinished(): Finished
subscription:OXY,#0,OXY,Minute,TradeBar,Trade,Raw,OpenInterest at 7/19/2024 8:00:00 PM UTC
20240723 21:47:34.833 DEBUG:: DataManager.RemoveSubscription(): Removed
?OXY,#0,OXY,Minute,ZipEntryName,Quote,Raw,OpenInterest
20240723 21:47:34.834 DEBUG:: Synchronizer.SubscriptionFinished(): Finished
subscription:?OXY,#0,OXY,Minute,ZipEntryName,Quote,Raw,OpenInterest at 7/19/2024 8:00:00 PM UTC
20240723 21:47:34.835 TRACE:: Synchronizer.GetEnumerator(): Exited thread.
20240723 21:47:34.837 TRACE:: AlgorithmManager.Run(): Firing On End Of Algorithm...
20240723 21:47:34.839 DEBUG:: BaseResultsHandler.SamplePerformance(): 8:00 PM >0
20240723 21:47:34.840 TRACE:: Engine.Run(): Exiting Algorithm Manager
20240723 21:47:34.853 DEBUG:: DataManager.RemoveSubscription(): Removed
QC-UNIVERSE-USERDEFINED-USA-EQUITY,#0,QC-UNIVERSE-USERDEFINED-USA-EQUITY,Minute,TradeBar,Trade,Adjusted,OpenInterest,Int
ernal
20240723 21:47:34.857 TRACE:: StopSafely(): Waiting for 'Isolator Thread' thread to stop...
20240723 21:47:34.859 TRACE:: FileSystemDataFeed.Exit(): Start. Setting cancellation token...
20240723 21:47:34.869 TRACE:: FileSystemDataFeed.Exit(): Exit Finished.
20240723 21:47:34.870 TRACE:: BacktestingResultHandler.Exit(): starting...
20240723 21:47:34.871 TRACE:: BacktestingResultHandler.Exit(): Saving logs...
20240723 21:47:34.883 TRACE:: StopSafely(): Waiting for 'Result Thread' thread to stop...
20240723 21:47:35.078 TRACE:: Debug: Algorithm Id:(1142883378) completed in 94.58 seconds at 0k data points per second.
Processing total of 8,191 data points.
20240723 21:47:35.078 TRACE:: Debug: Your log was successfully created and can be retrieved from:
/Results/1142883378-log.txt
20240723 21:47:35.079 TRACE:: BacktestingResultHandler.Run(): Ending Thread...
20240723 21:47:35.134 TRACE::
STATISTICS:: Total Orders 0
STATISTICS:: Average Win 0%
STATISTICS:: Average Loss 0%
STATISTICS:: Compounding Annual Return 0%
STATISTICS:: Drawdown 0%
STATISTICS:: Expectancy 0
STATISTICS:: Start Equity 100000
STATISTICS:: End Equity 100000
STATISTICS:: Net Profit 0%
STATISTICS:: Sharpe Ratio 0
STATISTICS:: Sortino Ratio 0
STATISTICS:: Probabilistic Sharpe Ratio 0%
STATISTICS:: Loss Rate 0%
STATISTICS:: Win Rate 0%
STATISTICS:: Profit-Loss Ratio 0
STATISTICS:: Alpha 0
STATISTICS:: Beta 0
STATISTICS:: Annual Standard Deviation 0
STATISTICS:: Annual Variance 0
STATISTICS:: Information Ratio 0
STATISTICS:: Tracking Error 0
STATISTICS:: Treynor Ratio 0
STATISTICS:: Total Fees $0.00
STATISTICS:: Estimated Strategy Capacity $0
STATISTICS:: Lowest Capacity Asset
STATISTICS:: Portfolio Turnover 0%
STATISTICS:: OrderListHash d41d8cd98f00b204e9800998ecf8427e
20240723 21:47:35.135 TRACE:: BacktestingResultHandler.SendAnalysisResult(): Processed final packet
20240723 21:47:35.140 TRACE:: Engine.Run(): Disconnecting from brokerage...
20240723 21:47:35.141 TRACE:: Engine.Run(): Disposing of setup handler...
20240723 21:47:35.143 TRACE:: Engine.Main(): Analysis Completed and Results Posted.
20240723 21:47:35.144 TRACE:: StopSafely(): Waiting for '' thread to stop...
20240723 21:47:35.155 TRACE:: DataMonitor.GenerateReport():
DATA USAGE:: Total data requests 14
DATA USAGE:: Succeeded data requests 6
DATA USAGE:: Failed data requests 8
DATA USAGE:: Failed data requests percentage 57%
DATA USAGE:: Total universe data requests 0
DATA USAGE:: Succeeded universe data requests 0
DATA USAGE:: Failed universe data requests 0
DATA USAGE:: Failed universe data requests percentage 0%
Engine.Main(): Analysis Complete.
20240723 21:47:35.172 TRACE:: Engine.Main(): Packet removed from queue: 1142883378
20240723 21:47:35.173 TRACE:: LeanEngineSystemHandlers.Dispose(): start...
20240723 21:47:35.175 TRACE:: LeanEngineSystemHandlers.Dispose(): Disposed of system handlers.
20240723 21:47:35.176 TRACE:: LeanEngineAlgorithmHandlers.Dispose(): start...
20240723 21:47:35.185 TRACE:: LeanEngineAlgorithmHandlers.Dispose(): Disposed of algorithm handlers.
20240723 21:47:35.189 TRACE:: StopSafely(): Waiting for 'CpuPerformance' thread to stop...
20240723 21:47:35.190 TRACE:: Program.Main(): Exiting Lean...
Successfully ran 'SampleOptionAlgo' in the 'backtesting' environment and stored the output in
'SampleOptionAlgo\backtests\2024-07-23_14-45-36'
jhonabreul commented 3 weeks ago

Should be fixed by #18