qlib
qlib copied to clipboard
Fix: QlibDataLoader drops the cols added by inst_processor
Fix: QlibDataLoader drops the cols added by inst_processor
Description
When inst_processor
creates new columns, the QlibDataLoader
drops them.
Motivation and Context
How Has This Been Tested?
- [ ] Pass the test by running:
pytest qlib/tests/test_all_pipeline.py
under upper directory ofqlib
. - [ ] If you are adding a new feature, test on your own test scripts.
Screenshots of Test Results (if appropriate):
- Pipeline test:
- Your own tests:
Types of changes
- [ X] Fix bugs
- [ ] Add new feature
- [ ] Update documentation
@microsoft-github-policy-service agree
On Sun, Feb 5, 2023 at 10:19 AM microsoft-github-policy-service[bot] < @.***> wrote:
@xu-li https://github.com/xu-li please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.
@microsoft-github-policy-service agree [company="{your company}"]
Options:
- (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
- (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement Contribution License Agreement
This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”), and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your contributions to Microsoft open source projects. This Agreement is effective as of the latest signature date below.
- Definitions. “Code” means the computer software code, whether in human-readable or machine-executable form, that is delivered by You to Microsoft under this Agreement. “Project” means any of the projects owned or managed by Microsoft and offered under a license approved by the Open Source Initiative (www.opensource.org). “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any Project, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of discussing and improving that Project, but excluding communication that is conspicuously marked or otherwise designated in writing by You as “Not a Submission.” “Submission” means the Code and any other copyrightable material Submitted by You, including any associated comments and documentation.
- Your Submission. You must agree to the terms of this Agreement before making a Submission to any Project. This Agreement covers any and all Submissions that You, now or in the future (except as described in Section 4 below), Submit to any Project.
- Originality of Work. You represent that each of Your Submissions is entirely Your original work. Should You wish to Submit materials that are not Your original work, You may Submit them separately to the Project if You (a) retain all copyright and license information that was in the materials as You received them, (b) in the description accompanying Your Submission, include the phrase “Submission containing materials of a third party:” followed by the names of the third party and any licenses or other restrictions of which You are aware, and (c) follow any other instructions in the Project’s written guidelines concerning Submissions.
- Your Employer. References to “employer” in this Agreement include Your employer or anyone else for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your Submission is made in the course of Your work for an employer or Your employer has intellectual property rights in Your Submission by contract or applicable law, You must secure permission from Your employer to make the Submission before signing this Agreement. In that case, the term “You” in this Agreement will refer to You and the employer collectively. If You change employers in the future and desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement and secure permission from the new employer before Submitting those Submissions.
- Licenses.
- Copyright License. You grant Microsoft, and those who receive the Submission directly or indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third parties.
- Patent License. You grant Microsoft, and those who receive the Submission directly or indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under Your patent claims that are necessarily infringed by the Submission or the combination of the Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and import or otherwise dispose of the Submission alone or with the Project.
- Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement. No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are granted by implication, exhaustion, estoppel or otherwise.
- Representations and Warranties. You represent that You are legally entitled to grant the above licenses. You represent that each of Your Submissions is entirely Your original work (except as You may have disclosed under Section 3). You represent that You have secured permission from Your employer to make the Submission in cases where Your Submission is made in the course of Your work for Your employer or Your employer has intellectual property rights in Your Submission by contract or applicable law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You have the necessary authority to bind the listed employer to the obligations contained in this Agreement. You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
- Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which You later become aware that would make Your representations in this Agreement inaccurate in any respect.
- Information about Submissions. You agree that contributions to Projects and information about contributions may be maintained indefinitely and disclosed publicly, including Your name and other information that You submit with Your Submission.
- Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County, Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all defenses of lack of personal jurisdiction and forum non-conveniens.
- Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and supersedes any and all prior agreements, understandings or communications, written or oral, between the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.
— Reply to this email directly, view it on GitHub https://github.com/microsoft/qlib/pull/1430#issuecomment-1416903330, or unsubscribe https://github.com/notifications/unsubscribe-auth/AABJ5EIAAAXROEVXS2F7IJLWV4E4ZANCNFSM6AAAAAAURPQCJA . You are receiving this because you were mentioned.Message ID: @.***>
-- Thanks.
Xu Li, Shanghai, China
@xu-li Could you please add any tests for it? (It fails in previous version and success in current version)
Thanks.
The test pipeline seems to be broken already on Mac. See the output below. I am on 6295939346bfe619fe6eef5ffbe7c9252c3c9b09.
Am I doing something wrong?
% git rev-parse HEAD
6295939346bfe619fe6eef5ffbe7c9252c3c9b09
% pytest tests/test_all_pipeline.py
================================================================================================= test session starts ==================================================================================================
platform darwin -- Python 3.8.16, pytest-7.2.1, pluggy-1.0.0
rootdir: /XXXXXX/tests, configfile: pytest.ini
collected 3 items
tests/test_all_pipeline.py .F. [100%]
======================================================================================================= FAILURES =======================================================================================================
_____________________________________________________________________________________________ TestAllFlow.test_1_backtest ______________________________________________________________________________________________
self = <test_all_pipeline.TestAllFlow testMethod=test_1_backtest>
@pytest.mark.slow
def test_1_backtest(self):
analyze_df = backtest_analysis(TestAllFlow.PRED_SCORE, TestAllFlow.RID, self.URI_PATH)
> self.assertGreaterEqual(
analyze_df.loc(axis=0)["excess_return_with_cost", "annualized_return"].values[0],
0.05,
"backtest failed",
)
E AssertionError: -0.09994674991447777 not greater than or equal to 0.05 : backtest failed
tests/test_all_pipeline.py:166: AssertionError
------------------------------------------------------------------------------------------------- Captured stdout call -------------------------------------------------------------------------------------------------
'The following are analysis results of benchmark return(1day).'
risk
mean 0.000477
std 0.012295
annualized_return 0.113561
information_ratio 0.598699
max_drawdown -0.370479
'The following are analysis results of the excess return without cost(1day).'
risk
mean -0.000417
std 0.012286
annualized_return -0.099245
information_ratio -0.523614
max_drawdown -0.503287
'The following are analysis results of the excess return with cost(1day).'
risk
mean -0.000420
std 0.012286
annualized_return -0.099947
information_ratio -0.527307
max_drawdown -0.503838
'The following are analysis results of indicators(1day).'
value
ffr 1.0
pa 0.0
pos 0.0
risk
excess_return_without_cost mean -0.000417
std 0.012286
annualized_return -0.099245
information_ratio -0.523614
max_drawdown -0.503287
excess_return_with_cost mean -0.000420
std 0.012286
annualized_return -0.099947
information_ratio -0.527307
max_drawdown -0.503838
------------------------------------------------------------------------------------------------- Captured stderr call -------------------------------------------------------------------------------------------------
[73260:MainThread](2023-02-06 20:06:05,082) INFO - qlib.timer - [log.py:128] - Time cost: 71.856s | Loading data Done
[73260:MainThread](2023-02-06 20:06:06,395) INFO - qlib.timer - [log.py:128] - Time cost: 0.359s | DropnaLabel Done
[73260:MainThread](2023-02-06 20:06:10,730) INFO - qlib.timer - [log.py:128] - Time cost: 4.335s | CSZScoreNorm Done
[73260:MainThread](2023-02-06 20:06:10,759) INFO - qlib.timer - [log.py:128] - Time cost: 5.677s | fit & process data Done
[73260:MainThread](2023-02-06 20:06:10,760) INFO - qlib.timer - [log.py:128] - Time cost: 77.534s | Init data Done
[73260:MainThread](2023-02-06 20:06:10,789) INFO - qlib.backtest caller - [__init__.py:93] - Create new exchange
[73260:MainThread](2023-02-06 20:06:39,242) WARNING - qlib.online operator - [exchange.py:219] - $close field data contains nan.
[73260:MainThread](2023-02-06 20:06:39,244) WARNING - qlib.online operator - [exchange.py:219] - $close field data contains nan.
[73260:MainThread](2023-02-06 20:06:39,247) WARNING - qlib.online operator - [exchange.py:226] - factor.day.bin file not exists or factor contains `nan`. Order using adjusted_price.
[73260:MainThread](2023-02-06 20:06:39,247) WARNING - qlib.online operator - [exchange.py:228] - trade unit 100 is not supported in adjusted_price mode.
[73260:MainThread](2023-02-06 20:06:44,264) WARNING - qlib.BaseExecutor - [executor.py:121] - `common_infra` is not set for <qlib.backtest.executor.SimulatorExecutor object at 0x141f05160>
backtest loop: 100%|██████████| 871/871 [00:10<00:00, 82.92it/s]
[73260:MainThread](2023-02-06 20:06:55,254) INFO - qlib.workflow - [record_temp.py:505] - Portfolio analysis record 'port_analysis_1day.pkl' has been saved as the artifact of the Experiment 1
[73260:MainThread](2023-02-06 20:06:55,272) INFO - qlib.workflow - [record_temp.py:530] - Indicator analysis record 'indicator_analysis_1day.pkl' has been saved as the artifact of the Experiment 1
This is the bug that I am trying to fix:
import pandas as pd
import qlib
from qlib.data import D
from qlib.data.inst_processor import InstProcessor
qlib.init()
class MyInstProcessor(InstProcessor):
def __init__(self) -> None:
super().__init__()
def __call__(self, df: pd.DataFrame, instrument, *args, **kwargs):
if df.empty:
return df
df['MyNewFeature'] = 1
return df
df = D.features(['SH601216'], ['$close'], start_time='2020-05-01', end_time='2020-05-10',
inst_processors=[MyInstProcessor()])
# Before fix:
# $close
# instrument datetime
# SH601216 2020-05-06 1.318379
# 2020-05-07 1.304631
# 2020-05-08 1.309334
# After fix:
# $close MyNewFeature
# instrument datetime
# SH601216 2020-05-06 1.318379 1
# 2020-05-07 1.304631 1
# 2020-05-08 1.309334 1
print(df)
from qlib.data.dataset.loader import QlibDataLoader
qdl_config = {
'feature': (['$close'], ['Close']),
'label': (['$close / Ref($close, 10)'], ['RET10'])
}
qdl = QlibDataLoader(config=qdl_config, inst_processor={'feature': [MyInstProcessor()]})
df = qdl.load(instruments=['sh600519'], start_time='20190101', end_time='20190105')
# Before fix:
# feature label
# Close RET10
# datetime instrument
# 2019-01-02 sh600519 72.881897 1.014326
# 2019-01-03 sh600519 71.789268 0.998409
# 2019-01-04 sh600519 73.249367 1.041884
# After fix:
# feature label
# Close MyNewFeature RET10
# datetime instrument
# 2019-01-02 sh600519 72.881897 1 1.014326
# 2019-01-03 sh600519 71.789268 1 0.998409
# 2019-01-04 sh600519 73.249367 1 1.041884
print(df)
Could you please handle the CI error message?