stock-manager-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stock_manager_cli-0.1.0.dist-info/METADATA +80 -0
- stock_manager_cli-0.1.0.dist-info/RECORD +17 -0
- stock_manager_cli-0.1.0.dist-info/WHEEL +4 -0
- stock_manager_cli-0.1.0.dist-info/entry_points.txt +2 -0
- stock_manager_cli-0.1.0.dist-info/licenses/LICENSE +201 -0
- tradingtools_stock/__init__.py +5 -0
- tradingtools_stock/__main__.py +6 -0
- tradingtools_stock/commands/dashboard.py +27 -0
- tradingtools_stock/commands/db.py +58 -0
- tradingtools_stock/commands/example.py +21 -0
- tradingtools_stock/commands/fetch.py +182 -0
- tradingtools_stock/commands/tickers.py +218 -0
- tradingtools_stock/core/config.py +5 -0
- tradingtools_stock/core/fetcher.py +487 -0
- tradingtools_stock/core/strategies.py +435 -0
- tradingtools_stock/dashboard/app.py +197 -0
- tradingtools_stock/main.py +42 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: stock-manager-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A world-class Python CLI template powered by Typer and rich.
|
|
5
|
+
Author-email: Your Name <your.email@example.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: pandas>=2.0.0
|
|
10
|
+
Requires-Dist: psycopg2-binary>=2.9.0
|
|
11
|
+
Requires-Dist: pydantic>=2.0.0
|
|
12
|
+
Requires-Dist: requests>=2.28.0
|
|
13
|
+
Requires-Dist: rich>=13.0.0
|
|
14
|
+
Requires-Dist: streamlit>=1.20.0
|
|
15
|
+
Requires-Dist: typer>=0.9.0
|
|
16
|
+
Requires-Dist: yahooquery>=2.3.0
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: mypy>=1.0.0; extra == 'dev'
|
|
19
|
+
Requires-Dist: pre-commit>=3.0.0; extra == 'dev'
|
|
20
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
21
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
22
|
+
Requires-Dist: ruff>=0.1.0; extra == 'dev'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# World-Class Python CLI Template
|
|
26
|
+
|
|
27
|
+
This repository is a state-of-the-art starting point for building Python Command Line Interfaces (CLIs). It's optimized for both human developers and the Antigravity AI pair-programming agent.
|
|
28
|
+
|
|
29
|
+
## Core Technologies
|
|
30
|
+
- **Framework:** [Typer](https://typer.tiangolo.com/) with [Rich](https://rich.readthedocs.io/)
|
|
31
|
+
- **Packaging:** Standard `pyproject.toml` (PEP 621) using `hatchling`
|
|
32
|
+
- **Linting & Formatting:** [Ruff](https://beta.ruff.rs/docs/)
|
|
33
|
+
- **Type Checking:** [Mypy](https://mypy.readthedocs.io/en/stable/)
|
|
34
|
+
- **Testing:** [Pytest](https://docs.pytest.org/en/7.4.x/)
|
|
35
|
+
- **Git Hooks:** [pre-commit](https://pre-commit.com/)
|
|
36
|
+
|
|
37
|
+
## Antigravity (AI) Integration
|
|
38
|
+
This repository is configured out-of-the-box with `.gemini/rules.md`. These rules instruct Antigravity automatically on architectural patterns (like enforcing standard `Typer` usage over other frameworks and maintaining `ruff` standards).
|
|
39
|
+
See `.gemini/mcp_instructions.md` for tips on how to push the AI even further using MCP tools like `sequential-thinking`.
|
|
40
|
+
|
|
41
|
+
## How to Work on this project
|
|
42
|
+
|
|
43
|
+
1. **Install tools and dependencies:**
|
|
44
|
+
We highly recommend using `uv` or creating a virtual environment first.
|
|
45
|
+
```bash
|
|
46
|
+
# Using standard pip in a venv
|
|
47
|
+
pip install -e ".[dev]"
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
2. **Setup Git hooks:**
|
|
51
|
+
```bash
|
|
52
|
+
make setup
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
3. **Useful Commands:**
|
|
56
|
+
- `make format`: Auto-fix linting issues and auto-format code using Ruff.
|
|
57
|
+
- `make lint`: Run strict Ruff and Mypy checks.
|
|
58
|
+
- `make test`: Run pytest suite.
|
|
59
|
+
- `make check`: Run format, lint, and tests all at once.
|
|
60
|
+
|
|
61
|
+
## Database Configuration
|
|
62
|
+
|
|
63
|
+
Before running commands that require a database connection (like the dashboard), you need to set up your environment variables.
|
|
64
|
+
|
|
65
|
+
In PowerShell, you can set them for your current session like this:
|
|
66
|
+
|
|
67
|
+
```powershell
|
|
68
|
+
$env:DB_NAME="fractanomicsdb"
|
|
69
|
+
$env:DB_USER="postgres"
|
|
70
|
+
$env:DB_PASS="postgres"
|
|
71
|
+
$env:DB_HOST="localhost"
|
|
72
|
+
$env:DB_PORT="5433"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Try the CLI locally
|
|
76
|
+
Once installed, you can invoke the CLI from anywhere in your terminal!
|
|
77
|
+
```bash
|
|
78
|
+
tradingtools-stock --help
|
|
79
|
+
tradingtools-stock example hello World
|
|
80
|
+
```
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
tradingtools_stock/__init__.py,sha256=IdLP-aAu_LMT-EMQ2uKTqNe6qAuwuBW5D9tjwWEilbA,59
|
|
2
|
+
tradingtools_stock/__main__.py,sha256=wWqC3rFQ_NnkVWR3Dj18rXTug9ilFnFLxEOXATaknrk,100
|
|
3
|
+
tradingtools_stock/main.py,sha256=nvbcDBE4jZAwtgDhOEG9KjMAwzm6olqRNE6PyuHIwrQ,1001
|
|
4
|
+
tradingtools_stock/commands/dashboard.py,sha256=421mI6OYbb2kFq73bwGKqLZCTb7azsCzbsZImfiCYAc,789
|
|
5
|
+
tradingtools_stock/commands/db.py,sha256=CfT4RDrH4bdM7hHKZb0-Y_F9o67V_F1gfKH9WA20a2M,2142
|
|
6
|
+
tradingtools_stock/commands/example.py,sha256=LQXeEKXzTk2KtnIPNVC12fUDZJeXqt-0K3fxxiTH1og,529
|
|
7
|
+
tradingtools_stock/commands/fetch.py,sha256=cSgbSPr53qwhRh0nHQd7HT8wEhcxoK8HLZo6iZZr7cM,6288
|
|
8
|
+
tradingtools_stock/commands/tickers.py,sha256=ExZrSj57V2_iuJw6PkpXjDkSwqHjfpoMsPOVjtZOfak,8001
|
|
9
|
+
tradingtools_stock/core/config.py,sha256=IQFpiUcddnb6Fq6TS_HVQpbjxL-tZtFpTVxtxkq17Yc,81
|
|
10
|
+
tradingtools_stock/core/fetcher.py,sha256=1ADR_o0OAt21eK8R24oFaJfrIpNQwJHJAhdUigrqZwg,18120
|
|
11
|
+
tradingtools_stock/core/strategies.py,sha256=5PPXsLMRZg_yiKrpPgZEXME_X3EoFCVSj9BXZ90kPwk,17444
|
|
12
|
+
tradingtools_stock/dashboard/app.py,sha256=iiifZMtb60EZSU4dgLQw-Jr5cG94Tt4bFG4RhtMxJSA,9358
|
|
13
|
+
stock_manager_cli-0.1.0.dist-info/METADATA,sha256=PBRf89qhHswbNcAZKHKqj321qHBsfm7eyZkc0PHCDZs,2870
|
|
14
|
+
stock_manager_cli-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
15
|
+
stock_manager_cli-0.1.0.dist-info/entry_points.txt,sha256=cVW7YqOxVr66BkUvt2yvQt-DKvWzpEv0i0UCNii_8vo,66
|
|
16
|
+
stock_manager_cli-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
17
|
+
stock_manager_cli-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
import typer
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
app = typer.Typer(help="Analytics and web dashboards.")
|
|
6
|
+
|
|
7
|
+
@app.command("start")
|
|
8
|
+
def start():
|
|
9
|
+
"""
|
|
10
|
+
Launch the Streamlit web dashboard.
|
|
11
|
+
"""
|
|
12
|
+
import tradingtools_stock
|
|
13
|
+
# Find the path to app.py
|
|
14
|
+
pkg_dir = Path(tradingtools_stock.__file__).parent
|
|
15
|
+
app_path = pkg_dir / "dashboard" / "app.py"
|
|
16
|
+
|
|
17
|
+
if not app_path.exists():
|
|
18
|
+
typer.secho(f"Dashboard app not found at {app_path}", fg=typer.colors.RED)
|
|
19
|
+
raise typer.Exit(1)
|
|
20
|
+
|
|
21
|
+
typer.secho("Starting Streamlit Dashboard...", fg=typer.colors.GREEN)
|
|
22
|
+
|
|
23
|
+
# Run streamlit
|
|
24
|
+
try:
|
|
25
|
+
subprocess.run(["streamlit", "run", str(app_path)])
|
|
26
|
+
except KeyboardInterrupt:
|
|
27
|
+
typer.secho("\nDashboard stopped.", fg=typer.colors.YELLOW)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import typer
|
|
3
|
+
import psycopg2
|
|
4
|
+
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
|
|
5
|
+
from rich.console import Console
|
|
6
|
+
|
|
7
|
+
from tradingtools_stock.core.fetcher import create_tables_if_not_exist, get_db_connection
|
|
8
|
+
|
|
9
|
+
app = typer.Typer(help="Database management commands.")
|
|
10
|
+
console = Console()
|
|
11
|
+
|
|
12
|
+
@app.command("setup")
|
|
13
|
+
def setup(
|
|
14
|
+
db_name: str = typer.Option("youtube_db", help="Name of the database to create"),
|
|
15
|
+
user: str = typer.Option("postgres", help="Database user"),
|
|
16
|
+
password: str = typer.Option("postgres", help="Database password"),
|
|
17
|
+
host: str = typer.Option("localhost", help="Database host"),
|
|
18
|
+
port: str = typer.Option("5432", help="Database port"),
|
|
19
|
+
):
|
|
20
|
+
"""
|
|
21
|
+
Setup the database and initialize tables.
|
|
22
|
+
"""
|
|
23
|
+
console.print(f"Setting up database [bold cyan]{db_name}[/]...")
|
|
24
|
+
try:
|
|
25
|
+
# Connect to the default 'postgres' database to create the new one
|
|
26
|
+
conn = psycopg2.connect(
|
|
27
|
+
dbname="postgres",
|
|
28
|
+
user=user,
|
|
29
|
+
password=password,
|
|
30
|
+
host=host,
|
|
31
|
+
port=port
|
|
32
|
+
)
|
|
33
|
+
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
|
|
34
|
+
with conn.cursor() as cur:
|
|
35
|
+
cur.execute(f"SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{db_name}'")
|
|
36
|
+
exists = cur.fetchone()
|
|
37
|
+
if not exists:
|
|
38
|
+
cur.execute(f"CREATE DATABASE {db_name}")
|
|
39
|
+
console.print(f"[green]Database {db_name} created successfully.[/]")
|
|
40
|
+
else:
|
|
41
|
+
console.print(f"[yellow]Database {db_name} already exists.[/]")
|
|
42
|
+
conn.close()
|
|
43
|
+
|
|
44
|
+
# Connect to the new database to create tables
|
|
45
|
+
os.environ["DB_NAME"] = db_name
|
|
46
|
+
os.environ["DB_USER"] = user
|
|
47
|
+
os.environ["DB_PASS"] = password
|
|
48
|
+
os.environ["DB_HOST"] = host
|
|
49
|
+
os.environ["DB_PORT"] = port
|
|
50
|
+
|
|
51
|
+
new_conn = get_db_connection()
|
|
52
|
+
create_tables_if_not_exist(new_conn)
|
|
53
|
+
new_conn.close()
|
|
54
|
+
|
|
55
|
+
console.print("[bold green]Database setup complete![/]")
|
|
56
|
+
except Exception as e:
|
|
57
|
+
console.print(f"[bold red]Error setting up database: {e}[/]")
|
|
58
|
+
raise typer.Exit(1)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import typer
|
|
2
|
+
from rich.console import Console
|
|
3
|
+
|
|
4
|
+
app = typer.Typer(help="Example commands to demonstrate structure.")
|
|
5
|
+
console = Console()
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@app.command()
|
|
9
|
+
def hello(name: str = typer.Argument(..., help="Name of the person to greet.")) -> None:
|
|
10
|
+
"""
|
|
11
|
+
Greet a user with their name.
|
|
12
|
+
"""
|
|
13
|
+
console.print(f"Hello, [bold green]{name}[/]!")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@app.command()
|
|
17
|
+
def info() -> None:
|
|
18
|
+
"""
|
|
19
|
+
Print information about this environment.
|
|
20
|
+
"""
|
|
21
|
+
console.print("This is a world-class CLI template environment. [green]Ready![/]")
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from datetime import datetime, timedelta
|
|
3
|
+
|
|
4
|
+
import typer
|
|
5
|
+
from rich.console import Console
|
|
6
|
+
from rich.progress import Progress, SpinnerColumn, TextColumn
|
|
7
|
+
|
|
8
|
+
from tradingtools_stock.core.fetcher import (
|
|
9
|
+
create_tables_if_not_exist,
|
|
10
|
+
fetch_stock_data,
|
|
11
|
+
get_active_tickers_with_markets,
|
|
12
|
+
format_yahoo_ticker,
|
|
13
|
+
get_db_connection,
|
|
14
|
+
get_existing_data_range,
|
|
15
|
+
psycopg2,
|
|
16
|
+
upsert_stock_data,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
app = typer.Typer(help="Fetch and save stock data.")
|
|
20
|
+
console = Console()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@app.command()
|
|
24
|
+
def update(
|
|
25
|
+
start_date: str | None = typer.Option(
|
|
26
|
+
None,
|
|
27
|
+
"--start-date",
|
|
28
|
+
"-s",
|
|
29
|
+
help="Start date in YYYY-MM-DD format (default: 30 days ago).",
|
|
30
|
+
),
|
|
31
|
+
end_date: str | None = typer.Option(
|
|
32
|
+
None,
|
|
33
|
+
"--end-date",
|
|
34
|
+
"-e",
|
|
35
|
+
help="End date in YYYY-MM-DD format (default: today).",
|
|
36
|
+
),
|
|
37
|
+
include_fundamentals: bool = typer.Option(
|
|
38
|
+
False,
|
|
39
|
+
"--include-fundamentals/--no-fundamentals",
|
|
40
|
+
help="Include quarterly fundamentals.",
|
|
41
|
+
),
|
|
42
|
+
tickers: list[str] | None = typer.Option(
|
|
43
|
+
None,
|
|
44
|
+
"--tickers",
|
|
45
|
+
"-t",
|
|
46
|
+
help="Specific tickers to update (e.g. -t AAPL -t GOOGL). "
|
|
47
|
+
"If omitted, active DB tickers are used.",
|
|
48
|
+
),
|
|
49
|
+
debug: bool = typer.Option(
|
|
50
|
+
False,
|
|
51
|
+
"--debug",
|
|
52
|
+
help="Enable debug logging.",
|
|
53
|
+
),
|
|
54
|
+
):
|
|
55
|
+
"""
|
|
56
|
+
Update stock data in the database over a given date range.
|
|
57
|
+
"""
|
|
58
|
+
log_level = logging.DEBUG if debug else logging.INFO
|
|
59
|
+
logging.basicConfig(
|
|
60
|
+
level=log_level, format="%(asctime)s - %(levelname)s - %(message)s"
|
|
61
|
+
)
|
|
62
|
+
# Suppress verbose logging from external libraries
|
|
63
|
+
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
|
64
|
+
logging.getLogger("requests").setLevel(logging.WARNING)
|
|
65
|
+
|
|
66
|
+
default_start = (datetime.today() - timedelta(days=30)).strftime("%Y-%m-%d")
|
|
67
|
+
start_dt = start_date or default_start
|
|
68
|
+
end_dt = end_date or datetime.today().strftime("%Y-%m-%d")
|
|
69
|
+
|
|
70
|
+
console.print(f"[bold cyan]Date range:[/] {start_dt} to {end_dt}")
|
|
71
|
+
console.print(f"[bold cyan]Include fundamentals:[/] {include_fundamentals}")
|
|
72
|
+
|
|
73
|
+
conn = None
|
|
74
|
+
try:
|
|
75
|
+
conn = get_db_connection()
|
|
76
|
+
console.print("[green]Connected to database.[/]")
|
|
77
|
+
|
|
78
|
+
create_tables_if_not_exist(conn)
|
|
79
|
+
|
|
80
|
+
tickers_with_markets = get_active_tickers_with_markets(conn, tickers)
|
|
81
|
+
if not tickers_with_markets:
|
|
82
|
+
console.print(
|
|
83
|
+
"[red]No active tickers found in the database. "
|
|
84
|
+
"Provide via --tickers.[/]"
|
|
85
|
+
)
|
|
86
|
+
raise typer.Exit(1)
|
|
87
|
+
|
|
88
|
+
console.print(
|
|
89
|
+
f"Processing {len(tickers_with_markets)} tickers."
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
total_records = 0
|
|
93
|
+
successful_tickers: list[str] = []
|
|
94
|
+
failed_tickers: list[str] = []
|
|
95
|
+
|
|
96
|
+
with Progress(
|
|
97
|
+
SpinnerColumn(),
|
|
98
|
+
TextColumn("[progress.description]{task.description}"),
|
|
99
|
+
console=console,
|
|
100
|
+
) as progress:
|
|
101
|
+
task = progress.add_task(
|
|
102
|
+
"[cyan]Fetching stock data...", total=len(tickers_with_markets)
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
for ticker_info in tickers_with_markets:
|
|
106
|
+
ticker = ticker_info["symbol"]
|
|
107
|
+
market = ticker_info["market"]
|
|
108
|
+
yahoo_ticker = format_yahoo_ticker(ticker, market)
|
|
109
|
+
|
|
110
|
+
progress.update(task, description=f"[cyan]Processing {ticker}...")
|
|
111
|
+
|
|
112
|
+
db_min, db_max = get_existing_data_range(conn, ticker)
|
|
113
|
+
req_start = datetime.strptime(start_dt, "%Y-%m-%d").date()
|
|
114
|
+
req_end = datetime.strptime(end_dt, "%Y-%m-%d").date()
|
|
115
|
+
|
|
116
|
+
fetch_ranges = []
|
|
117
|
+
if db_min is None or db_max is None:
|
|
118
|
+
fetch_ranges.append((req_start, req_end))
|
|
119
|
+
else:
|
|
120
|
+
if req_start < db_min:
|
|
121
|
+
gap_before = min(req_end, db_min - timedelta(days=1))
|
|
122
|
+
fetch_ranges.append((req_start, gap_before))
|
|
123
|
+
|
|
124
|
+
if req_end > db_max:
|
|
125
|
+
gap_after = max(req_start, db_max + timedelta(days=1))
|
|
126
|
+
fetch_ranges.append((gap_after, req_end))
|
|
127
|
+
|
|
128
|
+
if not fetch_ranges:
|
|
129
|
+
progress.console.print(f"[dim]{ticker} is already up to date.[/]")
|
|
130
|
+
successful_tickers.append(ticker)
|
|
131
|
+
progress.advance(task)
|
|
132
|
+
continue
|
|
133
|
+
|
|
134
|
+
ticker_data_accumulated = []
|
|
135
|
+
|
|
136
|
+
for f_start, f_end in fetch_ranges:
|
|
137
|
+
data = fetch_stock_data(
|
|
138
|
+
ticker,
|
|
139
|
+
f_start.strftime("%Y-%m-%d"),
|
|
140
|
+
f_end.strftime("%Y-%m-%d"),
|
|
141
|
+
include_fundamentals,
|
|
142
|
+
yahoo_ticker,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
if not data.empty:
|
|
146
|
+
ticker_data_accumulated.append(data)
|
|
147
|
+
|
|
148
|
+
if ticker_data_accumulated:
|
|
149
|
+
import pandas as pd
|
|
150
|
+
|
|
151
|
+
combined_data = pd.concat(ticker_data_accumulated)
|
|
152
|
+
records = upsert_stock_data(
|
|
153
|
+
conn, combined_data, include_fundamentals
|
|
154
|
+
)
|
|
155
|
+
total_records += records
|
|
156
|
+
successful_tickers.append(ticker)
|
|
157
|
+
progress.console.print(
|
|
158
|
+
f"[green]✓ Saved {records} new records for {ticker}[/]"
|
|
159
|
+
)
|
|
160
|
+
else:
|
|
161
|
+
successful_tickers.append(ticker)
|
|
162
|
+
progress.console.print(
|
|
163
|
+
f"[yellow]⚠ No new data returned for {ticker}[/]"
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
progress.advance(task)
|
|
167
|
+
|
|
168
|
+
console.print("\n[bold]Summary[/bold]")
|
|
169
|
+
console.print(f"Total Records Inserted: {total_records}")
|
|
170
|
+
console.print(f"Successful Tickers: {len(successful_tickers)}")
|
|
171
|
+
if failed_tickers:
|
|
172
|
+
console.print(f"Failed Tickers: {len(failed_tickers)}")
|
|
173
|
+
|
|
174
|
+
except psycopg2.Error as e:
|
|
175
|
+
console.print(f"[red]Database error: {e}[/]")
|
|
176
|
+
raise typer.Exit(1) from e
|
|
177
|
+
except Exception as e:
|
|
178
|
+
console.print(f"[red]Unexpected error: {e}[/]")
|
|
179
|
+
raise typer.Exit(1) from e
|
|
180
|
+
finally:
|
|
181
|
+
if conn:
|
|
182
|
+
conn.close()
|