Commit Graph

67 Commits

Author SHA1 Message Date
Michael Handschuh 39935552a3 Convert ObjectStore ext class to implement IObjectStore for API
Since extension methods don't play well with pythonnet, this change converts
the extensions class into a decorator class. Additionally, this ObjectStore
type is the type that gets exposed via QCAlgorithm so users can access these
methods directly without requiring the use of extension methods.

This approach has many good properties. For one, it doesn't force implementors
of IObjectStore to use a base class. Second, it maintains healthy separation of
API level concerns (such as convenient methods) from the  abstraction level conerns
of IObjectStore. Setting it up in this way ensures ANY implementation of IObjectStore
will still get access to these additional methods. Another thing to note is this
prevents using a base class on QCAlgorithm's public interface. Instead, we have a
specific type that is dedicated to fulfilling API level requirements, which also
provides us flexibility in the event the API needs to be updated. If it were a subclass,
you run the risk of breaking the implementors of the subclass.
2019-12-31 15:55:16 -05:00
Martin Molinero 3a5a2c582f Lazy OnEndOfDay ScheduledEvent
- Only add OnEndOfDay ScheduledEvent if the algorithm implements the
method. Adding unit tests
- Avoid creating a new baseData instance at
`SubscriptionDataSourceReader`
- Adding static `FineFundamental` instance since creating new ones is
expensive
2019-12-19 19:07:16 -03:00
Stefano Raggi d407307566 Add IObjectStore interface with LocalObjectStore implementation
This commit is squashed from iterative development:

- More consistent method naming
- Storage root path updated to be absolute and include algorithm name
- Storage root path created only if object store is actually used
- Implemented XML save/load
- Added missing unit tests
- Replaced Log.Trace with Log.Error calls
- Added the object store name logging in Engine.Main
- Read storage root from config
- Create algorithm storage root folder in Initialize
- Remove empty folder in Dispose
- Added null checks in all methods
- Added missing XML parameter docs
- make Initialize and Dispose virtual
- make AlgorithmStorageRoot protected

The IObjectStore abstraction provides algorithms with a persistent
storage mechanism. While the algorithm is running, data is maintained
in memory as a dictionary of raw bytes (string -> byte[]). This ensures
we avoid any reference type shenanigans. Periodically, the data in the
object store is persisted and additionally, when the algorithm shuts
down, the object store's data will again be persisted. This ensures that
when the algorithm starts up again, it will have access to any state
that has been saved into the object store.

A great use case for IObjectStore is saving a compute heavy model.
For example, computing the weights of a deep neural network is very
CPU intensive, but after the weights are computed, evaluation is fairly
quick. An initial backtest can be used to solved for the network's weights
and then subsequent backtests or even in live mode, the weights will be
available to the algorithm provided they were saved into the object store.

Also, some libraries require a file path to load model data. The object
store provides a `GetFilePath(key)` method which will copy the data for
the provided key to the disk and return that path so the library can load
the model data.
2019-12-17 22:21:11 -05:00
Martin Molinero 2aeed3595d Algorithm will respect job dates if present
- Console and Backtesting setup handler will use job dates if present
(not the brokerage setup handler)
- Adding unit test
2019-11-08 17:51:33 -03:00
Martin Molinero 68ad2f51b6 Address reviews
- Replacing `BaseData.AdjustResolution` for `DefaultResolution` and
`SupportedResolutions`
- Making `Resolution` nullable for `Algorithm.AddData` methods
- The `ISubscriptionDataConfigService` will set the default resolution
if none was provided and assert it is supported
- Fix bug with `PythonData` `IsSparseData` and `RequiresMapping`
resolution
2019-11-04 20:42:30 -03:00
Martin Molinero 1d43dcd601 Add BaseData.AdjustResolution
- Adding `BaseData.AdjustResolution()` that should return a valid
resolution for the given data and security type.
This allows us to set a limitation which is useful to avoid invalid data
requests or unnecessary fill forward situations. The user will be
notified through a console message.
- Adding unit and regression test
- Updating example algorithms custom data resolution
- Some performance improvements. Wont change console color if
`SelectedOptimization` is defined
2019-11-04 20:38:26 -03:00
AlexCatarino 7865516a7a Refactors AlgorithmPythonWrapper.OnFrameworkData 2019-10-16 22:36:34 +01:00
AlexCatarino d55eaae231 Uses the same instance wthether there is custom data or not. 2019-10-16 22:25:27 +01:00
AlexCatarino 24d0ba392d Wraps Slice Object with PythonSlice for Python Framework Algorithms
Wraps `Slice` object with `PythonSlice` for Python framework algorithms when alternative/custom data is present.
2019-10-16 20:13:50 +01:00
Martin Molinero 27ce9489a4 Check if Python OnMarginCall is defined
- Will check if python OnMarginCall is defined and throw is returns null
or empty list
- Adding unit tests
2019-10-16 11:49:12 -03:00
Martin Molinero f887c42638 Enable python and CSharp debugging
- Adding `DebuggerHelper` class, handles debugging initialization
- Setting the "PYTHONPATH" will be handled by the `JobQueue`
2019-08-12 22:03:13 -03:00
AlexCatarino 0f114df756 Mute Python Library Logging
Redirects Python standard output (`sys.stdout`) to `devull`
2019-08-05 17:32:03 +01:00
Jared 992d721d08 Revert "Reduce python load time 30% (#3440)" (#3441)
Reverts test commit 70017f0e05.
2019-07-28 18:37:34 -07:00
Jared 70017f0e05 Reduce python load time 30% (#3440)
Optimize python load times
2019-07-28 17:20:52 -07:00
Martin Molinero a92bee5bf1 Fix OnEndOfDay not fired
- Adding `IRealTimeHandler.OnSecurityChanged()` will be used to update
the `OnEndOfDay` security related scheduled events
- Adding `BaseRealTimeHandler.cs` to reduce code duplication in the
`Backtesting` and `LiveTrading` `RealTimeHandlers`
- Adding CSharp and Python regression tests
- Deprecating `OnEndOfDay()` callback because of two reasons, mainly
because Python does not support two methods with the same name, but also
because different assets have different market close times.
- `ScheduledEvents` set at the same time will now be deterministic
2019-06-20 17:35:28 -03:00
Jared 66c66abb12 Implement API download for QCALgorithm (#3215)
* Implementing download proxy for LEAN

* Remove accidentally added files

* Remove accidentally added files

* Tidy up
2019-05-20 18:34:19 -07:00
Martin Molinero fa122fa809 Add missing PyObject.Dispose calls
- Adding _some_ of the missing PyObject.Dispose calls. In the cases
where C# is calling the Python side.
   - Note that Python calls to C# code is correctly handling the
   disposure of resources.
2019-04-10 15:03:10 -03:00
Martin Molinero cfa08a11fb Address reviews
- Removing `using QCAlgorithmFramework = QuantConnect.Algorithm.QCAlgorithm`
- Removing `QCAlgorithmFrameworkBridge`
- Removing `IsFrameworkAlgorithm`
- Making `EmitInsightBasedOnFill` private. Adding new
`IOrderEventProvider` exposing an `event` to which `QCAlgorithm` will
subscribe.
- `AccountType.Cash` algorithms will be allowed to manually trade and
emight insights manually or with alpha model.
2019-04-03 21:55:44 -03:00
Martin Molinero 32ac3146b4 Merge Framework and Classic Algorithms
- Merging Framework and Bridge algorithms into classic QCAlgorithm
class.
- Removing Framework project, VS17 and VS15
2019-04-03 21:54:32 -03:00
Martin Molinero 5b04cfe202 Emiting Insights based on Fills
- Classic Algorithms will emight insights based on order fills.
   - To be able to update generated insights closed time, we will not
   clone emitted insights.
   - `InsightAnalysisContext` will update `AnalysisEndTimeUtc` when the
   Insight period is closed and the period is `EndOfTimeTimeSpan`
- Adding new regression algorithm asserting on the new emitted insights
- Adding unit tests
- `LiveTradingResultHandler` will store `AlphaRunTimeStatistics`
- Making `DefaultAlphaHandler.ProcessAsynchronousEvents` virtual to
facilitate cloud changes
2019-03-26 16:09:22 -03:00
Martin Molinero 1b0bdd9b0b Adding SetAccountCurrency for backtesting
- Adding new `SetAccountCurrency()` for backtesting. Has to be called
before adding any `Security` or calling `SetCash()`, else will throw.
- Adding new Non account currency unit tests for `CashBuyingPower`,
`SecurityPortfolioModel`, `SecurityMarginModel`,
`SecurityPortfolioManager`, `Future/OptionMarginBuyingPowerModels`
- Adding new C# regression test using `SetAccountCurrency()`, one for
`CashBuyingPowerModel` and one for `SecurityMarginModel`
- Adding new Py and C# basic regression algorithms using
`SetAccountCurrency()`
- `Options` and `Futures` will use not use `AccountCurrency` as quote
Cash.
- `SecurityBenchmark` value will be in account currency
2019-01-25 14:54:43 -03:00
Martin Molinero b60df26852 Keep OnData and OnOrderEvent python reference
- `AlgorithmPythonWrapper` will now keep reference to the `OnData` and
`OnOrderEvent` `PyObject` method, giving a performance improvement,
since it does not have to resolve it in each loop.
2019-01-09 19:32:19 -03:00
Martin Molinero a993c4932a Address reviews
- Some performance improvements
- Method renaming
2018-12-21 19:27:22 -03:00
Martin Molinero 65ea963a26 Using new HistoryRequestFactory
- BaseSetupHandler will use new `HistoryRequestProvider` class
2018-12-19 16:15:29 -03:00
Martin Molinero af8e6bf85c Fix starting capital for non usd cash
- Moving `UniverseSelection.EnsureCurrencyDataFeeds` call into the
`IResultHandler` implementation through usage of the new `SetupHandlerHelper`
class, that will also set an initial conversion rate if none present.
- Adding regression test, that reproduces original issue
2018-12-19 16:15:28 -03:00
Martin Molinero 75ffa300f1 Adding new IAlgorithm.AccountCurrency
- Adding new `IAlgorithm.AccountCurrency { get; }` that will point to the
`Portfolio.CashBook.AccountCurrency`. Setter will be added in a
following PR.
- Base `Brokerage` class will now have a `AccountCurrency { get }`
pointing to the `IAccountCurrencyProvider`. Will be used by the different
brokerages implementations.
2018-12-10 11:59:02 -03:00
Michael Handschuh cb2e5cdc5b Expose IAlgorithm.CurrentSlice
IAlgorithm exposed a means of setting the CurrentSlice but not a
means for consumers to get the value. This was because until now
all consumers were within the QCAlgorithm scope and had access to
the member variable. This change makes the CurrentSlice available
to LEAN engine code, where it's first use will be in PaperBrokerage
to detect and apply dividend distributions.
2018-10-04 14:00:43 -04:00
Martin Molinero 008c9ca873 Fixing unit tests 2018-09-28 15:44:05 -03:00
Martin Molinero 6da57a1e12 Improving GetMaximumOrderQuantityForTargetValue 2018-08-03 16:26:14 -03:00
Stefano Raggi bbfe7a9beb Rename LatestSlice to CurrentSlice 2018-06-05 19:05:40 +02:00
Stefano Raggi 08f28a55cf Make the latest Slice received in OnData available to the algorithm 2018-06-01 18:24:09 +02:00
Michael Handschuh dd764ad8e9 Rename InsightCollection->GeneratedInsightsCollection
This type is just used as a container for generatd insights. Renaming in
preparation for a new InsightCollection to mirror the PortfolioTargetCollection
2018-04-10 19:24:36 -04:00
AlexCatarino 5963f7e372 Refactors OnFrameworkData in AlgorithmPythonWrapper
`AlgorithmPythonWrapper.OnFrameworkData` should call the base class method (`QCAlgorithmFramework.OnFrameworkData`) directly instead of trying to call this method from the python script
2018-03-28 10:44:55 +01:00
Jared c896e08656 Merge pull request #1720 from QuantConnect/bug-1689-apply-security-changes-at-end-of-time-step
Apply security changes at end of time step
2018-03-20 15:48:02 -04:00
Michael Handschuh 27b34a4274 Add IAlgorithm.OnEndOfTimeStep to batch universe changes
We had an issue with the data feed picking up universe/security changes
too quickly, thereby preventing user code from being able to configure the
security object properly. Specifically, users were having an issue setting
the data normalization mode of options and underlying equity securities. By
the time the user code had set the data mode, the data feed had already
created a subscription and began processing it, so the changes were never
seen in the data feed.

This change moves all security/universe changes into pending lists and at
the end of the time step applies those changes. Security objects are still
added directly to the SecurityManager for instance access, but we delay in
adding the security to the universe and the universe to the UniverseManager.
Once added to the universe manager, an event is fired and the data feed will
process the new subscriptions.
2018-03-20 10:10:29 -04:00
AlexCatarino d5deabcb29 Fixes AlgorithmPythonWrapper.InsightsGenerated
This event was not properly wrapped.
When `IAlgorithm.InsightsGenerated` is set in `IAlphaHandler`, it should be directed to the base algorithm, whereas it was set to a null variable.
2018-03-19 11:15:57 +00:00
AlexCatarino 4e3577939d Refactors AlgorithmPythonWrapper
Move the logic of importing the module into AlgorithmPythonWrapper where it is wrapped.
Throws an exception if the script does not have a class that inherits from either QCAlgorithm not QCAlgorithmFramework.
Adds a check for OnData being defined in the module. If not, OnData from the base class will not be called (it causes stack overflow otherwise)
2018-03-12 23:36:39 +00:00
Michael Handschuh 6b239674e2 Renames Alpha -> Insight
The term 'alpha' is used to describe the entire algorithm. Therefore, 'alpha'
produces insights. From this we have things like IAlphaModel, which is the model
defining how insights are produced. We have IAlphaHandler, which defines how the
insights from a single 'alpha' (the algorithm) are managed, analyzed, and stored.
Types closer to the individual prediction level, such as InsightDirection, or
InsightScore relate directly to exactly 1 insight. The distinction between the
two became more clear as we developed the insights API, and from that effort it
was decided to harmonize alpha/insight terminology across the various QC systems.
2018-03-09 16:12:56 -05:00
AlexCatarino 1e594749a9 Fixes multiple OnEndOfDay error message
The error message it was used to bypass the the error logging has been changed from `takes exactly x arguments (y given)` to `takes x positional argument but y were given`.
2018-03-02 18:37:12 +00:00
AlexCatarino 9dfc8ee3a0 Adds PythonSlice static constructor
With this constructor, SetConverter method, that was not respecting Lean pattern, is removed. The initialization of _converter field is done once the type is loaded.
2018-02-12 16:23:23 +00:00
AlexCatarino cff1243b86 Creates wrapper for Slice (python custom data)
Python algorithms with custom data requires an operation that converts a dictionary key into a attribute. In the current implementation the Slice object was converted into a python dictionary. This was not optimal, since we just need to make this conversion when the value of a key in the Slice is accessed.
This implementation proposes a wrapper for the Slice object, PythonSlice, that would just perform the operation described above when needed.
2018-02-12 15:49:09 +00:00
AlexCatarino 2cfe77d10e Fixes OnWarmupFinished not firing in python algorithms 2018-01-15 18:43:38 +00:00
Stefano Raggi 89a59351cd Add OnWarmupFinished method to QCAlgorithm
This method is being added to allow algorithms to complete initialization tasks that cannot be executed during Initialize, such as cancelling existing open orders in live trading.
This method will be called only once, when the warmup task is complete.

Closes #1043
2018-01-15 13:46:30 +01:00
Michael Handschuh b4b3aae112 Rename Signal -> Alpha
Whoa... I think I got everything :)
2017-12-15 18:24:58 -05:00
Michael Handschuh d8ef289c9b Add IAlgorithm.IsFrameworkAlgorithm and BacktestingResut.IsFrameworkAlgorithm
Flag indicates whether or not the algorithm is a framework algorithm.
2017-12-14 19:43:26 -05:00
Michael Handschuh c879f4ee83 Chart average signal scores daily 2017-12-12 15:57:00 -05:00
Michael Handschuh 39f5080a40 Rename framework events to OnFramework<Event>
This more closely follows existing conventions.
2017-12-08 12:04:53 -05:00
Michael Handschuh c093b45319 Add IAlgorithm.SignalsGenerated event
This event will fire each time step that generates signals and will
include all signals generated by the algorithm at that time step.
2017-12-08 10:07:54 -05:00
Michael Handschuh 14a2a09581 Add explicit methods for updating framework models
IAlgorithm.FrameworkOnData is used to pulse models with new data each time step
IAlgorithm.FrameworkOnSecuritiesChanged is used to pulse models with security changes

These two functions need to be separate to ensure that if we add an indicator during
the securities changed event that it will get the data from the current time step.
This forces us to call the securities changed event before we invoke the consolidators
for the current time step.
2017-12-08 10:07:54 -05:00
AlexCatarino 70d67e3fb3 Fixes OnEndOfDay exceptions in python algorithms
The engine creates schedule events that call OnEndOfDay() and OnEndOdDay(Symbol) for every security. If just one of these method overloads is defined in the python script, the call of the other will throw a exception due different parameter count.
In this case, we will disregard this exception and throw those that may happen in the method implementation body.
2017-12-06 18:43:23 +00:00