Skip to content

Commit 53e59d9

Browse files
committed
Update regression algorithms to solve issues
1 parent 19444c6 commit 53e59d9

File tree

2 files changed

+88
-59
lines changed

2 files changed

+88
-59
lines changed

Algorithm.CSharp/PersistentCustomDataUniverseRegressionAlgorithm.cs

+49-32
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
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+
116
using System;
217
using System.Collections.Generic;
3-
using System.Globalization;
418
using System.Linq;
5-
using System.Threading.Tasks;
619
using QuantConnect.Data;
7-
using QuantConnect.Data.UniverseSelection;
820
using QuantConnect.Interfaces;
921

1022
namespace QuantConnect.Algorithm.CSharp
@@ -16,11 +28,12 @@ public class PersistentCustomDataUniverseRegressionAlgorithm : QCAlgorithm, IReg
1628

1729
public override void Initialize()
1830
{
19-
SetStartDate(2018, 1, 3);
20-
SetEndDate(2018, 1, 20);
31+
SetStartDate(2018, 6, 1);
32+
SetEndDate(2018, 6, 19);
2133

2234
var universe = AddUniverse<StockDataSource>("my-stock-data-source", Resolution.Daily, UniverseSelector);
2335
_universeSymbol = universe.Symbol;
36+
var history = History(_universeSymbol, new DateTime(2018, 1, 1), new DateTime(2018, 6, 1), Resolution.Daily).ToList();
2437
}
2538

2639
private IEnumerable<Symbol> UniverseSelector(IEnumerable<BaseData> data)
@@ -48,53 +61,57 @@ public override void OnEndOfAlgorithm()
4861
}
4962
}
5063

64+
5165
/// <summary>
5266
/// Our custom data type that defines where to get and how to read our backtest and live data.
5367
/// </summary>
54-
class StockDataSource : BaseData
68+
private class StockDataSource : BaseData
5569
{
56-
private const string Url = @"https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1";
57-
5870
public List<string> Symbols { get; set; }
5971

6072
public StockDataSource()
6173
{
6274
Symbols = new List<string>();
6375
}
6476

77+
public override DateTime EndTime
78+
{
79+
get { return Time + Period; }
80+
set { Time = value - Period; }
81+
}
82+
83+
public TimeSpan Period
84+
{
85+
get { return QuantConnect.Time.OneDay; }
86+
}
87+
6588
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
6689
{
67-
return new SubscriptionDataSource(Url, SubscriptionTransportMedium.RemoteFile);
90+
string source = @"..\..\..\Tests\TestData\daily-stock-picker-backtest.csv";
91+
return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv);
6892
}
6993

7094
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
7195
{
96+
if (string.IsNullOrWhiteSpace(line) || !char.IsDigit(line[0]))
97+
{
98+
return null;
99+
}
100+
101+
var stocks = new StockDataSource { Symbol = config.Symbol };
102+
72103
try
73104
{
74-
// create a new StockDataSource and set the symbol using config.Symbol
75-
var stocks = new StockDataSource { Symbol = config.Symbol };
76-
// break our line into csv pieces
77105
var csv = line.ToCsv();
78-
if (isLiveMode)
79-
{
80-
// our live mode format does not have a date in the first column, so use date parameter
81-
stocks.Time = date;
82-
stocks.Symbols.AddRange(csv);
83-
}
84-
else
85-
{
86-
// our backtest mode format has the first column as date, parse it
87-
stocks.Time = DateTime.ParseExact(csv[0], "yyyyMMdd", null);
88-
// any following comma separated values are symbols, save them off
89-
stocks.Symbols.AddRange(csv.Skip(1));
90-
}
91-
return stocks;
106+
stocks.Time = DateTime.ParseExact(csv[0], "yyyyMMdd", null);
107+
stocks.Symbols.AddRange(csv[1..]);
92108
}
93-
// return null if we encounter any errors
94-
catch
109+
catch (FormatException)
95110
{
96111
return null;
97112
}
113+
114+
return stocks;
98115
}
99116
}
100117

@@ -111,12 +128,12 @@ public override BaseData Reader(SubscriptionDataConfig config, string line, Date
111128
/// <summary>
112129
/// Data Points count of all timeslices of algorithm
113130
/// </summary>
114-
public long DataPoints => 26024;
131+
public long DataPoints => 8767;
115132

116133
/// <summary>
117134
/// Data Points count of the algorithm history
118135
/// </summary>
119-
public int AlgorithmHistoryDataPoints => 0;
136+
public int AlgorithmHistoryDataPoints => 149;
120137

121138
/// <summary>
122139
/// Final status of the algorithm
@@ -147,8 +164,8 @@ public override BaseData Reader(SubscriptionDataConfig config, string line, Date
147164
{"Beta", "0"},
148165
{"Annual Standard Deviation", "0"},
149166
{"Annual Variance", "0"},
150-
{"Information Ratio", "-12.133"},
151-
{"Tracking Error", "0.059"},
167+
{"Information Ratio", "-3.9"},
168+
{"Tracking Error", "0.045"},
152169
{"Treynor Ratio", "0"},
153170
{"Total Fees", "$0.00"},
154171
{"Estimated Strategy Capacity", "$0"},
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,33 @@
1-
import datetime
1+
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
2+
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
7+
#
8+
# Unless required by applicable law or agreed to in writing, software
9+
# distributed under the License is distributed on an "AS IS" BASIS,
10+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
# See the License for the specific language governing permissions and
12+
# limitations under the License.
13+
14+
from datetime import timedelta
215
from AlgorithmImports import *
316

17+
### <summary>
18+
### Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary
19+
### </summary>
420
class PersistentCustomDataUniverseRegressionAlgorithm(QCAlgorithm):
521

622
def Initialize(self):
7-
self.set_start_date(2018, 1, 3)
8-
self.set_end_date(2018, 1, 20)
23+
self.set_start_date(2018, 6, 1)
24+
self.set_end_date(2018, 6, 19)
925

1026
universe = self.add_universe(StockDataSource, "my-stock-data-source", Resolution.DAILY, self.universe_selector)
1127
self._universe_symbol = universe.symbol
28+
history = list(self.history[StockDataSource](universe.symbol, datetime(2018, 1, 1), datetime(2018, 6, 1), Resolution.DAILY))
29+
if (len(history) == 0):
30+
raise Exception(f"No historical data received for symbol {universe.symbol} and the given date range.")
1231
self._data_received = False
1332

1433
def universe_selector(self, data):
@@ -25,33 +44,26 @@ def OnEndOfAlgorithm(self) -> None:
2544

2645
class StockDataSource(PythonData):
2746

28-
def __init__(self):
29-
super().__init__()
30-
self.Symbols = []
31-
3247
def get_source(self, config: SubscriptionDataConfig, date: datetime, is_live: bool) -> SubscriptionDataSource:
33-
url = "https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1"
34-
return SubscriptionDataSource(url, SubscriptionTransportMedium.RemoteFile)
48+
source = "../../../Tests/TestData/daily-stock-picker-backtest.csv"
49+
return SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile, FileFormat.Csv)
3550

3651
def reader(self, config: SubscriptionDataConfig, line: str, date: datetime, is_live: bool) -> BaseData:
37-
if not line.strip():
38-
return None
52+
if not (line.strip() and line[0].isdigit()): return None
53+
54+
stocks = StockDataSource()
55+
stocks.symbol = config.symbol
3956

4057
try:
4158
csv = line.split(',')
42-
stocks = StockDataSource()
43-
stocks.Symbol = config.Symbol
44-
45-
if is_live:
46-
# In live mode, the first column does not contain a date, so we use the provided date
47-
stocks.Time = date
48-
stocks.Symbols.extend(csv)
49-
else:
50-
# In backtest mode, the first column contains the date
51-
stocks.Time = datetime.strptime(csv[0], "%Y%m%d")
52-
stocks.Symbols.extend(csv[1:])
53-
54-
return stocks
55-
56-
except Exception:
57-
return None
59+
stocks.time = datetime.strptime(csv[0], "%Y%m%d")
60+
stocks.end_time = stocks.time + self.period
61+
stocks["Symbols"] = csv[1:]
62+
63+
except ValueError:
64+
return None
65+
66+
return stocks
67+
@property
68+
def period(self) -> timedelta:
69+
return timedelta(days=1)

0 commit comments

Comments
 (0)