Skip to content

Commit

Permalink
Adds Python Support
Browse files Browse the repository at this point in the history
- Adds PyObject overload to `ScheduleManager.TrainingNow` and `ScheduleManager.Training`
- Adds `QCAlgorithm.Train` helper method
- Adds Python algorithm showing how to use the helper method.
  • Loading branch information
AlexCatarino authored and mchandschuh committed Oct 19, 2019
1 parent 28be3bb commit c37b450
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 0 deletions.
1 change: 1 addition & 0 deletions Algorithm.Python/QuantConnect.Algorithm.Python.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
<None Include="SmartInsiderDataAlgorithm.py" />
<None Include="PandasDataFrameHistoryAlgorithm.py" />
<None Include="CustomDataAddDataRegressionAlgorithm.py" />
<None Include="TrainingExampleAlgorithm.py" />
<Content Include="Benchmarks\SECReportBenchmarkAlgorithm.py" />
<Content Include="Benchmarks\SmartInsiderEventBenchmarkAlgorithm.py" />
<Content Include="CustomDataAddDataOnSecuritiesChangedRegressionAlgorithm.py" />
Expand Down
52 changes: 52 additions & 0 deletions Algorithm.Python/TrainingExampleAlgorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from time import sleep

### <summary>
### Example algorithm showing how to use QCAlgorithm.Train method
### </summary>
### <meta name="tag" content="using quantconnect" />
### <meta name="tag" content="training" />
class TrainingExampleAlgorithm(QCAlgorithm):
'''Example algorithm showing how to use QCAlgorithm.Train method'''

def Initialize(self):

self.SetStartDate(2013, 10, 7)
self.SetEndDate(2013, 10, 14)

self.AddEquity("SPY", Resolution.Daily)

# Set TrainingMethod to be executed immediately
self.Train(self.TrainingMethod)

# Set TrainingMethod to be executed at 8:00 am every Sunday
self.Train(self.DateRules.Every(DayOfWeek.Sunday), self.TimeRules.At(8 , 0), self.TrainingMethod)

def TrainingMethod(self):

self.Log(f'Start training at {self.Time}')
# Use the historical data to train the machine learning model
history = self.History(["SPY"], 200, Resolution.Daily)

# ML code:
pass
21 changes: 21 additions & 0 deletions Algorithm/QCAlgorithm.Python.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
using QuantConnect.Data.Fundamental;
using System.Linq;
using QuantConnect.Brokerages;
using QuantConnect.Scheduling;
using QuantConnect.Util;

namespace QuantConnect.Algorithm
Expand Down Expand Up @@ -1029,6 +1030,26 @@ public IDataConsolidator Consolidate(Symbol symbol, Func<DateTime, CalendarInfo>
return Consolidate(symbol, calendarType, null, handler);
}

/// <summary>
/// Schedules the provided training code to execute immediately
/// </summary>
/// <param name="trainingCode">The training code to be invoked</param>
public ScheduledEvent Train(PyObject trainingCode)
{
return Schedule.TrainingNow(trainingCode);
}

/// <summary>
/// Schedules the training code to run using the specified date and time rules
/// </summary>
/// <param name="dateRule">Specifies what dates the event should run</param>
/// <param name="timeRule">Specifies the times on those dates the event should run</param>
/// <param name="trainingCode">The training code to be invoked</param>
public ScheduledEvent Train(IDateRule dateRule, ITimeRule timeRule, PyObject trainingCode)
{
return Schedule.Training(dateRule, timeRule, trainingCode);
}

/// <summary>
/// Registers the <paramref name="handler"/> to receive consolidated data for the specified symbol
/// </summary>
Expand Down
21 changes: 21 additions & 0 deletions Algorithm/QCAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
using QuantConnect.Statistics;
using QuantConnect.Util;
using System.Collections.Concurrent;
using Python.Runtime;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Crypto;
using QuantConnect.Algorithm.Framework.Alphas;
Expand Down Expand Up @@ -2150,6 +2151,26 @@ public string Download(string address, IEnumerable<KeyValuePair<string, string>>
return _api.Download(address, headers, userName, password);
}

/// <summary>
/// Schedules the provided training code to execute immediately
/// </summary>
/// <param name="trainingCode">The training code to be invoked</param>
public ScheduledEvent Train(Action trainingCode)
{
return Schedule.TrainingNow(trainingCode);
}

/// <summary>
/// Schedules the training code to run using the specified date and time rules
/// </summary>
/// <param name="dateRule">Specifies what dates the event should run</param>
/// <param name="timeRule">Specifies the times on those dates the event should run</param>
/// <param name="trainingCode">The training code to be invoked</param>
public ScheduledEvent Train(IDateRule dateRule, ITimeRule timeRule, Action trainingCode)
{
return Schedule.Training(dateRule, timeRule, trainingCode);
}

/// <summary>
/// Event invocator for the <see cref="InsightsGenerated"/> event
/// </summary>
Expand Down
21 changes: 21 additions & 0 deletions Common/Scheduling/ScheduleManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,14 @@ public ScheduledEvent TrainingNow(Action trainingCode)
return On($"Training: Now: {_securities.UtcTime:O}", DateRules.Today, TimeRules.Now, trainingCode);
}

/// <summary>
/// Schedules the provided training code to execute immediately
/// </summary>
public ScheduledEvent TrainingNow(PyObject trainingCode)
{
return On($"Training: Now: {_securities.UtcTime:O}", DateRules.Today, TimeRules.Now, trainingCode);
}

/// <summary>
/// Schedules the training code to run using the specified date and time rules
/// </summary>
Expand All @@ -254,6 +262,19 @@ public ScheduledEvent Training(IDateRule dateRule, ITimeRule timeRule, Action tr
return On(name, dateRule, timeRule, (n, time) => trainingCode());
}


/// <summary>
/// Schedules the training code to run using the specified date and time rules
/// </summary>
/// <param name="dateRule">Specifies what dates the event should run</param>
/// <param name="timeRule">Specifies the times on those dates the event should run</param>
/// <param name="trainingCode">The training code to be invoked</param>
public ScheduledEvent Training(IDateRule dateRule, ITimeRule timeRule, PyObject trainingCode)
{
var name = $"{dateRule.Name}: {timeRule.Name}";
return On(name, dateRule, timeRule, (n, time) => { using (Py.GIL()) trainingCode.Invoke(); });
}

/// <summary>
/// Schedules the training code to run using the specified date and time rules
/// </summary>
Expand Down

0 comments on commit c37b450

Please sign in to comment.