Time Series Forecasting
Transformers
PyTorch
Korean
jnu_tsb
feature-extraction
jnu-tsb
time-series
forecasting
chronos-2
polyglot-ko
korean
finance
covariates
r
reticulate
education
custom_code
Instructions to use HONGRIZON/JNU-TSB with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use HONGRIZON/JNU-TSB with Transformers:
# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("HONGRIZON/JNU-TSB", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
Upload 18 files
Browse files- .gitattributes +3 -0
- .gitignore +17 -0
- LICENSE +174 -0
- MANIFEST.json +35 -0
- NOTICE +9 -0
- README.md +283 -0
- __init__.py +4 -0
- app.py +58 -0
- config.json +62 -0
- configuration_jnu_tsb.py +99 -0
- event_extractor.py +191 -0
- handler.py +20 -0
- modeling_jnu_tsb.py +59 -0
- pipeline.py +47 -0
- pytorch_model.bin +3 -0
- requirements.txt +8 -0
- runtime.py +358 -0
- upload_model_repo.py +40 -0
.gitattributes
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
*.pyo
|
| 4 |
+
*.pyd
|
| 5 |
+
.Python
|
| 6 |
+
.env
|
| 7 |
+
.venv/
|
| 8 |
+
venv/
|
| 9 |
+
env/
|
| 10 |
+
.ipynb_checkpoints/
|
| 11 |
+
outputs/
|
| 12 |
+
checkpoints/
|
| 13 |
+
wandb/
|
| 14 |
+
.cache/
|
| 15 |
+
*.zip
|
| 16 |
+
*.tar.gz
|
| 17 |
+
.DS_Store
|
LICENSE
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
patent license to make, have made, use, offer to sell, sell, import,
|
| 77 |
+
and otherwise transfer the Work, where such license applies only to
|
| 78 |
+
those patent claims licensable by such Contributor that are necessarily
|
| 79 |
+
infringed by their Contribution(s) alone or by combination of their
|
| 80 |
+
Contribution(s) with the Work to which such Contribution(s) was
|
| 81 |
+
submitted. If You institute patent litigation against any entity
|
| 82 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 83 |
+
the Work or a Contribution incorporated within the Work constitutes
|
| 84 |
+
direct or contributory patent infringement, then any patent licenses
|
| 85 |
+
granted to You under this License for that Work shall terminate as of
|
| 86 |
+
the date such litigation is filed.
|
| 87 |
+
|
| 88 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 89 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 90 |
+
modifications, and in Source or Object form, provided that You
|
| 91 |
+
meet the following conditions:
|
| 92 |
+
|
| 93 |
+
(a) You must give any other recipients of the Work or
|
| 94 |
+
Derivative Works a copy of this License; and
|
| 95 |
+
|
| 96 |
+
(b) You must cause any modified files to carry prominent notices
|
| 97 |
+
stating that You changed the files; and
|
| 98 |
+
|
| 99 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 100 |
+
that You distribute, all copyright, patent, trademark, and
|
| 101 |
+
attribution notices from the Source form of the Work,
|
| 102 |
+
excluding those notices that do not pertain to any part of
|
| 103 |
+
the Derivative Works; and
|
| 104 |
+
|
| 105 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 106 |
+
distribution, then any Derivative Works that You distribute must
|
| 107 |
+
include a readable copy of the attribution notices contained
|
| 108 |
+
within such NOTICE file, excluding those notices that do not
|
| 109 |
+
pertain to any part of the Derivative Works, in at least one
|
| 110 |
+
of the following places: within a NOTICE text file distributed
|
| 111 |
+
as part of the Derivative Works; within the Source form or
|
| 112 |
+
documentation, if provided along with the Derivative Works; or,
|
| 113 |
+
within a display generated by the Derivative Works, if and
|
| 114 |
+
wherever such third-party notices normally appear. The contents
|
| 115 |
+
of the NOTICE file are for informational purposes only and
|
| 116 |
+
do not modify the License. You may add Your own attribution
|
| 117 |
+
notices within Derivative Works that You distribute, alongside
|
| 118 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 119 |
+
that such additional attribution notices cannot be construed
|
| 120 |
+
as modifying the License.
|
| 121 |
+
|
| 122 |
+
You may add Your own copyright statement to Your modifications and
|
| 123 |
+
may provide additional or different license terms and conditions
|
| 124 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 125 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 126 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 127 |
+
the conditions stated in this License.
|
| 128 |
+
|
| 129 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 130 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 131 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 132 |
+
this License, without any additional terms or conditions.
|
| 133 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 134 |
+
the terms of any separate license agreement you may have executed
|
| 135 |
+
with Licensor regarding such Contributions.
|
| 136 |
+
|
| 137 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 138 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 139 |
+
except as required for reasonable and customary use in describing the
|
| 140 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 141 |
+
|
| 142 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 143 |
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
| 144 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 145 |
+
implied, including, without limitation, any warranties or conditions
|
| 146 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 147 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 148 |
+
appropriateness of using or redistributing the Work and assume any
|
| 149 |
+
risks associated with Your exercise of permissions under this License.
|
| 150 |
+
|
| 151 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 152 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 153 |
+
unless required by applicable law (such as deliberate and grossly
|
| 154 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 155 |
+
liable to You for damages, including any direct, indirect, special,
|
| 156 |
+
incidental, or consequential damages of any character arising as a
|
| 157 |
+
result of this License or out of the use or inability to use the
|
| 158 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 159 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 160 |
+
other commercial damages or losses), even if such Contributor
|
| 161 |
+
has been advised of the possibility of such damages.
|
| 162 |
+
|
| 163 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 164 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 165 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 166 |
+
or other liability obligations and/or rights consistent with this
|
| 167 |
+
License. However, in accepting such obligations, You may act only
|
| 168 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 169 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 170 |
+
defend, and hold each Contributor harmless for any liability
|
| 171 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 172 |
+
of your accepting any such warranty or additional liability.
|
| 173 |
+
|
| 174 |
+
END OF TERMS AND CONDITIONS
|
MANIFEST.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"repo_id": "HONGRIZON/JNU-TSB",
|
| 3 |
+
"root_files": [
|
| 4 |
+
".gitattributes",
|
| 5 |
+
".gitignore",
|
| 6 |
+
"LICENSE",
|
| 7 |
+
"MANIFEST.json",
|
| 8 |
+
"NOTICE",
|
| 9 |
+
"README.md",
|
| 10 |
+
"__init__.py",
|
| 11 |
+
"app.py",
|
| 12 |
+
"config.json",
|
| 13 |
+
"configuration_jnu_tsb.py",
|
| 14 |
+
"data/sample_news.json",
|
| 15 |
+
"data/sample_stock.csv",
|
| 16 |
+
"docs/classroom_guide_ko.md",
|
| 17 |
+
"docs/input_output_schema_ko.md",
|
| 18 |
+
"docs/usage_ko.md",
|
| 19 |
+
"event_extractor.py",
|
| 20 |
+
"examples/python_automodel.py",
|
| 21 |
+
"examples/python_quickstart.py",
|
| 22 |
+
"examples/r_http_client.R",
|
| 23 |
+
"examples/r_quickstart.R",
|
| 24 |
+
"handler.py",
|
| 25 |
+
"modeling_jnu_tsb.py",
|
| 26 |
+
"pipeline.py",
|
| 27 |
+
"pytorch_model.bin",
|
| 28 |
+
"requirements.txt",
|
| 29 |
+
"runtime.py",
|
| 30 |
+
"tests/smoke_test.py",
|
| 31 |
+
"upload_model_repo.py"
|
| 32 |
+
],
|
| 33 |
+
"upload_command": "hf upload HONGRIZON/JNU-TSB . .",
|
| 34 |
+
"note": "이 폴더의 내용물 전체를 Hugging Face repo 루트에 업로드하세요."
|
| 35 |
+
}
|
NOTICE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
JNU-TSB
|
| 2 |
+
|
| 3 |
+
이 저장소는 교육 및 연구용 wrapper 코드를 포함합니다.
|
| 4 |
+
다음 Hugging Face upstream model을 참조하지만, 해당 모델 가중치를 재배포하지 않습니다.
|
| 5 |
+
|
| 6 |
+
- amazon/chronos-2
|
| 7 |
+
- EleutherAI/polyglot-ko-1.3b
|
| 8 |
+
|
| 9 |
+
JNU-TSB는 Amazon, EleutherAI, Hugging Face와 공식적으로 제휴된 프로젝트가 아닙니다.
|
README.md
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
base_model:
|
| 4 |
+
- amazon/chronos-2
|
| 5 |
+
- EleutherAI/polyglot-ko-1.3b
|
| 6 |
+
library_name: transformers
|
| 7 |
+
pipeline_tag: time-series-forecasting
|
| 8 |
+
language:
|
| 9 |
+
- ko
|
| 10 |
+
tags:
|
| 11 |
+
- jnu-tsb
|
| 12 |
+
- time-series
|
| 13 |
+
- forecasting
|
| 14 |
+
- chronos-2
|
| 15 |
+
- polyglot-ko
|
| 16 |
+
- korean
|
| 17 |
+
- finance
|
| 18 |
+
- covariates
|
| 19 |
+
- r
|
| 20 |
+
- reticulate
|
| 21 |
+
- education
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
# JNU-TSB
|
| 25 |
+
|
| 26 |
+
**JNU-TSB**는 한국어 뉴스와 주가 시계열을 함께 다루기 위한 교육용 **Time-LLM-style time-series bridge/router**입니다.
|
| 27 |
+
|
| 28 |
+
```text
|
| 29 |
+
Repo ID: HONGRIZON/JNU-TSB
|
| 30 |
+
Full name: Jeju National University Time-Series Bridge
|
| 31 |
+
Nickname: TSB = Time-Series Bridge, also Time-Series Seungbin
|
| 32 |
+
Time-series model: amazon/chronos-2
|
| 33 |
+
Korean language model: EleutherAI/polyglot-ko-1.3b
|
| 34 |
+
Router: stock only, news only, news + stock hybrid
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
이 저장소는 **Chronos-2 또는 Polyglot-Ko의 가중치를 재배포하지 않습니다.** 여기에는 가벼운 wrapper 코드, 설정 파일, 예제 코드, 수업용 샘플 데이터만 포함되어 있습니다. 두 base model은 실행 시 Hugging Face에서 다운로드됩니다.
|
| 38 |
+
|
| 39 |
+
## 이 저장소는 무엇인가요?
|
| 40 |
+
|
| 41 |
+
JNU-TSB는 **wrapper-style model repo**입니다. 학부생 수업 시연과 작은 연구 프로토타입을 위해 만들었으며, 한국어 금융 뉴스 제목을 일별 공변량으로 바꾸고 이를 Chronos-2에 전달하여 공변량 기반 시계열 예측을 수행합니다.
|
| 42 |
+
|
| 43 |
+
```text
|
| 44 |
+
뉴스 제목
|
| 45 |
+
-> Polyglot-Ko / keyword fallback
|
| 46 |
+
-> 일별 14차원 이벤트 공변량
|
| 47 |
+
-> Chronos-2 covariate-informed forecasting
|
| 48 |
+
|
| 49 |
+
주가 시계열
|
| 50 |
+
-> Chronos-2 forecasting
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
이 구조는 **Time-LLM-style**입니다. 원 논문의 Time-LLM reprogramming architecture를 엄밀히 재구현한 것은 아닙니다. 의도적으로 숫자 시계열 예측은 Chronos-2가 담당하고, 한국어 LLM은 뉴스 텍스트를 구조화된 공변량으로 바꾸는 역할만 맡도록 설계했습니다.
|
| 54 |
+
|
| 55 |
+
## 라우터 구조
|
| 56 |
+
|
| 57 |
+
JNU-TSB는 입력에 따라 세 가지 경로 중 하나를 자동 선택합니다.
|
| 58 |
+
|
| 59 |
+
| 입력 | 경로 | 출력 |
|
| 60 |
+
|---|---|---|
|
| 61 |
+
| `stock`만 있음 | Chronos-2 단독 경로 | 분위수 시계열 예측 |
|
| 62 |
+
| `news`만 있음 | Polyglot-Ko / keyword fallback 경로 | 이벤트 카테고리, 감성, confidence, 일별 공변량 |
|
| 63 |
+
| `stock` + `news` 모두 있음 | 하이브리드 경로 | 뉴스 공변량을 포함한 Chronos-2 예측 |
|
| 64 |
+
|
| 65 |
+
하이브리드 경로는 다음 순서로 동작합니다.
|
| 66 |
+
|
| 67 |
+
```text
|
| 68 |
+
한국어 뉴스
|
| 69 |
+
-> 이벤트/감성 추출
|
| 70 |
+
-> 일별 14차원 covariate 생성
|
| 71 |
+
-> 주가 context dataframe과 merge
|
| 72 |
+
-> Chronos-2 predict_df 호출
|
| 73 |
+
-> forecast 반환
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
## 14차원 뉴스 공변량
|
| 77 |
+
|
| 78 |
+
뉴스는 하루 단위로 집계되어 아래 14개 공변량으로 변환됩니다.
|
| 79 |
+
|
| 80 |
+
| 컬럼 | 의미 |
|
| 81 |
+
|---|---|
|
| 82 |
+
| `cov_earnings_count` | 실적/매출/영업이익 관련 뉴스 수 |
|
| 83 |
+
| `cov_product_count` | 제품 출시, 개발, 양산, 반도체 관련 뉴스 수 |
|
| 84 |
+
| `cov_macro_count` | 금리, 환율, 경기, 해외시장 등 거시경제 뉴스 수 |
|
| 85 |
+
| `cov_regulation_count` | 규제, 소송, 제재, 정부 정책 관련 뉴스 수 |
|
| 86 |
+
| `cov_supply_chain_count` | 공급망, 수주, 계약, 생산, 물류 관련 뉴스 수 |
|
| 87 |
+
| `cov_competition_count` | 경쟁사, 점유율, 가격 경쟁 관련 뉴스 수 |
|
| 88 |
+
| `cov_other_count` | 위 범주에 명확히 속하지 않는 뉴스 수 |
|
| 89 |
+
| `cov_sentiment_pos_count` | 긍정 감성 뉴스 수 |
|
| 90 |
+
| `cov_sentiment_neg_count` | 부정 감성 뉴스 수 |
|
| 91 |
+
| `cov_sentiment_neu_count` | 중립 감성 뉴스 수 |
|
| 92 |
+
| `cov_news_count` | 해당 날짜의 전체 뉴스 수 |
|
| 93 |
+
| `cov_sentiment_mean` | 평균 감성 점수, `-1`, `0`, `1` 기반 |
|
| 94 |
+
| `cov_confidence_mean` | 평균 추출 confidence |
|
| 95 |
+
| `cov_event_score` | 감성 × confidence의 합 |
|
| 96 |
+
|
| 97 |
+
## 설치
|
| 98 |
+
|
| 99 |
+
```bash
|
| 100 |
+
pip install -U transformers torch accelerate pandas pyarrow chronos-forecasting
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
R에서 사용할 경우 `reticulate` 가상환경에 위 Python 패키지를 설치하면 됩니다. 예시는 `examples/r_quickstart.R`에 들어 있습니다.
|
| 104 |
+
|
| 105 |
+
## Python 빠른 시작
|
| 106 |
+
|
| 107 |
+
수업에서 빠르게 테스트할 때는 `use_llm_extractor=False`를 권장합니다. 이 경우 Polyglot-Ko를 로드하지 않고 keyword fallback만 사용하므로 훨씬 가볍게 실행됩니다.
|
| 108 |
+
|
| 109 |
+
```python
|
| 110 |
+
from transformers import pipeline
|
| 111 |
+
|
| 112 |
+
pipe = pipeline(
|
| 113 |
+
task="jnu-tsb",
|
| 114 |
+
model="HONGRIZON/JNU-TSB",
|
| 115 |
+
trust_remote_code=True,
|
| 116 |
+
device=-1, # CPU. GPU 0번을 쓰려면 0으로 변경
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
stock = [
|
| 120 |
+
{"timestamp": "2024-12-01", "target": 71000},
|
| 121 |
+
{"timestamp": "2024-12-02", "target": 71800},
|
| 122 |
+
{"timestamp": "2024-12-03", "target": 70400},
|
| 123 |
+
{"timestamp": "2024-12-04", "target": 70900},
|
| 124 |
+
{"timestamp": "2024-12-05", "target": 72100},
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
news = [
|
| 128 |
+
{"date": "2024-12-01", "title": "삼성전자 HBM 신제품 출시"},
|
| 129 |
+
{"date": "2024-12-02", "title": "반도체 업황 둔화 우려"},
|
| 130 |
+
]
|
| 131 |
+
|
| 132 |
+
result = pipe(
|
| 133 |
+
{"stock": stock, "news": news},
|
| 134 |
+
prediction_length=3,
|
| 135 |
+
use_llm_extractor=False,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
print(result)
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
## AutoModel 직접 사용
|
| 142 |
+
|
| 143 |
+
```python
|
| 144 |
+
from transformers import AutoModel
|
| 145 |
+
|
| 146 |
+
model = AutoModel.from_pretrained(
|
| 147 |
+
"HONGRIZON/JNU-TSB",
|
| 148 |
+
trust_remote_code=True,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
result = model.predict(
|
| 152 |
+
stock=[{"timestamp": "2024-12-01", "target": 71000}],
|
| 153 |
+
news=[{"date": "2024-12-01", "title": "삼성전자 HBM 신제품 출시"}],
|
| 154 |
+
prediction_length=3,
|
| 155 |
+
use_llm_extractor=False,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
print(result)
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
## R 빠른 시작
|
| 162 |
+
|
| 163 |
+
```r
|
| 164 |
+
library(reticulate)
|
| 165 |
+
|
| 166 |
+
# 최초 1회만 실행:
|
| 167 |
+
# reticulate::virtualenv_create("jnu-tsb-env")
|
| 168 |
+
# reticulate::virtualenv_install(
|
| 169 |
+
# "jnu-tsb-env",
|
| 170 |
+
# c("transformers", "torch", "accelerate", "pandas", "pyarrow", "chronos-forecasting")
|
| 171 |
+
# )
|
| 172 |
+
|
| 173 |
+
use_virtualenv("jnu-tsb-env", required = TRUE)
|
| 174 |
+
transformers <- import("transformers")
|
| 175 |
+
|
| 176 |
+
pipe <- transformers$pipeline(
|
| 177 |
+
task = "jnu-tsb",
|
| 178 |
+
model = "HONGRIZON/JNU-TSB",
|
| 179 |
+
trust_remote_code = TRUE,
|
| 180 |
+
device = -1L
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
stock <- list(
|
| 184 |
+
list(timestamp = "2024-12-01", target = 71000),
|
| 185 |
+
list(timestamp = "2024-12-02", target = 71800),
|
| 186 |
+
list(timestamp = "2024-12-03", target = 70400)
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
news <- list(
|
| 190 |
+
list(date = "2024-12-01", title = "삼성전자 HBM 신제품 출시"),
|
| 191 |
+
list(date = "2024-12-02", title = "반도체 업황 둔화 우려")
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
result <- pipe(
|
| 195 |
+
list(stock = stock, news = news),
|
| 196 |
+
prediction_length = 3L,
|
| 197 |
+
use_llm_extractor = FALSE
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
print(py_to_r(result))
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
## 입력 형식
|
| 204 |
+
|
| 205 |
+
### `stock`
|
| 206 |
+
|
| 207 |
+
`stock`은 pandas DataFrame, list of dicts, 또는 dict of columns 형식으로 넣을 수 있습니다. 최소 컬럼은 다음 두 개입니다.
|
| 208 |
+
|
| 209 |
+
```text
|
| 210 |
+
timestamp: 날짜 또는 시간
|
| 211 |
+
target: 예측 대상 값, 예: 종가
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
`item_id`가 없으면 내부적으로 `series_0`이 자동 부여됩니다.
|
| 215 |
+
|
| 216 |
+
### `news`
|
| 217 |
+
|
| 218 |
+
`news`는 list of dicts 형식입니다. 각 항목은 최소한 날짜와 제목을 가져야 합니다.
|
| 219 |
+
|
| 220 |
+
```json
|
| 221 |
+
[
|
| 222 |
+
{"date": "2024-12-01", "title": "삼성전자 HBM 신제품 출시"},
|
| 223 |
+
{"date": "2024-12-02", "title": "반도체 업황 둔화 우려"}
|
| 224 |
+
]
|
| 225 |
+
```
|
| 226 |
+
|
| 227 |
+
`title` 대신 `headline`, `text`, `content`도 인식합니다.
|
| 228 |
+
|
| 229 |
+
### `future_news`와 `future_covariates`
|
| 230 |
+
|
| 231 |
+
미래에 이미 알려진 뉴스나 일정이 있을 때만 `future_news` 또는 `future_covariates`를 사용하세요. 일반 뉴스 데이터는 보통 미래 값을 알 수 없으므로, 과거 뉴스는 context 구간의 past covariate로만 쓰는 것이 안전합니다.
|
| 232 |
+
|
| 233 |
+
## Hugging Face 업로드 방법
|
| 234 |
+
|
| 235 |
+
이 폴더의 **내용물 전체**를 `HONGRIZON/JNU-TSB` repo의 루트에 업로드하면 됩니다.
|
| 236 |
+
|
| 237 |
+
```bash
|
| 238 |
+
pip install -U huggingface_hub
|
| 239 |
+
hf auth login
|
| 240 |
+
hf upload HONGRIZON/JNU-TSB . .
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
또는 포함된 스크립트를 사용할 수 있습니다.
|
| 244 |
+
|
| 245 |
+
```bash
|
| 246 |
+
python upload_model_repo.py --repo_id HONGRIZON/JNU-TSB
|
| 247 |
+
```
|
| 248 |
+
|
| 249 |
+
다음은 업로드하지 마세요.
|
| 250 |
+
|
| 251 |
+
```text
|
| 252 |
+
.venv/
|
| 253 |
+
venv/
|
| 254 |
+
__pycache__/
|
| 255 |
+
outputs/
|
| 256 |
+
checkpoints/
|
| 257 |
+
wandb/
|
| 258 |
+
Hugging Face cache/
|
| 259 |
+
Chronos-2 가중치
|
| 260 |
+
Polyglot-Ko 가중치
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
## 수업용 권장 사용법
|
| 264 |
+
|
| 265 |
+
수업 시연에서는 다음 순서를 추천합니다.
|
| 266 |
+
|
| 267 |
+
1. `news`만 넣어서 이벤트/감성/공변량이 어떻게 만들어지는지 확인합니다.
|
| 268 |
+
2. `stock`만 넣어서 Chronos-2 시계열 예측 경로를 확인합니다.
|
| 269 |
+
3. `stock + news`를 함께 넣어서 하이브리드 라우터가 동작하는지 확인합니다.
|
| 270 |
+
4. `use_llm_extractor=False`와 `True`의 차이를 비교합니다.
|
| 271 |
+
|
| 272 |
+
`use_llm_extractor=True`는 Polyglot-Ko-1.3B를 로드하므로 CPU 환경에서는 느릴 수 있습니다. 학부생 실습에서는 fallback 모드부터 시작하는 편이 좋습니다.
|
| 273 |
+
|
| 274 |
+
## 중요한 주의사항
|
| 275 |
+
|
| 276 |
+
- 이 모델은 교육/연구 데모용입니다. 투자 조언이나 실제 매매 판단에 사용하지 마세요.
|
| 277 |
+
- `EleutherAI/polyglot-ko-1.3b`는 instruction-tuned JSON extractor가 아니라 base language model입니다. 따라서 JSON 추출이 실패할 수 있고, 이 저장소는 keyword fallback을 함께 제공합니다.
|
| 278 |
+
- Chronos-2 또는 Polyglot-Ko 가중치를 이 저장소에 포함하지 않습니다. 실행 시 각 upstream repo에서 다운로드합니다.
|
| 279 |
+
- 이 저장소는 원 논문 Time-LLM을 그대로 재구현한 것이 아니라, 한국어 뉴스와 시계열 예측을 연결하는 Time-LLM-style wrapper/router입니다.
|
| 280 |
+
|
| 281 |
+
## 라이선스
|
| 282 |
+
|
| 283 |
+
Wrapper 코드는 Apache-2.0으로 배포됩니다. Upstream base model인 `amazon/chronos-2`와 `EleutherAI/polyglot-ko-1.3b`는 각 Hugging Face repo의 라이선스와 사용 조건을 따릅니다.
|
__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .configuration_jnu_tsb import JNUTSBConfig
|
| 2 |
+
from .modeling_jnu_tsb import JNUTSBModel
|
| 3 |
+
|
| 4 |
+
__all__ = ["JNUTSBConfig", "JNUTSBModel"]
|
app.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from runtime import JNUTSBRuntime
|
| 11 |
+
|
| 12 |
+
runtime = JNUTSBRuntime.from_config_dir(Path(__file__).parent)
|
| 13 |
+
|
| 14 |
+
DEFAULT_STOCK = """timestamp,target
|
| 15 |
+
2024-12-01,71000
|
| 16 |
+
2024-12-02,71800
|
| 17 |
+
2024-12-03,70400
|
| 18 |
+
2024-12-04,70900
|
| 19 |
+
2024-12-05,72100
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
DEFAULT_NEWS = """[
|
| 23 |
+
{"date": "2024-12-01", "title": "삼성전자 HBM 신제품 출시"},
|
| 24 |
+
{"date": "2024-12-02", "title": "반도체 업황 둔화 우려"}
|
| 25 |
+
]"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def run_demo(stock_csv: str, news_json: str, prediction_length: int, use_llm_extractor: bool) -> Any:
|
| 29 |
+
from io import StringIO
|
| 30 |
+
|
| 31 |
+
stock = pd.read_csv(StringIO(stock_csv)) if stock_csv.strip() else None
|
| 32 |
+
news = json.loads(news_json) if news_json.strip() else None
|
| 33 |
+
result = runtime.predict(
|
| 34 |
+
inputs={"stock": stock, "news": news},
|
| 35 |
+
prediction_length=int(prediction_length),
|
| 36 |
+
use_llm_extractor=bool(use_llm_extractor),
|
| 37 |
+
)
|
| 38 |
+
return result
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
with gr.Blocks(title="JNU-TSB") as demo:
|
| 42 |
+
gr.Markdown("# JNU-TSB: 한국어 뉴스 기반 Time-Series Bridge")
|
| 43 |
+
gr.Markdown(
|
| 44 |
+
"Chronos-2 + Polyglot-Ko + 3-way router 구조의 교육/연구용 데모입니다. "
|
| 45 |
+
"예측 결과는 투자 조언이 아닙니다."
|
| 46 |
+
)
|
| 47 |
+
with gr.Row():
|
| 48 |
+
stock_box = gr.Textbox(label="주가 CSV", value=DEFAULT_STOCK, lines=9)
|
| 49 |
+
news_box = gr.Textbox(label="뉴스 JSON", value=DEFAULT_NEWS, lines=9)
|
| 50 |
+
with gr.Row():
|
| 51 |
+
pred_len = gr.Slider(label="예측 길이 prediction_length", minimum=1, maximum=30, value=3, step=1)
|
| 52 |
+
use_llm = gr.Checkbox(label="Polyglot-Ko 추출기 사용", value=False)
|
| 53 |
+
btn = gr.Button("JNU-TSB 실행")
|
| 54 |
+
out = gr.JSON(label="결과")
|
| 55 |
+
btn.click(run_demo, inputs=[stock_box, news_box, pred_len, use_llm], outputs=out)
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
demo.launch()
|
config.json
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "jnu_tsb",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"JNUTSBModel"
|
| 5 |
+
],
|
| 6 |
+
"repo_id": "HONGRIZON/JNU-TSB",
|
| 7 |
+
"project_name": "JNU-TSB",
|
| 8 |
+
"project_full_name": "Jeju National University Time-Series Bridge",
|
| 9 |
+
"description": "한국어 뉴스 기반 공변량 추출과 Chronos-2 시계열 예측을 연결하는 교육용 Time-LLM-style router.",
|
| 10 |
+
"chronos_model_id": "amazon/chronos-2",
|
| 11 |
+
"llm_model_id": "EleutherAI/polyglot-ko-1.3b",
|
| 12 |
+
"timestamp_column": "timestamp",
|
| 13 |
+
"target_column": "target",
|
| 14 |
+
"id_column": "item_id",
|
| 15 |
+
"default_item_id": "series_0",
|
| 16 |
+
"prediction_length": 5,
|
| 17 |
+
"quantile_levels": [
|
| 18 |
+
0.1,
|
| 19 |
+
0.5,
|
| 20 |
+
0.9
|
| 21 |
+
],
|
| 22 |
+
"event_categories": [
|
| 23 |
+
"earnings",
|
| 24 |
+
"product",
|
| 25 |
+
"macro",
|
| 26 |
+
"regulation",
|
| 27 |
+
"supply_chain",
|
| 28 |
+
"competition",
|
| 29 |
+
"other"
|
| 30 |
+
],
|
| 31 |
+
"covariate_columns": [
|
| 32 |
+
"cov_earnings_count",
|
| 33 |
+
"cov_product_count",
|
| 34 |
+
"cov_macro_count",
|
| 35 |
+
"cov_regulation_count",
|
| 36 |
+
"cov_supply_chain_count",
|
| 37 |
+
"cov_competition_count",
|
| 38 |
+
"cov_other_count",
|
| 39 |
+
"cov_sentiment_pos_count",
|
| 40 |
+
"cov_sentiment_neg_count",
|
| 41 |
+
"cov_sentiment_neu_count",
|
| 42 |
+
"cov_news_count",
|
| 43 |
+
"cov_sentiment_mean",
|
| 44 |
+
"cov_confidence_mean",
|
| 45 |
+
"cov_event_score"
|
| 46 |
+
],
|
| 47 |
+
"use_llm_extractor": true,
|
| 48 |
+
"allow_naive_fallback": true,
|
| 49 |
+
"auto_map": {
|
| 50 |
+
"AutoConfig": "configuration_jnu_tsb.JNUTSBConfig",
|
| 51 |
+
"AutoModel": "modeling_jnu_tsb.JNUTSBModel"
|
| 52 |
+
},
|
| 53 |
+
"custom_pipelines": {
|
| 54 |
+
"jnu-tsb": {
|
| 55 |
+
"impl": "pipeline.JNUTSBPipeline",
|
| 56 |
+
"pt": [
|
| 57 |
+
"AutoModel"
|
| 58 |
+
],
|
| 59 |
+
"type": "multimodal"
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
}
|
configuration_jnu_tsb.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, List, Optional
|
| 4 |
+
|
| 5 |
+
from transformers import PretrainedConfig
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
DEFAULT_EVENT_CATEGORIES = [
|
| 9 |
+
"earnings",
|
| 10 |
+
"product",
|
| 11 |
+
"macro",
|
| 12 |
+
"regulation",
|
| 13 |
+
"supply_chain",
|
| 14 |
+
"competition",
|
| 15 |
+
"other",
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
DEFAULT_COVARIATE_COLUMNS = [
|
| 19 |
+
"cov_earnings_count",
|
| 20 |
+
"cov_product_count",
|
| 21 |
+
"cov_macro_count",
|
| 22 |
+
"cov_regulation_count",
|
| 23 |
+
"cov_supply_chain_count",
|
| 24 |
+
"cov_competition_count",
|
| 25 |
+
"cov_other_count",
|
| 26 |
+
"cov_sentiment_pos_count",
|
| 27 |
+
"cov_sentiment_neg_count",
|
| 28 |
+
"cov_sentiment_neu_count",
|
| 29 |
+
"cov_news_count",
|
| 30 |
+
"cov_sentiment_mean",
|
| 31 |
+
"cov_confidence_mean",
|
| 32 |
+
"cov_event_score",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class JNUTSBConfig(PretrainedConfig):
|
| 37 |
+
"""Configuration for the JNU-TSB router wrapper.
|
| 38 |
+
|
| 39 |
+
The repository stores lightweight code and metadata only. The upstream
|
| 40 |
+
models, amazon/chronos-2 and EleutherAI/polyglot-ko-1.3b, are loaded lazily
|
| 41 |
+
at runtime when the corresponding route is used.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
model_type = "jnu_tsb"
|
| 45 |
+
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
repo_id: str = "HONGRIZON/JNU-TSB",
|
| 49 |
+
project_name: str = "JNU-TSB",
|
| 50 |
+
project_full_name: str = "Jeju National University Time-Series Bridge",
|
| 51 |
+
chronos_model_id: str = "amazon/chronos-2",
|
| 52 |
+
llm_model_id: str = "EleutherAI/polyglot-ko-1.3b",
|
| 53 |
+
timestamp_column: str = "timestamp",
|
| 54 |
+
target_column: str = "target",
|
| 55 |
+
id_column: str = "item_id",
|
| 56 |
+
default_item_id: str = "series_0",
|
| 57 |
+
prediction_length: int = 5,
|
| 58 |
+
quantile_levels: Optional[List[float]] = None,
|
| 59 |
+
event_categories: Optional[List[str]] = None,
|
| 60 |
+
covariate_columns: Optional[List[str]] = None,
|
| 61 |
+
use_llm_extractor: bool = True,
|
| 62 |
+
allow_naive_fallback: bool = True,
|
| 63 |
+
**kwargs: Any,
|
| 64 |
+
) -> None:
|
| 65 |
+
super().__init__(**kwargs)
|
| 66 |
+
self.repo_id = repo_id
|
| 67 |
+
self.project_name = project_name
|
| 68 |
+
self.project_full_name = project_full_name
|
| 69 |
+
self.chronos_model_id = chronos_model_id
|
| 70 |
+
self.llm_model_id = llm_model_id
|
| 71 |
+
self.timestamp_column = timestamp_column
|
| 72 |
+
self.target_column = target_column
|
| 73 |
+
self.id_column = id_column
|
| 74 |
+
self.default_item_id = default_item_id
|
| 75 |
+
self.prediction_length = int(prediction_length)
|
| 76 |
+
self.quantile_levels = quantile_levels or [0.1, 0.5, 0.9]
|
| 77 |
+
self.event_categories = event_categories or list(DEFAULT_EVENT_CATEGORIES)
|
| 78 |
+
self.covariate_columns = covariate_columns or list(DEFAULT_COVARIATE_COLUMNS)
|
| 79 |
+
self.use_llm_extractor = bool(use_llm_extractor)
|
| 80 |
+
self.allow_naive_fallback = bool(allow_naive_fallback)
|
| 81 |
+
|
| 82 |
+
def to_router_dict(self) -> Dict[str, Any]:
|
| 83 |
+
return {
|
| 84 |
+
"repo_id": self.repo_id,
|
| 85 |
+
"project_name": self.project_name,
|
| 86 |
+
"project_full_name": self.project_full_name,
|
| 87 |
+
"chronos_model_id": self.chronos_model_id,
|
| 88 |
+
"llm_model_id": self.llm_model_id,
|
| 89 |
+
"timestamp_column": self.timestamp_column,
|
| 90 |
+
"target_column": self.target_column,
|
| 91 |
+
"id_column": self.id_column,
|
| 92 |
+
"default_item_id": self.default_item_id,
|
| 93 |
+
"prediction_length": self.prediction_length,
|
| 94 |
+
"quantile_levels": self.quantile_levels,
|
| 95 |
+
"event_categories": self.event_categories,
|
| 96 |
+
"covariate_columns": self.covariate_columns,
|
| 97 |
+
"use_llm_extractor": self.use_llm_extractor,
|
| 98 |
+
"allow_naive_fallback": self.allow_naive_fallback,
|
| 99 |
+
}
|
event_extractor.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
from collections import Counter
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Any, Callable, Dict, Iterable, List, Optional
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
DEFAULT_CATEGORIES = [
|
| 13 |
+
"earnings",
|
| 14 |
+
"product",
|
| 15 |
+
"macro",
|
| 16 |
+
"regulation",
|
| 17 |
+
"supply_chain",
|
| 18 |
+
"competition",
|
| 19 |
+
"other",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
COVARIATE_COLUMNS = [
|
| 23 |
+
"cov_earnings_count",
|
| 24 |
+
"cov_product_count",
|
| 25 |
+
"cov_macro_count",
|
| 26 |
+
"cov_regulation_count",
|
| 27 |
+
"cov_supply_chain_count",
|
| 28 |
+
"cov_competition_count",
|
| 29 |
+
"cov_other_count",
|
| 30 |
+
"cov_sentiment_pos_count",
|
| 31 |
+
"cov_sentiment_neg_count",
|
| 32 |
+
"cov_sentiment_neu_count",
|
| 33 |
+
"cov_news_count",
|
| 34 |
+
"cov_sentiment_mean",
|
| 35 |
+
"cov_confidence_mean",
|
| 36 |
+
"cov_event_score",
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
CATEGORY_KEYWORDS = {
|
| 40 |
+
"earnings": ["실적", "영업이익", "매출", "순이익", "가이던스", "어닝", "분기", "흑자", "적자"],
|
| 41 |
+
"product": ["신제품", "출시", "HBM", "AI칩", "반도체", "스마트폰", "제품", "개발", "양산"],
|
| 42 |
+
"macro": ["금리", "환율", "물가", "경기", "코스피", "나스닥", "연준", "미국", "중국", "수출"],
|
| 43 |
+
"regulation": ["규제", "정부", "공정위", "조사", "제재", "법안", "허가", "소송", "벌금"],
|
| 44 |
+
"supply_chain": ["공급", "수주", "계약", "공장", "생산", "물류", "공급망", "원재료", "납품"],
|
| 45 |
+
"competition": ["경쟁", "점유율", "가격인하", "경쟁사", "SK하이닉스", "엔비디아", "TSMC"],
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
POSITIVE_KEYWORDS = [
|
| 49 |
+
"상승", "호재", "개선", "증가", "수주", "계약", "출시", "성장", "최대", "돌파",
|
| 50 |
+
"흑자", "강세", "투자", "확대", "회복", "승인", "개발", "양산",
|
| 51 |
+
]
|
| 52 |
+
NEGATIVE_KEYWORDS = [
|
| 53 |
+
"하락", "악재", "둔화", "감소", "우려", "적자", "부진", "규제", "제재", "소송",
|
| 54 |
+
"중단", "감산", "약세", "리콜", "손실", "취소", "침체",
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class EventResult:
|
| 60 |
+
category: str
|
| 61 |
+
sentiment: int
|
| 62 |
+
confidence: float
|
| 63 |
+
source: str
|
| 64 |
+
raw_text: str = ""
|
| 65 |
+
|
| 66 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 67 |
+
return {
|
| 68 |
+
"category": self.category,
|
| 69 |
+
"sentiment": int(self.sentiment),
|
| 70 |
+
"confidence": float(self.confidence),
|
| 71 |
+
"source": self.source,
|
| 72 |
+
"raw_text": self.raw_text,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class EventExtractor:
|
| 77 |
+
"""Korean financial news -> event/sentiment -> daily covariates.
|
| 78 |
+
|
| 79 |
+
The LLM path asks Polyglot-Ko to emit JSON. Since Polyglot-Ko-1.3B is a base
|
| 80 |
+
LM rather than an instruction-tuned JSON extractor, deterministic keyword
|
| 81 |
+
fallback is always available.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(
|
| 85 |
+
self,
|
| 86 |
+
generate_fn: Optional[Callable[[str], str]] = None,
|
| 87 |
+
categories: Optional[List[str]] = None,
|
| 88 |
+
use_llm: bool = True,
|
| 89 |
+
) -> None:
|
| 90 |
+
self.generate_fn = generate_fn
|
| 91 |
+
self.categories = categories or list(DEFAULT_CATEGORIES)
|
| 92 |
+
self.use_llm = bool(use_llm)
|
| 93 |
+
|
| 94 |
+
def build_prompt(self, title: str) -> str:
|
| 95 |
+
cats = ", ".join(self.categories)
|
| 96 |
+
return (
|
| 97 |
+
"다음 한국어 금융뉴스 제목을 주가 예측용 공변량으로 분석하세요.\n"
|
| 98 |
+
f"가능한 category: {cats}\n"
|
| 99 |
+
"sentiment는 주가 관점에서 -1, 0, 1 중 하나입니다.\n"
|
| 100 |
+
"confidence는 0과 1 사이 숫자입니다.\n"
|
| 101 |
+
"반드시 JSON만 출력하세요.\n"
|
| 102 |
+
f"뉴스: {title}\n"
|
| 103 |
+
"JSON:"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
def extract(self, title: str) -> Dict[str, Any]:
|
| 107 |
+
title = str(title or "").strip()
|
| 108 |
+
if self.use_llm and self.generate_fn is not None and title:
|
| 109 |
+
try:
|
| 110 |
+
raw = self.generate_fn(self.build_prompt(title))
|
| 111 |
+
parsed = self._parse_json(raw)
|
| 112 |
+
if parsed is not None:
|
| 113 |
+
return parsed.to_dict()
|
| 114 |
+
except Exception:
|
| 115 |
+
pass
|
| 116 |
+
return self._keyword_fallback(title).to_dict()
|
| 117 |
+
|
| 118 |
+
def aggregate_to_daily(self, news: Iterable[Dict[str, Any]]) -> pd.DataFrame:
|
| 119 |
+
rows: List[Dict[str, Any]] = []
|
| 120 |
+
for item in news or []:
|
| 121 |
+
date_value = item.get("date") or item.get("timestamp") or item.get("datetime")
|
| 122 |
+
title = item.get("title") or item.get("headline") or item.get("text") or item.get("content") or ""
|
| 123 |
+
if date_value is None:
|
| 124 |
+
continue
|
| 125 |
+
day = pd.to_datetime(date_value).floor("D")
|
| 126 |
+
event = self.extract(str(title))
|
| 127 |
+
event["timestamp"] = day
|
| 128 |
+
rows.append(event)
|
| 129 |
+
|
| 130 |
+
if not rows:
|
| 131 |
+
return pd.DataFrame(columns=["timestamp", *COVARIATE_COLUMNS])
|
| 132 |
+
|
| 133 |
+
df = pd.DataFrame(rows)
|
| 134 |
+
daily_rows: List[Dict[str, Any]] = []
|
| 135 |
+
for day, group in df.groupby("timestamp"):
|
| 136 |
+
counter = Counter(group["category"].tolist())
|
| 137 |
+
sentiments = group["sentiment"].astype(float)
|
| 138 |
+
confidences = group["confidence"].astype(float).clip(0, 1)
|
| 139 |
+
out: Dict[str, Any] = {"timestamp": pd.to_datetime(day)}
|
| 140 |
+
|
| 141 |
+
for cat in DEFAULT_CATEGORIES:
|
| 142 |
+
out[f"cov_{cat}_count"] = float(counter.get(cat, 0))
|
| 143 |
+
|
| 144 |
+
out["cov_sentiment_pos_count"] = float((sentiments > 0).sum())
|
| 145 |
+
out["cov_sentiment_neg_count"] = float((sentiments < 0).sum())
|
| 146 |
+
out["cov_sentiment_neu_count"] = float((sentiments == 0).sum())
|
| 147 |
+
out["cov_news_count"] = float(len(group))
|
| 148 |
+
out["cov_sentiment_mean"] = float(sentiments.mean()) if len(group) else 0.0
|
| 149 |
+
out["cov_confidence_mean"] = float(confidences.mean()) if len(group) else 0.0
|
| 150 |
+
out["cov_event_score"] = float((sentiments * confidences).sum()) if len(group) else 0.0
|
| 151 |
+
daily_rows.append(out)
|
| 152 |
+
|
| 153 |
+
result = pd.DataFrame(daily_rows).sort_values("timestamp").reset_index(drop=True)
|
| 154 |
+
for col in COVARIATE_COLUMNS:
|
| 155 |
+
if col not in result.columns:
|
| 156 |
+
result[col] = 0.0
|
| 157 |
+
return result[["timestamp", *COVARIATE_COLUMNS]]
|
| 158 |
+
|
| 159 |
+
def _parse_json(self, raw: str) -> Optional[EventResult]:
|
| 160 |
+
if not raw:
|
| 161 |
+
return None
|
| 162 |
+
# Extract the first {...} block.
|
| 163 |
+
match = re.search(r"\{.*?\}", str(raw), flags=re.DOTALL)
|
| 164 |
+
if not match:
|
| 165 |
+
return None
|
| 166 |
+
payload = json.loads(match.group(0))
|
| 167 |
+
category = str(payload.get("category", "other")).strip()
|
| 168 |
+
if category not in self.categories:
|
| 169 |
+
category = "other"
|
| 170 |
+
sentiment = int(payload.get("sentiment", 0))
|
| 171 |
+
sentiment = -1 if sentiment < 0 else (1 if sentiment > 0 else 0)
|
| 172 |
+
confidence = float(payload.get("confidence", 0.5))
|
| 173 |
+
confidence = max(0.0, min(1.0, confidence))
|
| 174 |
+
return EventResult(category=category, sentiment=sentiment, confidence=confidence, source="llm", raw_text=str(raw))
|
| 175 |
+
|
| 176 |
+
def _keyword_fallback(self, title: str) -> EventResult:
|
| 177 |
+
text = title.lower()
|
| 178 |
+
scores: Dict[str, int] = {}
|
| 179 |
+
for category, keywords in CATEGORY_KEYWORDS.items():
|
| 180 |
+
scores[category] = sum(1 for kw in keywords if kw.lower() in text)
|
| 181 |
+
|
| 182 |
+
category = max(scores, key=scores.get) if scores else "other"
|
| 183 |
+
if scores.get(category, 0) == 0:
|
| 184 |
+
category = "other"
|
| 185 |
+
|
| 186 |
+
pos = sum(1 for kw in POSITIVE_KEYWORDS if kw.lower() in text)
|
| 187 |
+
neg = sum(1 for kw in NEGATIVE_KEYWORDS if kw.lower() in text)
|
| 188 |
+
sentiment = 1 if pos > neg else (-1 if neg > pos else 0)
|
| 189 |
+
confidence = 0.55 + 0.1 * min(3, abs(pos - neg) + scores.get(category, 0))
|
| 190 |
+
confidence = max(0.1, min(0.95, confidence))
|
| 191 |
+
return EventResult(category=category, sentiment=sentiment, confidence=confidence, source="keyword", raw_text=title)
|
handler.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict
|
| 4 |
+
|
| 5 |
+
try:
|
| 6 |
+
from .runtime import JNUTSBRuntime
|
| 7 |
+
except ImportError: # pragma: no cover
|
| 8 |
+
from runtime import JNUTSBRuntime
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class EndpointHandler:
|
| 12 |
+
"""Hugging Face Inference Endpoint custom handler."""
|
| 13 |
+
|
| 14 |
+
def __init__(self, model_dir: str, **kwargs: Any) -> None:
|
| 15 |
+
self.runtime = JNUTSBRuntime.from_config_dir(model_dir)
|
| 16 |
+
|
| 17 |
+
def __call__(self, data: Dict[str, Any]) -> Any:
|
| 18 |
+
inputs = data.get("inputs", data)
|
| 19 |
+
parameters = data.get("parameters", {})
|
| 20 |
+
return self.runtime.predict(inputs=inputs, **parameters)
|
modeling_jnu_tsb.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, Optional
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from transformers import PreTrainedModel
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from .configuration_jnu_tsb import JNUTSBConfig
|
| 11 |
+
except ImportError: # pragma: no cover - local execution fallback
|
| 12 |
+
from configuration_jnu_tsb import JNUTSBConfig
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class JNUTSBModel(PreTrainedModel):
|
| 16 |
+
"""Tiny Hugging Face model wrapper for JNU-TSB.
|
| 17 |
+
|
| 18 |
+
The actual computation lives in ``runtime.JNUTSBRuntime``. This class exists
|
| 19 |
+
so that ``AutoModel.from_pretrained(..., trust_remote_code=True)`` and the
|
| 20 |
+
custom Transformers pipeline can load the repo like a normal HF model.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
config_class = JNUTSBConfig
|
| 24 |
+
base_model_prefix = "jnu_tsb"
|
| 25 |
+
main_input_name = "inputs"
|
| 26 |
+
|
| 27 |
+
def __init__(self, config: JNUTSBConfig) -> None:
|
| 28 |
+
super().__init__(config)
|
| 29 |
+
self.dummy = nn.Parameter(torch.zeros(1), requires_grad=False)
|
| 30 |
+
self._runtime = None
|
| 31 |
+
|
| 32 |
+
def forward(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
|
| 33 |
+
return {
|
| 34 |
+
"message": "JNU-TSB is a router wrapper. Use model.predict(...) or pipeline(task='jnu-tsb', ...).",
|
| 35 |
+
"repo_id": self.config.repo_id,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
def get_runtime(self):
|
| 39 |
+
if self._runtime is None:
|
| 40 |
+
try:
|
| 41 |
+
from .runtime import JNUTSBRuntime
|
| 42 |
+
except ImportError: # pragma: no cover
|
| 43 |
+
from runtime import JNUTSBRuntime
|
| 44 |
+
self._runtime = JNUTSBRuntime.from_config(self.config)
|
| 45 |
+
return self._runtime
|
| 46 |
+
|
| 47 |
+
def predict(self, inputs: Optional[Dict[str, Any]] = None, **kwargs: Any) -> Any:
|
| 48 |
+
"""Run the 3-way router.
|
| 49 |
+
|
| 50 |
+
Supports either:
|
| 51 |
+
model.predict({"stock": ..., "news": ...}, prediction_length=5)
|
| 52 |
+
or:
|
| 53 |
+
model.predict(stock=..., news=..., prediction_length=5)
|
| 54 |
+
"""
|
| 55 |
+
payload = dict(inputs or {})
|
| 56 |
+
for key in ("stock", "news", "future_news", "future_covariates"):
|
| 57 |
+
if key in kwargs:
|
| 58 |
+
payload[key] = kwargs.pop(key)
|
| 59 |
+
return self.get_runtime().predict(inputs=payload, **kwargs)
|
pipeline.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any, Dict, Optional, Tuple
|
| 4 |
+
|
| 5 |
+
from transformers import Pipeline
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class JNUTSBPipeline(Pipeline):
|
| 9 |
+
"""Custom Transformers pipeline for JNU-TSB.
|
| 10 |
+
|
| 11 |
+
Example:
|
| 12 |
+
from transformers import pipeline
|
| 13 |
+
pipe = pipeline("jnu-tsb", model="HONGRIZON/JNU-TSB", trust_remote_code=True)
|
| 14 |
+
pipe({"stock": [...], "news": [...]}, prediction_length=5)
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def _sanitize_parameters(
|
| 18 |
+
self,
|
| 19 |
+
prediction_length: Optional[int] = None,
|
| 20 |
+
quantile_levels: Optional[list] = None,
|
| 21 |
+
use_llm_extractor: Optional[bool] = None,
|
| 22 |
+
allow_naive_fallback: Optional[bool] = None,
|
| 23 |
+
**kwargs: Any,
|
| 24 |
+
) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
|
| 25 |
+
forward_params: Dict[str, Any] = dict(kwargs)
|
| 26 |
+
if prediction_length is not None:
|
| 27 |
+
forward_params["prediction_length"] = int(prediction_length)
|
| 28 |
+
if quantile_levels is not None:
|
| 29 |
+
forward_params["quantile_levels"] = quantile_levels
|
| 30 |
+
if use_llm_extractor is not None:
|
| 31 |
+
forward_params["use_llm_extractor"] = bool(use_llm_extractor)
|
| 32 |
+
if allow_naive_fallback is not None:
|
| 33 |
+
forward_params["allow_naive_fallback"] = bool(allow_naive_fallback)
|
| 34 |
+
return {}, forward_params, {}
|
| 35 |
+
|
| 36 |
+
def preprocess(self, inputs: Any, **preprocess_params: Any) -> Any:
|
| 37 |
+
if inputs is None:
|
| 38 |
+
raise ValueError("JNU-TSB expects a dict with 'stock', 'news', or both.")
|
| 39 |
+
return inputs
|
| 40 |
+
|
| 41 |
+
def _forward(self, model_inputs: Any, **forward_params: Any) -> Any:
|
| 42 |
+
if not hasattr(self.model, "predict"):
|
| 43 |
+
raise TypeError("The loaded model does not expose a predict(...) method.")
|
| 44 |
+
return self.model.predict(model_inputs, **forward_params)
|
| 45 |
+
|
| 46 |
+
def postprocess(self, model_outputs: Any, **postprocess_params: Any) -> Any:
|
| 47 |
+
return model_outputs
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ee70794f4c8b7feed2ca6cfa91f3226ccfd5f22e19eb5d5f223beff4f4e479a1
|
| 3 |
+
size 1619
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers>=4.45
|
| 2 |
+
accelerate>=0.33
|
| 3 |
+
torch>=2.2
|
| 4 |
+
pandas>=2.0
|
| 5 |
+
pyarrow>=14.0
|
| 6 |
+
chronos-forecasting>=2.0
|
| 7 |
+
huggingface_hub>=0.25
|
| 8 |
+
gradio>=4.44
|
runtime.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Union
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from .configuration_jnu_tsb import JNUTSBConfig
|
| 13 |
+
from .event_extractor import COVARIATE_COLUMNS, EventExtractor
|
| 14 |
+
except ImportError: # pragma: no cover - local execution fallback
|
| 15 |
+
from configuration_jnu_tsb import JNUTSBConfig
|
| 16 |
+
from event_extractor import COVARIATE_COLUMNS, EventExtractor
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class JNUTSBRuntime:
|
| 20 |
+
"""Runtime used by the model wrapper, pipeline, Endpoint handler, Gradio, and R examples.
|
| 21 |
+
|
| 22 |
+
Routes inputs into three paths:
|
| 23 |
+
1. stock only -> Chronos-2 forecast
|
| 24 |
+
2. news only -> event extraction and daily covariates
|
| 25 |
+
3. stock + news -> news covariates + stock context -> Chronos-2 forecast
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
config: Union[JNUTSBConfig, Dict[str, Any]],
|
| 31 |
+
chronos_device_map: Optional[str] = None,
|
| 32 |
+
llm_device_map: Optional[str] = None,
|
| 33 |
+
) -> None:
|
| 34 |
+
if isinstance(config, dict):
|
| 35 |
+
config = JNUTSBConfig(**config)
|
| 36 |
+
self.config = config
|
| 37 |
+
self.chronos_device_map = chronos_device_map or os.getenv("JNU_TSB_CHRONOS_DEVICE_MAP", "cpu")
|
| 38 |
+
self.llm_device_map = llm_device_map or os.getenv("JNU_TSB_LLM_DEVICE_MAP", "cpu")
|
| 39 |
+
self._chronos = None
|
| 40 |
+
self._llm_pipe = None
|
| 41 |
+
self._extractor = None
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def from_config(cls, config: Union[JNUTSBConfig, Dict[str, Any]], **kwargs: Any) -> "JNUTSBRuntime":
|
| 45 |
+
return cls(config=config, **kwargs)
|
| 46 |
+
|
| 47 |
+
@classmethod
|
| 48 |
+
def from_config_dir(cls, path: Union[str, os.PathLike[str]], **kwargs: Any) -> "JNUTSBRuntime":
|
| 49 |
+
path = Path(path)
|
| 50 |
+
with open(path / "config.json", "r", encoding="utf-8") as f:
|
| 51 |
+
payload = json.load(f)
|
| 52 |
+
return cls(config=payload, **kwargs)
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def chronos(self):
|
| 56 |
+
if self._chronos is None:
|
| 57 |
+
try:
|
| 58 |
+
from chronos import Chronos2Pipeline
|
| 59 |
+
except Exception as exc: # pragma: no cover
|
| 60 |
+
raise ImportError(
|
| 61 |
+
"chronos-forecasting is required for Chronos-2 inference. "
|
| 62 |
+
"Install it with: pip install chronos-forecasting"
|
| 63 |
+
) from exc
|
| 64 |
+
self._chronos = Chronos2Pipeline.from_pretrained(
|
| 65 |
+
self.config.chronos_model_id,
|
| 66 |
+
device_map=self.chronos_device_map,
|
| 67 |
+
)
|
| 68 |
+
return self._chronos
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def extractor(self) -> EventExtractor:
|
| 72 |
+
if self._extractor is None:
|
| 73 |
+
self._extractor = EventExtractor(
|
| 74 |
+
generate_fn=self._generate_with_polyglot if self.config.use_llm_extractor else None,
|
| 75 |
+
categories=self.config.event_categories,
|
| 76 |
+
use_llm=self.config.use_llm_extractor,
|
| 77 |
+
)
|
| 78 |
+
return self._extractor
|
| 79 |
+
|
| 80 |
+
def _generate_with_polyglot(self, prompt: str) -> str:
|
| 81 |
+
if self._llm_pipe is None:
|
| 82 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline as hf_pipeline
|
| 83 |
+
|
| 84 |
+
tokenizer = AutoTokenizer.from_pretrained(self.config.llm_model_id)
|
| 85 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 86 |
+
self.config.llm_model_id,
|
| 87 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 88 |
+
device_map=self.llm_device_map,
|
| 89 |
+
)
|
| 90 |
+
self._llm_pipe = hf_pipeline(
|
| 91 |
+
"text-generation",
|
| 92 |
+
model=model,
|
| 93 |
+
tokenizer=tokenizer,
|
| 94 |
+
)
|
| 95 |
+
output = self._llm_pipe(
|
| 96 |
+
prompt,
|
| 97 |
+
max_new_tokens=96,
|
| 98 |
+
do_sample=False,
|
| 99 |
+
return_full_text=False,
|
| 100 |
+
)
|
| 101 |
+
if isinstance(output, list) and output:
|
| 102 |
+
return output[0].get("generated_text", "")
|
| 103 |
+
return str(output)
|
| 104 |
+
|
| 105 |
+
def predict(
|
| 106 |
+
self,
|
| 107 |
+
inputs: Optional[Dict[str, Any]] = None,
|
| 108 |
+
prediction_length: Optional[int] = None,
|
| 109 |
+
quantile_levels: Optional[Sequence[float]] = None,
|
| 110 |
+
use_llm_extractor: Optional[bool] = None,
|
| 111 |
+
allow_naive_fallback: Optional[bool] = None,
|
| 112 |
+
**kwargs: Any,
|
| 113 |
+
) -> Dict[str, Any]:
|
| 114 |
+
payload: Dict[str, Any] = dict(inputs or {})
|
| 115 |
+
payload.update(kwargs)
|
| 116 |
+
|
| 117 |
+
if use_llm_extractor is not None and bool(use_llm_extractor) != self.config.use_llm_extractor:
|
| 118 |
+
# Rebuild extractor with the requested setting for this runtime instance.
|
| 119 |
+
self.config.use_llm_extractor = bool(use_llm_extractor)
|
| 120 |
+
self._extractor = None
|
| 121 |
+
|
| 122 |
+
prediction_length = int(prediction_length or self.config.prediction_length)
|
| 123 |
+
quantile_levels = list(quantile_levels or self.config.quantile_levels)
|
| 124 |
+
allow_naive_fallback = self.config.allow_naive_fallback if allow_naive_fallback is None else bool(allow_naive_fallback)
|
| 125 |
+
|
| 126 |
+
news = payload.get("news")
|
| 127 |
+
stock = payload.get("stock")
|
| 128 |
+
future_news = payload.get("future_news")
|
| 129 |
+
future_covariates = payload.get("future_covariates")
|
| 130 |
+
|
| 131 |
+
has_news = bool(news)
|
| 132 |
+
stock_df = self._prepare_stock_df(stock)
|
| 133 |
+
has_stock = stock_df is not None and not stock_df.empty
|
| 134 |
+
|
| 135 |
+
if has_news and has_stock:
|
| 136 |
+
context_df = self._merge_news_covariates(stock_df, news)
|
| 137 |
+
future_df = self._prepare_future_covariates(
|
| 138 |
+
stock_df=context_df,
|
| 139 |
+
future_news=future_news,
|
| 140 |
+
future_covariates=future_covariates,
|
| 141 |
+
prediction_length=prediction_length,
|
| 142 |
+
)
|
| 143 |
+
return self._forecast(
|
| 144 |
+
context_df=context_df,
|
| 145 |
+
prediction_length=prediction_length,
|
| 146 |
+
quantile_levels=quantile_levels,
|
| 147 |
+
route="hybrid",
|
| 148 |
+
future_df=future_df,
|
| 149 |
+
allow_naive_fallback=allow_naive_fallback,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
if has_stock:
|
| 153 |
+
return self._forecast(
|
| 154 |
+
context_df=stock_df,
|
| 155 |
+
prediction_length=prediction_length,
|
| 156 |
+
quantile_levels=quantile_levels,
|
| 157 |
+
route="chronos_only",
|
| 158 |
+
future_df=None,
|
| 159 |
+
allow_naive_fallback=allow_naive_fallback,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
if has_news:
|
| 163 |
+
events = [self.extractor.extract(item.get("title") or item.get("headline") or item.get("text") or "") for item in news]
|
| 164 |
+
daily_covariates = self.extractor.aggregate_to_daily(news)
|
| 165 |
+
return {
|
| 166 |
+
"route": "text_only",
|
| 167 |
+
"repo_id": self.config.repo_id,
|
| 168 |
+
"events": events,
|
| 169 |
+
"daily_covariates": self._df_to_records(daily_covariates),
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
raise ValueError("JNU-TSB expects at least one of: stock, news.")
|
| 173 |
+
|
| 174 |
+
def _forecast(
|
| 175 |
+
self,
|
| 176 |
+
context_df: pd.DataFrame,
|
| 177 |
+
prediction_length: int,
|
| 178 |
+
quantile_levels: Sequence[float],
|
| 179 |
+
route: str,
|
| 180 |
+
future_df: Optional[pd.DataFrame] = None,
|
| 181 |
+
allow_naive_fallback: bool = True,
|
| 182 |
+
) -> Dict[str, Any]:
|
| 183 |
+
try:
|
| 184 |
+
kwargs = dict(
|
| 185 |
+
prediction_length=prediction_length,
|
| 186 |
+
quantile_levels=list(quantile_levels),
|
| 187 |
+
id_column=self.config.id_column,
|
| 188 |
+
timestamp_column=self.config.timestamp_column,
|
| 189 |
+
target=self.config.target_column,
|
| 190 |
+
)
|
| 191 |
+
if future_df is not None and not future_df.empty:
|
| 192 |
+
pred = self.chronos.predict_df(context_df, future_df=future_df, **kwargs)
|
| 193 |
+
else:
|
| 194 |
+
pred = self.chronos.predict_df(context_df, **kwargs)
|
| 195 |
+
return {
|
| 196 |
+
"route": route,
|
| 197 |
+
"repo_id": self.config.repo_id,
|
| 198 |
+
"engine": self.config.chronos_model_id,
|
| 199 |
+
"forecast": self._df_to_records(pred),
|
| 200 |
+
"used_naive_fallback": False,
|
| 201 |
+
}
|
| 202 |
+
except Exception as exc:
|
| 203 |
+
if not allow_naive_fallback:
|
| 204 |
+
raise
|
| 205 |
+
pred = self._naive_forecast(context_df, prediction_length, quantile_levels)
|
| 206 |
+
return {
|
| 207 |
+
"route": route,
|
| 208 |
+
"repo_id": self.config.repo_id,
|
| 209 |
+
"engine": "naive_last_value_fallback",
|
| 210 |
+
"forecast": self._df_to_records(pred),
|
| 211 |
+
"used_naive_fallback": True,
|
| 212 |
+
"warning": f"Chronos-2 inference failed or was unavailable: {type(exc).__name__}: {exc}",
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
def _prepare_stock_df(self, stock: Any) -> Optional[pd.DataFrame]:
|
| 216 |
+
if stock is None:
|
| 217 |
+
return None
|
| 218 |
+
if isinstance(stock, pd.DataFrame):
|
| 219 |
+
df = stock.copy()
|
| 220 |
+
elif isinstance(stock, list):
|
| 221 |
+
df = pd.DataFrame(stock)
|
| 222 |
+
elif isinstance(stock, dict):
|
| 223 |
+
df = pd.DataFrame(stock)
|
| 224 |
+
else:
|
| 225 |
+
raise TypeError("stock must be a pandas DataFrame, list of dicts, or dict of columns.")
|
| 226 |
+
|
| 227 |
+
if df.empty:
|
| 228 |
+
return df
|
| 229 |
+
|
| 230 |
+
timestamp_col = self.config.timestamp_column
|
| 231 |
+
if timestamp_col not in df.columns:
|
| 232 |
+
for cand in ("date", "Date", "datetime", "time"):
|
| 233 |
+
if cand in df.columns:
|
| 234 |
+
df = df.rename(columns={cand: timestamp_col})
|
| 235 |
+
break
|
| 236 |
+
|
| 237 |
+
target_col = self.config.target_column
|
| 238 |
+
if target_col not in df.columns:
|
| 239 |
+
for cand in ("close", "Close", "price", "value", "y"):
|
| 240 |
+
if cand in df.columns:
|
| 241 |
+
df = df.rename(columns={cand: target_col})
|
| 242 |
+
break
|
| 243 |
+
|
| 244 |
+
if timestamp_col not in df.columns or target_col not in df.columns:
|
| 245 |
+
raise ValueError(f"stock must contain '{timestamp_col}' and '{target_col}' columns.")
|
| 246 |
+
|
| 247 |
+
if self.config.id_column not in df.columns:
|
| 248 |
+
df[self.config.id_column] = self.config.default_item_id
|
| 249 |
+
|
| 250 |
+
df[timestamp_col] = pd.to_datetime(df[timestamp_col])
|
| 251 |
+
df = df.sort_values([self.config.id_column, timestamp_col]).reset_index(drop=True)
|
| 252 |
+
return df
|
| 253 |
+
|
| 254 |
+
def _prepare_future_df(self, data: Any) -> Optional[pd.DataFrame]:
|
| 255 |
+
if data is None:
|
| 256 |
+
return None
|
| 257 |
+
if isinstance(data, pd.DataFrame):
|
| 258 |
+
df = data.copy()
|
| 259 |
+
elif isinstance(data, list):
|
| 260 |
+
df = pd.DataFrame(data)
|
| 261 |
+
elif isinstance(data, dict):
|
| 262 |
+
df = pd.DataFrame(data)
|
| 263 |
+
else:
|
| 264 |
+
raise TypeError("future_covariates must be a pandas DataFrame, list of dicts, or dict of columns.")
|
| 265 |
+
|
| 266 |
+
if df.empty:
|
| 267 |
+
return df
|
| 268 |
+
|
| 269 |
+
timestamp_col = self.config.timestamp_column
|
| 270 |
+
if timestamp_col not in df.columns:
|
| 271 |
+
for cand in ("date", "Date", "datetime", "time"):
|
| 272 |
+
if cand in df.columns:
|
| 273 |
+
df = df.rename(columns={cand: timestamp_col})
|
| 274 |
+
break
|
| 275 |
+
if timestamp_col not in df.columns:
|
| 276 |
+
raise ValueError(f"future_covariates must contain a '{timestamp_col}' column.")
|
| 277 |
+
if self.config.id_column not in df.columns:
|
| 278 |
+
df[self.config.id_column] = self.config.default_item_id
|
| 279 |
+
|
| 280 |
+
df[timestamp_col] = pd.to_datetime(df[timestamp_col])
|
| 281 |
+
df = df.sort_values([self.config.id_column, timestamp_col]).reset_index(drop=True)
|
| 282 |
+
return df
|
| 283 |
+
|
| 284 |
+
def _merge_news_covariates(self, stock_df: pd.DataFrame, news: Iterable[Dict[str, Any]]) -> pd.DataFrame:
|
| 285 |
+
cov = self.extractor.aggregate_to_daily(news)
|
| 286 |
+
context = stock_df.copy()
|
| 287 |
+
day_col = "__day__"
|
| 288 |
+
context[day_col] = pd.to_datetime(context[self.config.timestamp_column]).dt.floor("D")
|
| 289 |
+
cov = cov.rename(columns={"timestamp": day_col})
|
| 290 |
+
merged = context.merge(cov, on=day_col, how="left").drop(columns=[day_col])
|
| 291 |
+
for col in COVARIATE_COLUMNS:
|
| 292 |
+
if col in merged.columns:
|
| 293 |
+
merged[col] = merged[col].fillna(0).astype(float)
|
| 294 |
+
return merged
|
| 295 |
+
|
| 296 |
+
def _prepare_future_covariates(
|
| 297 |
+
self,
|
| 298 |
+
stock_df: pd.DataFrame,
|
| 299 |
+
future_news: Optional[Iterable[Dict[str, Any]]],
|
| 300 |
+
future_covariates: Any,
|
| 301 |
+
prediction_length: int,
|
| 302 |
+
) -> Optional[pd.DataFrame]:
|
| 303 |
+
if future_covariates is not None:
|
| 304 |
+
fut = self._prepare_future_df(future_covariates)
|
| 305 |
+
if fut is not None and not fut.empty:
|
| 306 |
+
return fut.drop(columns=[self.config.target_column], errors="ignore")
|
| 307 |
+
|
| 308 |
+
if not future_news:
|
| 309 |
+
return None
|
| 310 |
+
|
| 311 |
+
first_id = stock_df[self.config.id_column].iloc[0]
|
| 312 |
+
last_ts = pd.to_datetime(stock_df[self.config.timestamp_column]).max()
|
| 313 |
+
freq = pd.infer_freq(pd.to_datetime(stock_df[self.config.timestamp_column]).drop_duplicates().sort_values()) or "D"
|
| 314 |
+
future_dates = pd.date_range(start=last_ts, periods=prediction_length + 1, freq=freq)[1:]
|
| 315 |
+
base = pd.DataFrame({
|
| 316 |
+
self.config.timestamp_column: future_dates,
|
| 317 |
+
self.config.id_column: first_id,
|
| 318 |
+
})
|
| 319 |
+
|
| 320 |
+
cov = self.extractor.aggregate_to_daily(future_news)
|
| 321 |
+
if cov.empty:
|
| 322 |
+
return base
|
| 323 |
+
cov_day = cov.rename(columns={"timestamp": "__day__"})
|
| 324 |
+
base["__day__"] = pd.to_datetime(base[self.config.timestamp_column]).dt.floor("D")
|
| 325 |
+
merged = base.merge(cov_day, on="__day__", how="left").drop(columns=["__day__"])
|
| 326 |
+
for col in COVARIATE_COLUMNS:
|
| 327 |
+
if col in merged.columns:
|
| 328 |
+
merged[col] = merged[col].fillna(0).astype(float)
|
| 329 |
+
return merged
|
| 330 |
+
|
| 331 |
+
def _naive_forecast(self, context_df: pd.DataFrame, prediction_length: int, quantile_levels: Sequence[float]) -> pd.DataFrame:
|
| 332 |
+
timestamp_col = self.config.timestamp_column
|
| 333 |
+
target_col = self.config.target_column
|
| 334 |
+
id_col = self.config.id_column
|
| 335 |
+
|
| 336 |
+
rows: List[Dict[str, Any]] = []
|
| 337 |
+
for item_id, group in context_df.groupby(id_col):
|
| 338 |
+
group = group.sort_values(timestamp_col)
|
| 339 |
+
last_ts = pd.to_datetime(group[timestamp_col].iloc[-1])
|
| 340 |
+
last_value = float(group[target_col].iloc[-1])
|
| 341 |
+
freq = pd.infer_freq(pd.to_datetime(group[timestamp_col]).drop_duplicates().sort_values()) or "D"
|
| 342 |
+
dates = pd.date_range(start=last_ts, periods=prediction_length + 1, freq=freq)[1:]
|
| 343 |
+
for ts in dates:
|
| 344 |
+
row: Dict[str, Any] = {id_col: item_id, timestamp_col: ts}
|
| 345 |
+
for q in quantile_levels:
|
| 346 |
+
row[str(q)] = last_value
|
| 347 |
+
row[f"q{q}"] = last_value
|
| 348 |
+
row["mean"] = last_value
|
| 349 |
+
row["prediction"] = last_value
|
| 350 |
+
rows.append(row)
|
| 351 |
+
return pd.DataFrame(rows)
|
| 352 |
+
|
| 353 |
+
def _df_to_records(self, df: pd.DataFrame) -> List[Dict[str, Any]]:
|
| 354 |
+
out = df.copy()
|
| 355 |
+
for col in out.columns:
|
| 356 |
+
if pd.api.types.is_datetime64_any_dtype(out[col]):
|
| 357 |
+
out[col] = out[col].astype(str)
|
| 358 |
+
return out.to_dict(orient="records")
|
upload_model_repo.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from huggingface_hub import HfApi, create_repo
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def main() -> None:
|
| 10 |
+
parser = argparse.ArgumentParser(description="Upload JNU-TSB files to Hugging Face Hub")
|
| 11 |
+
parser.add_argument("--repo_id", default="HONGRIZON/JNU-TSB", help="Hugging Face repo id")
|
| 12 |
+
parser.add_argument("--private", action="store_true", help="Create/upload as a private repo")
|
| 13 |
+
parser.add_argument("--folder", default=".", help="Folder to upload")
|
| 14 |
+
args = parser.parse_args()
|
| 15 |
+
|
| 16 |
+
folder = Path(args.folder).resolve()
|
| 17 |
+
create_repo(args.repo_id, repo_type="model", private=args.private, exist_ok=True)
|
| 18 |
+
api = HfApi()
|
| 19 |
+
api.upload_folder(
|
| 20 |
+
folder_path=str(folder),
|
| 21 |
+
repo_id=args.repo_id,
|
| 22 |
+
repo_type="model",
|
| 23 |
+
ignore_patterns=[
|
| 24 |
+
".git/*",
|
| 25 |
+
"__pycache__/*",
|
| 26 |
+
"*.pyc",
|
| 27 |
+
"*.zip",
|
| 28 |
+
".venv/*",
|
| 29 |
+
"venv/*",
|
| 30 |
+
"env/*",
|
| 31 |
+
"outputs/*",
|
| 32 |
+
"checkpoints/*",
|
| 33 |
+
"wandb/*",
|
| 34 |
+
],
|
| 35 |
+
)
|
| 36 |
+
print(f"Uploaded {folder} to https://huggingface.co/{args.repo_id}")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if __name__ == "__main__":
|
| 40 |
+
main()
|