twse-audit 0.1.0__tar.gz
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.
- twse_audit-0.1.0/.gitattributes +2 -0
- twse_audit-0.1.0/CHANGELOG.md +26 -0
- twse_audit-0.1.0/CONTRIBUTING.md +57 -0
- twse_audit-0.1.0/LICENSE +21 -0
- twse_audit-0.1.0/MANIFEST.in +3 -0
- twse_audit-0.1.0/PKG-INFO +170 -0
- twse_audit-0.1.0/README.md +142 -0
- twse_audit-0.1.0/README.zh-TW.md +137 -0
- twse_audit-0.1.0/examples/calendar.csv +4 -0
- twse_audit-0.1.0/examples/daily.csv +4 -0
- twse_audit-0.1.0/examples/expected-report.json +52 -0
- twse_audit-0.1.0/pyproject.toml +40 -0
- twse_audit-0.1.0/setup.cfg +4 -0
- twse_audit-0.1.0/src/twse_audit/__init__.py +3 -0
- twse_audit-0.1.0/src/twse_audit/__main__.py +7 -0
- twse_audit-0.1.0/src/twse_audit/cli.py +53 -0
- twse_audit-0.1.0/src/twse_audit/core.py +130 -0
- twse_audit-0.1.0/src/twse_audit.egg-info/PKG-INFO +170 -0
- twse_audit-0.1.0/src/twse_audit.egg-info/SOURCES.txt +22 -0
- twse_audit-0.1.0/src/twse_audit.egg-info/dependency_links.txt +1 -0
- twse_audit-0.1.0/src/twse_audit.egg-info/entry_points.txt +2 -0
- twse_audit-0.1.0/src/twse_audit.egg-info/top_level.txt +1 -0
- twse_audit-0.1.0/tests/check_golden.py +37 -0
- twse_audit-0.1.0/tests/test_audit.py +193 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
The format is based on Keep a Changelog, and this project follows Semantic Versioning.
|
|
5
|
+
|
|
6
|
+
## [0.1.0] - 2026-12-05
|
|
7
|
+
|
|
8
|
+
### Added
|
|
9
|
+
|
|
10
|
+
- Installable, dependency-free Python 3.10+ package with a src layout.
|
|
11
|
+
- `twse-audit` console command and `python -m twse_audit` entry point.
|
|
12
|
+
- Standard-library regression tests and CI for Ubuntu/Windows on Python 3.10–3.13.
|
|
13
|
+
- English and Traditional Chinese documentation, contribution guide, MIT license
|
|
14
|
+
and issue templates.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Split the original v0.1 single-file tool into a read-only audit core and CLI.
|
|
19
|
+
- Made UTF-8/LF report serialization explicit on Windows as well as Unix so that
|
|
20
|
+
file and stdout bytes match the existing golden report.
|
|
21
|
+
|
|
22
|
+
### Preserved
|
|
23
|
+
|
|
24
|
+
- Audit rules, JSON schema, field order, Chinese details and backfill reasons.
|
|
25
|
+
- CLI option names, exit codes, input protection and atomic report replacement.
|
|
26
|
+
- Original example file bytes and their SHA-256 digests.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Contributing
|
|
2
|
+
|
|
3
|
+
Use Python 3.10 or newer. Runtime code must use only the Python standard library.
|
|
4
|
+
|
|
5
|
+
## Development environment
|
|
6
|
+
|
|
7
|
+
Create and activate a virtual environment:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
python -m venv .venv
|
|
11
|
+
# Linux/macOS
|
|
12
|
+
. .venv/bin/activate
|
|
13
|
+
# Windows PowerShell (use this instead of the preceding activation command)
|
|
14
|
+
.venv\Scripts\Activate.ps1
|
|
15
|
+
python -m pip install -e .
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
For optional pytest-based development, install `pytest` separately.
|
|
19
|
+
CI installs the editable package and pytest, then runs the same unittest cases.
|
|
20
|
+
|
|
21
|
+
## Offline tests without installation
|
|
22
|
+
|
|
23
|
+
POSIX shell:
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
PYTHONPATH=src python -X utf8 -m unittest discover -s tests -v
|
|
27
|
+
PYTHONPATH=src python -X utf8 tests/check_golden.py
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Windows PowerShell:
|
|
31
|
+
|
|
32
|
+
```powershell
|
|
33
|
+
[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
|
34
|
+
$env:PYTHONPATH = "src"
|
|
35
|
+
python -X utf8 -m unittest discover -s tests -v
|
|
36
|
+
python -X utf8 tests/check_golden.py
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
After editable installation, `python -X utf8 -m pytest -v` also runs the suite.
|
|
40
|
+
CI uses Ubuntu and Windows with Python 3.10, 3.11, 3.12 and 3.13, and separately
|
|
41
|
+
compares the golden report through both module and installed console entry points.
|
|
42
|
+
|
|
43
|
+
## Change requirements
|
|
44
|
+
|
|
45
|
+
- Use only synthetic data. Never submit private or paid market data, credentials
|
|
46
|
+
or proprietary datasets in code, fixtures, issue reports or logs.
|
|
47
|
+
- Generate new test data inside temporary directories; use `unittest.TestCase`
|
|
48
|
+
so no third-party runner is needed locally.
|
|
49
|
+
- Preserve CLI flags and exit-code meanings, deterministic JSON field order,
|
|
50
|
+
Chinese reason strings and input-file protection.
|
|
51
|
+
- Do not change `examples/daily.csv`, `examples/calendar.csv`,
|
|
52
|
+
`examples/expected-report.json` or `.gitattributes`. Their exact bytes and
|
|
53
|
+
SHA-256 digests are regression evidence.
|
|
54
|
+
- Keep project text UTF-8 with LF. Do not normalize the example files.
|
|
55
|
+
- Include focused regression tests and document implemented behavior. Label
|
|
56
|
+
future work as not implemented.
|
|
57
|
+
- Send a pull request describing the problem, resulting behavior and validation.
|
twse_audit-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 liangyiK
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: twse-audit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Offline TWSE daily OHLCV CSV auditing against a supplied market calendar
|
|
5
|
+
Author: liangyiK
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/liangyiK/twse-audit
|
|
8
|
+
Project-URL: Repository, https://github.com/liangyiK/twse-audit
|
|
9
|
+
Project-URL: Issues, https://github.com/liangyiK/twse-audit/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/liangyiK/twse-audit/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: twse,taiwan,ohlcv,csv,audit,market-calendar
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# twse-audit
|
|
30
|
+
|
|
31
|
+
Offline auditing of TWSE daily OHLCV CSV files against a supplied market calendar.
|
|
32
|
+
Produces a deterministic JSON issue report and dates needing backfill.
|
|
33
|
+
Python 3.10+, standard library only, no runtime dependencies.
|
|
34
|
+
|
|
35
|
+
[繁體中文](https://github.com/liangyiK/twse-audit/blob/main/README.zh-TW.md) · [Contributing](https://github.com/liangyiK/twse-audit/blob/main/CONTRIBUTING.md) · [Changelog](https://github.com/liangyiK/twse-audit/blob/main/CHANGELOG.md)
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
Install from a local checkout:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
python -m pip install .
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The distribution name is `twse-audit`; the Python package is `twse_audit`.
|
|
46
|
+
After a release is published to PyPI, installation will be
|
|
47
|
+
`python -m pip install twse-audit`. This repository does not establish that a
|
|
48
|
+
PyPI release already exists.
|
|
49
|
+
|
|
50
|
+
## One-minute example
|
|
51
|
+
|
|
52
|
+
From the repository root after installation:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
twse-audit --csv examples/daily.csv --calendar examples/calendar.csv --start 2018-12-21 --end 2018-12-23 --output audit.json
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The equivalent module command is:
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
python -m twse_audit --csv examples/daily.csv --calendar examples/calendar.csv --start 2018-12-21 --end 2018-12-23 --output audit.json
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The synthetic example reports a duplicate symbol/date on December 21, missing
|
|
65
|
+
usable daily data on the Saturday open session of December 22, and unexpected
|
|
66
|
+
data on the closed December 23 session. Exit code **1 is expected**.
|
|
67
|
+
The output matches `examples/expected-report.json` byte for byte.
|
|
68
|
+
Omit `--output` to write the same UTF-8/LF JSON to stdout.
|
|
69
|
+
The output file is written to a temporary file in the same directory and then
|
|
70
|
+
replaced; its parent directory must exist. Output cannot resolve to either
|
|
71
|
+
input path. Report contents contain no input paths.
|
|
72
|
+
|
|
73
|
+
## Input formats
|
|
74
|
+
|
|
75
|
+
Both files are UTF-8 CSV (an optional UTF-8 BOM is accepted), with a header.
|
|
76
|
+
Required column names are case-sensitive; extra columns are allowed.
|
|
77
|
+
Use ISO `YYYY-MM-DD` dates. The inclusive range is selected by `--start` and `--end`.
|
|
78
|
+
|
|
79
|
+
Daily data:
|
|
80
|
+
|
|
81
|
+
```csv
|
|
82
|
+
date,symbol,open,high,low,close,volume
|
|
83
|
+
2018-12-21,0050,30,33,29,32,1000
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Symbols remain strings, including leading zeros. Prices must be finite positive
|
|
87
|
+
decimal numbers; low/high must cover open and close. Volume is a nonnegative
|
|
88
|
+
integer number of shares. The duplicate key is `(date, symbol)`; this format
|
|
89
|
+
assumes one daily row per symbol. Convert thousands separators, ROC dates and
|
|
90
|
+
other source formats before auditing.
|
|
91
|
+
|
|
92
|
+
Calendar:
|
|
93
|
+
|
|
94
|
+
```csv
|
|
95
|
+
date,status,source
|
|
96
|
+
2018-12-21,open,synthetic
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Each date must be unique, and `source` must be nonempty. It records the supplied
|
|
100
|
+
evidence reference; the tool does not fetch or verify that reference.
|
|
101
|
+
|
|
102
|
+
| Status | Meaning and behavior |
|
|
103
|
+
| --- | --- |
|
|
104
|
+
| `open` | A trading session; no valid daily rows produces an issue and a backfill date. |
|
|
105
|
+
| `closed` | No trading; any observed daily rows produce an issue. |
|
|
106
|
+
| `settlement_only` | Settlement without trading; any observed daily rows produce an issue. |
|
|
107
|
+
| `unknown` | An issue is always reported; never added to backfill. |
|
|
108
|
+
|
|
109
|
+
A date missing from the calendar becomes `unknown` with a null source.
|
|
110
|
+
Weekends, typhoon closures and settlement-only days follow the supplied calendar;
|
|
111
|
+
there is no weekday heuristic.
|
|
112
|
+
|
|
113
|
+
## Exit codes
|
|
114
|
+
|
|
115
|
+
| Code | Meaning |
|
|
116
|
+
| --- | --- |
|
|
117
|
+
| 0 | No issues. |
|
|
118
|
+
| 1 | Issues found, including unknown calendar dates. A report is produced. |
|
|
119
|
+
| 2 | Input, argument or execution error. No successful report is produced. |
|
|
120
|
+
|
|
121
|
+
Input validation errors leave an existing report untouched. Successful file
|
|
122
|
+
output replaces the report atomically on the destination filesystem.
|
|
123
|
+
|
|
124
|
+
## Report fields
|
|
125
|
+
|
|
126
|
+
Schema version 1 preserves the following top-level order:
|
|
127
|
+
|
|
128
|
+
| Field | Contents |
|
|
129
|
+
| --- | --- |
|
|
130
|
+
| `schema_version` | Integer `1`. |
|
|
131
|
+
| `dataset` | `TWSE daily OHLCV`. |
|
|
132
|
+
| `range` | Inclusive `start` and `end`. |
|
|
133
|
+
| `input_sha256` | SHA-256 of the exact `daily_csv` and `calendar_csv` bytes. |
|
|
134
|
+
| `calendar_days` | Day counts by status, sorted by status name. |
|
|
135
|
+
| `input_rows_in_range` | Observed rows with a parseable date in the range and required fields present. |
|
|
136
|
+
| `issue_counts` | Counts by issue code, sorted by code. |
|
|
137
|
+
| `issues` | Ordered issue objects: row issues in input order, followed by calendar issues in date order. |
|
|
138
|
+
| `backfill` | Open dates without usable daily rows, with calendar status, source and Chinese reason. |
|
|
139
|
+
|
|
140
|
+
Issue codes are `invalid_row`, `duplicate_key`, `calendar_unknown`,
|
|
141
|
+
`missing_daily_data` and `unexpected_daily_data`. Depending on the issue, fields
|
|
142
|
+
include a CSV `line`, `date`, `symbol`, `detail`, `calendar_status`, `source`,
|
|
143
|
+
and observed `rows`. Details and backfill reasons retain their Chinese wording.
|
|
144
|
+
Identical input bytes and arguments produce identical JSON bytes.
|
|
145
|
+
|
|
146
|
+
For Python callers, `twse_audit.core.audit(data_path, calendar_path, start, end)`
|
|
147
|
+
accepts `pathlib.Path` inputs and `datetime.date` bounds and returns a dictionary.
|
|
148
|
+
The core reads and validates inputs without printing or writing a report.
|
|
149
|
+
|
|
150
|
+
## Limitations
|
|
151
|
+
|
|
152
|
+
Coverage is checked at the market-day level: one valid row makes an open day
|
|
153
|
+
covered. Per-symbol completeness requires a daily listing universe, which is
|
|
154
|
+
not implemented. A duplicate is reported but can still count as usable if its
|
|
155
|
+
values pass validation. Invalid dates and malformed rows may be reported even
|
|
156
|
+
when they cannot be assigned to the requested range. Files are read into memory.
|
|
157
|
+
The report lists backfill dates; it does not download or repair data, validate
|
|
158
|
+
calendar evidence, update a dashboard or replay announcement timing.
|
|
159
|
+
|
|
160
|
+
## Roadmap — not implemented
|
|
161
|
+
|
|
162
|
+
- Official source format conversion.
|
|
163
|
+
- Resumable backfill.
|
|
164
|
+
- Per-symbol coverage checks using a daily listing universe.
|
|
165
|
+
|
|
166
|
+
## Development and license
|
|
167
|
+
|
|
168
|
+
See [CONTRIBUTING.md](https://github.com/liangyiK/twse-audit/blob/main/CONTRIBUTING.md) for offline standard-library tests and CI.
|
|
169
|
+
Only synthetic fixtures belong in this repository. Licensed under the
|
|
170
|
+
[MIT License](https://github.com/liangyiK/twse-audit/blob/main/LICENSE).
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# twse-audit
|
|
2
|
+
|
|
3
|
+
Offline auditing of TWSE daily OHLCV CSV files against a supplied market calendar.
|
|
4
|
+
Produces a deterministic JSON issue report and dates needing backfill.
|
|
5
|
+
Python 3.10+, standard library only, no runtime dependencies.
|
|
6
|
+
|
|
7
|
+
[繁體中文](https://github.com/liangyiK/twse-audit/blob/main/README.zh-TW.md) · [Contributing](https://github.com/liangyiK/twse-audit/blob/main/CONTRIBUTING.md) · [Changelog](https://github.com/liangyiK/twse-audit/blob/main/CHANGELOG.md)
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
Install from a local checkout:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
python -m pip install .
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The distribution name is `twse-audit`; the Python package is `twse_audit`.
|
|
18
|
+
After a release is published to PyPI, installation will be
|
|
19
|
+
`python -m pip install twse-audit`. This repository does not establish that a
|
|
20
|
+
PyPI release already exists.
|
|
21
|
+
|
|
22
|
+
## One-minute example
|
|
23
|
+
|
|
24
|
+
From the repository root after installation:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
twse-audit --csv examples/daily.csv --calendar examples/calendar.csv --start 2018-12-21 --end 2018-12-23 --output audit.json
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The equivalent module command is:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
python -m twse_audit --csv examples/daily.csv --calendar examples/calendar.csv --start 2018-12-21 --end 2018-12-23 --output audit.json
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The synthetic example reports a duplicate symbol/date on December 21, missing
|
|
37
|
+
usable daily data on the Saturday open session of December 22, and unexpected
|
|
38
|
+
data on the closed December 23 session. Exit code **1 is expected**.
|
|
39
|
+
The output matches `examples/expected-report.json` byte for byte.
|
|
40
|
+
Omit `--output` to write the same UTF-8/LF JSON to stdout.
|
|
41
|
+
The output file is written to a temporary file in the same directory and then
|
|
42
|
+
replaced; its parent directory must exist. Output cannot resolve to either
|
|
43
|
+
input path. Report contents contain no input paths.
|
|
44
|
+
|
|
45
|
+
## Input formats
|
|
46
|
+
|
|
47
|
+
Both files are UTF-8 CSV (an optional UTF-8 BOM is accepted), with a header.
|
|
48
|
+
Required column names are case-sensitive; extra columns are allowed.
|
|
49
|
+
Use ISO `YYYY-MM-DD` dates. The inclusive range is selected by `--start` and `--end`.
|
|
50
|
+
|
|
51
|
+
Daily data:
|
|
52
|
+
|
|
53
|
+
```csv
|
|
54
|
+
date,symbol,open,high,low,close,volume
|
|
55
|
+
2018-12-21,0050,30,33,29,32,1000
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Symbols remain strings, including leading zeros. Prices must be finite positive
|
|
59
|
+
decimal numbers; low/high must cover open and close. Volume is a nonnegative
|
|
60
|
+
integer number of shares. The duplicate key is `(date, symbol)`; this format
|
|
61
|
+
assumes one daily row per symbol. Convert thousands separators, ROC dates and
|
|
62
|
+
other source formats before auditing.
|
|
63
|
+
|
|
64
|
+
Calendar:
|
|
65
|
+
|
|
66
|
+
```csv
|
|
67
|
+
date,status,source
|
|
68
|
+
2018-12-21,open,synthetic
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Each date must be unique, and `source` must be nonempty. It records the supplied
|
|
72
|
+
evidence reference; the tool does not fetch or verify that reference.
|
|
73
|
+
|
|
74
|
+
| Status | Meaning and behavior |
|
|
75
|
+
| --- | --- |
|
|
76
|
+
| `open` | A trading session; no valid daily rows produces an issue and a backfill date. |
|
|
77
|
+
| `closed` | No trading; any observed daily rows produce an issue. |
|
|
78
|
+
| `settlement_only` | Settlement without trading; any observed daily rows produce an issue. |
|
|
79
|
+
| `unknown` | An issue is always reported; never added to backfill. |
|
|
80
|
+
|
|
81
|
+
A date missing from the calendar becomes `unknown` with a null source.
|
|
82
|
+
Weekends, typhoon closures and settlement-only days follow the supplied calendar;
|
|
83
|
+
there is no weekday heuristic.
|
|
84
|
+
|
|
85
|
+
## Exit codes
|
|
86
|
+
|
|
87
|
+
| Code | Meaning |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| 0 | No issues. |
|
|
90
|
+
| 1 | Issues found, including unknown calendar dates. A report is produced. |
|
|
91
|
+
| 2 | Input, argument or execution error. No successful report is produced. |
|
|
92
|
+
|
|
93
|
+
Input validation errors leave an existing report untouched. Successful file
|
|
94
|
+
output replaces the report atomically on the destination filesystem.
|
|
95
|
+
|
|
96
|
+
## Report fields
|
|
97
|
+
|
|
98
|
+
Schema version 1 preserves the following top-level order:
|
|
99
|
+
|
|
100
|
+
| Field | Contents |
|
|
101
|
+
| --- | --- |
|
|
102
|
+
| `schema_version` | Integer `1`. |
|
|
103
|
+
| `dataset` | `TWSE daily OHLCV`. |
|
|
104
|
+
| `range` | Inclusive `start` and `end`. |
|
|
105
|
+
| `input_sha256` | SHA-256 of the exact `daily_csv` and `calendar_csv` bytes. |
|
|
106
|
+
| `calendar_days` | Day counts by status, sorted by status name. |
|
|
107
|
+
| `input_rows_in_range` | Observed rows with a parseable date in the range and required fields present. |
|
|
108
|
+
| `issue_counts` | Counts by issue code, sorted by code. |
|
|
109
|
+
| `issues` | Ordered issue objects: row issues in input order, followed by calendar issues in date order. |
|
|
110
|
+
| `backfill` | Open dates without usable daily rows, with calendar status, source and Chinese reason. |
|
|
111
|
+
|
|
112
|
+
Issue codes are `invalid_row`, `duplicate_key`, `calendar_unknown`,
|
|
113
|
+
`missing_daily_data` and `unexpected_daily_data`. Depending on the issue, fields
|
|
114
|
+
include a CSV `line`, `date`, `symbol`, `detail`, `calendar_status`, `source`,
|
|
115
|
+
and observed `rows`. Details and backfill reasons retain their Chinese wording.
|
|
116
|
+
Identical input bytes and arguments produce identical JSON bytes.
|
|
117
|
+
|
|
118
|
+
For Python callers, `twse_audit.core.audit(data_path, calendar_path, start, end)`
|
|
119
|
+
accepts `pathlib.Path` inputs and `datetime.date` bounds and returns a dictionary.
|
|
120
|
+
The core reads and validates inputs without printing or writing a report.
|
|
121
|
+
|
|
122
|
+
## Limitations
|
|
123
|
+
|
|
124
|
+
Coverage is checked at the market-day level: one valid row makes an open day
|
|
125
|
+
covered. Per-symbol completeness requires a daily listing universe, which is
|
|
126
|
+
not implemented. A duplicate is reported but can still count as usable if its
|
|
127
|
+
values pass validation. Invalid dates and malformed rows may be reported even
|
|
128
|
+
when they cannot be assigned to the requested range. Files are read into memory.
|
|
129
|
+
The report lists backfill dates; it does not download or repair data, validate
|
|
130
|
+
calendar evidence, update a dashboard or replay announcement timing.
|
|
131
|
+
|
|
132
|
+
## Roadmap — not implemented
|
|
133
|
+
|
|
134
|
+
- Official source format conversion.
|
|
135
|
+
- Resumable backfill.
|
|
136
|
+
- Per-symbol coverage checks using a daily listing universe.
|
|
137
|
+
|
|
138
|
+
## Development and license
|
|
139
|
+
|
|
140
|
+
See [CONTRIBUTING.md](https://github.com/liangyiK/twse-audit/blob/main/CONTRIBUTING.md) for offline standard-library tests and CI.
|
|
141
|
+
Only synthetic fixtures belong in this repository. Licensed under the
|
|
142
|
+
[MIT License](https://github.com/liangyiK/twse-audit/blob/main/LICENSE).
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# twse-audit · TWSE 日線資料檢查器
|
|
2
|
+
|
|
3
|
+
用本機 CSV 確認哪天應該有交易、哪天的日線缺漏、哪些資料不符合格式。
|
|
4
|
+
產生可重現的 JSON 問題清單及待回補日期。Python 3.10+,標準函式庫,
|
|
5
|
+
無執行期依賴,離線執行。
|
|
6
|
+
|
|
7
|
+
[English](README.md) · [參與開發](CONTRIBUTING.md) · [更新紀錄](CHANGELOG.md)
|
|
8
|
+
|
|
9
|
+
## 安裝
|
|
10
|
+
|
|
11
|
+
從本機專案目錄安裝:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
python -m pip install .
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
套件發行名稱為 `twse-audit`,Python 套件名稱為 `twse_audit`。
|
|
18
|
+
發布至 PyPI 後可用 `python -m pip install twse-audit` 安裝;
|
|
19
|
+
本專案文件不表示 PyPI 已有發行版本。
|
|
20
|
+
|
|
21
|
+
## 一分鐘範例
|
|
22
|
+
|
|
23
|
+
安裝後,在本專案根目錄執行:
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
twse-audit --csv examples/daily.csv --calendar examples/calendar.csv --start 2018-12-21 --end 2018-12-23 --output audit.json
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
也可執行等效的模組指令:
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
python -m twse_audit --csv examples/daily.csv --calendar examples/calendar.csv --start 2018-12-21 --end 2018-12-23 --output audit.json
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
內附日線列是合成測資。結果會指出 12 月 21 日同股同日重複、
|
|
36
|
+
12 月 22 日週六有交易但缺可用資料、12 月 23 日休市卻有資料。
|
|
37
|
+
**預期結束碼是 1**;輸出與 `examples/expected-report.json` 逐位元組相同。
|
|
38
|
+
不指定 `--output` 時,會將相同的 UTF-8/LF JSON 寫至 stdout。
|
|
39
|
+
檔案輸出先寫同目錄暫存檔再 replace;輸出目錄必須存在,
|
|
40
|
+
輸出路徑解析後不可等於任一輸入路徑。報告內容不含輸入檔路徑。
|
|
41
|
+
|
|
42
|
+
## 輸入格式
|
|
43
|
+
|
|
44
|
+
兩個檔案都使用含標頭的 UTF-8 CSV,可含 UTF-8 BOM。
|
|
45
|
+
必要欄名區分大小寫,可有額外欄位。日期使用 ISO `YYYY-MM-DD`。
|
|
46
|
+
`--start` 與 `--end` 的日期範圍含頭尾兩天。
|
|
47
|
+
|
|
48
|
+
日線:
|
|
49
|
+
|
|
50
|
+
```csv
|
|
51
|
+
date,symbol,open,high,low,close,volume
|
|
52
|
+
2018-12-21,0050,30,33,29,32,1000
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
股票代號保留為字串,包括前綴零。OHLC 須為有限正數,
|
|
56
|
+
最低價與最高價須涵蓋開盤價、收盤價;成交股數須為非負整數。
|
|
57
|
+
重複鍵為日期與代號;適用於每檔每天一列的日線。
|
|
58
|
+
需要千分位或民國日期的原始檔,先轉成此格式。
|
|
59
|
+
|
|
60
|
+
日曆:
|
|
61
|
+
|
|
62
|
+
```csv
|
|
63
|
+
date,status,source
|
|
64
|
+
2018-12-21,open,synthetic
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
日期不可重複,`source` 不可空白,用於記錄日曆證據來源;
|
|
68
|
+
工具不會下載或查證該來源。
|
|
69
|
+
|
|
70
|
+
| 狀態 | 意義與行為 |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `open` | 開市;沒有合格日線列時回報異常並列入待回補日期。 |
|
|
73
|
+
| `closed` | 休市;有日線列時回報異常。 |
|
|
74
|
+
| `settlement_only` | 僅交割、不交易;有日線列時回報異常。 |
|
|
75
|
+
| `unknown` | 未知;一律回報異常,不列入回補。 |
|
|
76
|
+
|
|
77
|
+
日曆沒列到的日期視為 `unknown`,來源為 null。
|
|
78
|
+
週末、颱風與僅交割以提供的日曆為準,不依星期推斷。
|
|
79
|
+
|
|
80
|
+
## 結束碼
|
|
81
|
+
|
|
82
|
+
| 結束碼 | 意義 |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| 0 | 通過,沒有異常。 |
|
|
85
|
+
| 1 | 有異常或未知日期,仍產生報告。 |
|
|
86
|
+
| 2 | 輸入、參數或執行錯誤,未成功產生報告。 |
|
|
87
|
+
|
|
88
|
+
輸入驗證失敗時保留既有報告;成功寫檔時在目的檔案系統以 replace
|
|
89
|
+
原子替換報告。
|
|
90
|
+
|
|
91
|
+
## 報告欄位
|
|
92
|
+
|
|
93
|
+
結構版本 1 保留以下頂層欄位順序:
|
|
94
|
+
|
|
95
|
+
| 欄位 | 內容 |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `schema_version` | 整數 `1`。 |
|
|
98
|
+
| `dataset` | `TWSE daily OHLCV`。 |
|
|
99
|
+
| `range` | 含頭尾的 `start`、`end`。 |
|
|
100
|
+
| `input_sha256` | `daily_csv`、`calendar_csv` 原始位元組的 SHA-256。 |
|
|
101
|
+
| `calendar_days` | 各狀態天數,依狀態名稱排序。 |
|
|
102
|
+
| `input_rows_in_range` | 必要欄位完整且日期可解析、落在範圍內的觀察列數。 |
|
|
103
|
+
| `issue_counts` | 各問題代碼的數量,依代碼排序。 |
|
|
104
|
+
| `issues` | 先依輸入順序列出資料列問題,再依日期列出日曆問題。 |
|
|
105
|
+
| `backfill` | 開市但沒有可用日線列的日期、日曆狀態、來源與中文原因。 |
|
|
106
|
+
|
|
107
|
+
問題代碼包括 `invalid_row`、`duplicate_key`、`calendar_unknown`、
|
|
108
|
+
`missing_daily_data`、`unexpected_daily_data`。
|
|
109
|
+
依問題類型包含 CSV 行數 `line`、日期 `date`、代號 `symbol`、
|
|
110
|
+
說明 `detail`、日曆狀態 `calendar_status`、來源 `source`、
|
|
111
|
+
觀察列數 `rows`。說明與待回補原因沿用中文。
|
|
112
|
+
相同輸入位元組與參數重跑會得到相同 JSON 位元組。
|
|
113
|
+
|
|
114
|
+
Python 呼叫端可使用
|
|
115
|
+
`twse_audit.core.audit(data_path, calendar_path, start, end)`;
|
|
116
|
+
檔案參數為 `pathlib.Path`,日期為 `datetime.date`,回傳 dict。
|
|
117
|
+
核心只讀檔與驗證,不印出結果、不寫報告。
|
|
118
|
+
|
|
119
|
+
## 限制
|
|
120
|
+
|
|
121
|
+
單一市場交易日只要有一筆合格日線即視為當天有資料;
|
|
122
|
+
個股覆蓋率需另有每日上市名單才能驗證,目前尚未實作。
|
|
123
|
+
重複列會回報異常,但數值合格時仍可計入可用資料。
|
|
124
|
+
無法解析日期或欄位數錯誤的資料列,即使無法歸入查詢範圍也可能回報。
|
|
125
|
+
檔案會完整讀入記憶體。這版的回補是**列出待補日期**;
|
|
126
|
+
不會自動抓取或修復資料、查證日曆來源、更新正式儀表板或回放公告時點。
|
|
127
|
+
|
|
128
|
+
## 路線圖(尚未實作)
|
|
129
|
+
|
|
130
|
+
- 官方格式轉換。
|
|
131
|
+
- 可續跑回補。
|
|
132
|
+
- 搭配每日上市名單的逐股覆蓋檢查。
|
|
133
|
+
|
|
134
|
+
## 開發與授權
|
|
135
|
+
|
|
136
|
+
離線標準函式庫測試與 CI 說明見 [CONTRIBUTING.md](CONTRIBUTING.md)。
|
|
137
|
+
專案只收合成測資,採用 [MIT 授權](LICENSE)。
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
date,status,source
|
|
2
|
+
2018-12-21,open,https://www.twse.com.tw/exchangeReport/FMTQIK?response=json&date=20181201
|
|
3
|
+
2018-12-22,open,https://www.twse.com.tw/exchangeReport/FMTQIK?response=json&date=20181201
|
|
4
|
+
2018-12-23,closed,https://www.twse.com.tw/exchangeReport/FMTQIK?response=json&date=20181201
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema_version": 1,
|
|
3
|
+
"dataset": "TWSE daily OHLCV",
|
|
4
|
+
"range": {
|
|
5
|
+
"start": "2018-12-21",
|
|
6
|
+
"end": "2018-12-23"
|
|
7
|
+
},
|
|
8
|
+
"input_sha256": {
|
|
9
|
+
"daily_csv": "3843242b7ee000d766e692f66541be8c9a6c6f2a13b33141bcffa3710cdf6eb4",
|
|
10
|
+
"calendar_csv": "28e86929a027d45718557d9f3ae62d337e259ddbfe11d6625f7b3f50c2b45f4c"
|
|
11
|
+
},
|
|
12
|
+
"calendar_days": {
|
|
13
|
+
"closed": 1,
|
|
14
|
+
"open": 2
|
|
15
|
+
},
|
|
16
|
+
"input_rows_in_range": 3,
|
|
17
|
+
"issue_counts": {
|
|
18
|
+
"duplicate_key": 1,
|
|
19
|
+
"missing_daily_data": 1,
|
|
20
|
+
"unexpected_daily_data": 1
|
|
21
|
+
},
|
|
22
|
+
"issues": [
|
|
23
|
+
{
|
|
24
|
+
"code": "duplicate_key",
|
|
25
|
+
"line": 3,
|
|
26
|
+
"date": "2018-12-21",
|
|
27
|
+
"symbol": "DEMO01"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"code": "missing_daily_data",
|
|
31
|
+
"date": "2018-12-22",
|
|
32
|
+
"calendar_status": "open",
|
|
33
|
+
"source": "https://www.twse.com.tw/exchangeReport/FMTQIK?response=json&date=20181201",
|
|
34
|
+
"rows": 0
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
"code": "unexpected_daily_data",
|
|
38
|
+
"date": "2018-12-23",
|
|
39
|
+
"calendar_status": "closed",
|
|
40
|
+
"source": "https://www.twse.com.tw/exchangeReport/FMTQIK?response=json&date=20181201",
|
|
41
|
+
"rows": 1
|
|
42
|
+
}
|
|
43
|
+
],
|
|
44
|
+
"backfill": [
|
|
45
|
+
{
|
|
46
|
+
"date": "2018-12-22",
|
|
47
|
+
"calendar_status": "open",
|
|
48
|
+
"source": "https://www.twse.com.tw/exchangeReport/FMTQIK?response=json&date=20181201",
|
|
49
|
+
"reason": "開市但沒有可用日線列"
|
|
50
|
+
}
|
|
51
|
+
]
|
|
52
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "twse-audit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Offline TWSE daily OHLCV CSV auditing against a supplied market calendar"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [{name = "liangyiK"}]
|
|
13
|
+
keywords = ["twse", "taiwan", "ohlcv", "csv", "audit", "market-calendar"]
|
|
14
|
+
dependencies = []
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Environment :: Console",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
23
|
+
"Programming Language :: Python :: 3.10",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Topic :: Office/Business :: Financial",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.scripts]
|
|
31
|
+
twse-audit = "twse_audit.cli:main"
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://github.com/liangyiK/twse-audit"
|
|
35
|
+
Repository = "https://github.com/liangyiK/twse-audit"
|
|
36
|
+
Issues = "https://github.com/liangyiK/twse-audit/issues"
|
|
37
|
+
Changelog = "https://github.com/liangyiK/twse-audit/blob/main/CHANGELOG.md"
|
|
38
|
+
|
|
39
|
+
[tool.setuptools.packages.find]
|
|
40
|
+
where = ["src"]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Command-line interface and atomic report output."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import csv
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from contextlib import suppress
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from tempfile import NamedTemporaryFile
|
|
10
|
+
|
|
11
|
+
from .core import audit, iso_date
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def write_report(target, payload):
|
|
15
|
+
temporary = None
|
|
16
|
+
try:
|
|
17
|
+
with NamedTemporaryFile(
|
|
18
|
+
dir=target.parent, prefix=".twse_audit_", delete=False,
|
|
19
|
+
mode="w", encoding="utf-8", newline="\n"
|
|
20
|
+
) as handle:
|
|
21
|
+
temporary = Path(handle.name)
|
|
22
|
+
handle.write(payload)
|
|
23
|
+
temporary.replace(target)
|
|
24
|
+
finally:
|
|
25
|
+
if temporary is not None:
|
|
26
|
+
with suppress(FileNotFoundError):
|
|
27
|
+
temporary.unlink()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main():
|
|
31
|
+
parser = argparse.ArgumentParser(description="以交易日曆檢查 TWSE 日線 CSV 並列出回補日期")
|
|
32
|
+
parser.add_argument("--csv", type=Path, required=True)
|
|
33
|
+
parser.add_argument("--calendar", type=Path, required=True)
|
|
34
|
+
parser.add_argument("--start", required=True)
|
|
35
|
+
parser.add_argument("--end", required=True)
|
|
36
|
+
parser.add_argument("--output", type=Path)
|
|
37
|
+
options = parser.parse_args()
|
|
38
|
+
try:
|
|
39
|
+
if options.output is not None:
|
|
40
|
+
output = options.output.resolve()
|
|
41
|
+
if output in {options.csv.resolve(), options.calendar.resolve()}:
|
|
42
|
+
raise ValueError("輸出檔不能是輸入檔")
|
|
43
|
+
result = audit(options.csv, options.calendar, iso_date(options.start), iso_date(options.end))
|
|
44
|
+
payload = json.dumps(result, ensure_ascii=False, indent=2) + "\n"
|
|
45
|
+
if options.output is None:
|
|
46
|
+
sys.stdout.reconfigure(encoding="utf-8", newline="\n")
|
|
47
|
+
print(payload, end="")
|
|
48
|
+
else:
|
|
49
|
+
write_report(options.output, payload)
|
|
50
|
+
except (OSError, ValueError, csv.Error) as exc:
|
|
51
|
+
print(f"檢查失敗:{exc}", file=sys.stderr)
|
|
52
|
+
return 2
|
|
53
|
+
return int(bool(result["issues"]))
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Audit a TWSE daily OHLCV CSV against a supplied market calendar."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import hashlib
|
|
5
|
+
import io
|
|
6
|
+
from collections import Counter
|
|
7
|
+
from datetime import date, timedelta
|
|
8
|
+
from decimal import Decimal, InvalidOperation
|
|
9
|
+
|
|
10
|
+
PRICE_FIELDS = ("open", "high", "low", "close")
|
|
11
|
+
DATA_FIELDS = ("date", "symbol", *PRICE_FIELDS, "volume")
|
|
12
|
+
CALENDAR_FIELDS = ("date", "status", "source")
|
|
13
|
+
CALENDAR_STATUSES = {"open", "closed", "settlement_only", "unknown"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def iso_date(value):
|
|
17
|
+
try:
|
|
18
|
+
parsed = date.fromisoformat(value)
|
|
19
|
+
except ValueError as exc:
|
|
20
|
+
raise ValueError(f"日期必須是 YYYY-MM-DD,收到 {value!r}") from exc
|
|
21
|
+
if value != parsed.isoformat():
|
|
22
|
+
raise ValueError(f"日期必須是 YYYY-MM-DD,收到 {value!r}")
|
|
23
|
+
return parsed
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def read_csv(path, required):
|
|
27
|
+
content = path.read_bytes()
|
|
28
|
+
rows = csv.DictReader(io.StringIO(content.decode("utf-8-sig"), newline=""), strict=True)
|
|
29
|
+
fields = rows.fieldnames or []
|
|
30
|
+
if len(fields) != len(set(fields)):
|
|
31
|
+
raise ValueError(f"{path}: CSV 欄名重複")
|
|
32
|
+
missing = [name for name in required if name not in fields]
|
|
33
|
+
if missing:
|
|
34
|
+
raise ValueError(f"{path}: CSV 缺少欄位 {', '.join(missing)}")
|
|
35
|
+
return hashlib.sha256(content).hexdigest(), rows
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def read_calendar(path):
|
|
39
|
+
digest, rows = read_csv(path, CALENDAR_FIELDS)
|
|
40
|
+
calendar = {}
|
|
41
|
+
for row in rows:
|
|
42
|
+
if None in row or any(row[field] is None for field in CALENDAR_FIELDS):
|
|
43
|
+
raise ValueError(f"{path}:{rows.line_num}: 欄位數與標頭不符")
|
|
44
|
+
day = iso_date(row["date"].strip())
|
|
45
|
+
status, source = row["status"].strip(), row["source"].strip()
|
|
46
|
+
if day in calendar or status not in CALENDAR_STATUSES or not source:
|
|
47
|
+
raise ValueError(f"{path}:{rows.line_num}: 日期重複、狀態不合法或來源未填")
|
|
48
|
+
calendar[day] = (status, source)
|
|
49
|
+
return digest, calendar
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def validate_values(row):
|
|
53
|
+
try:
|
|
54
|
+
opening, high, low, close = (Decimal(row[field].strip()) for field in PRICE_FIELDS)
|
|
55
|
+
volume = Decimal(row["volume"].strip())
|
|
56
|
+
except InvalidOperation:
|
|
57
|
+
return "價格或成交股數空白或格式錯誤"
|
|
58
|
+
if any(not value.is_finite() or value <= 0 for value in (opening, high, low, close)):
|
|
59
|
+
return "OHLC 必須是有限正數"
|
|
60
|
+
if low > min(opening, close) or high < max(opening, close):
|
|
61
|
+
return "最低價與最高價未涵蓋開盤價、收盤價"
|
|
62
|
+
if not volume.is_finite() or volume < 0 or volume != volume.to_integral_value():
|
|
63
|
+
return "成交股數須為非負整數"
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def audit(data_path, calendar_path, start, end):
|
|
68
|
+
if start > end:
|
|
69
|
+
raise ValueError("起日必須早於或等於迄日")
|
|
70
|
+
calendar_hash, calendar = read_calendar(calendar_path)
|
|
71
|
+
data_hash, rows = read_csv(data_path, DATA_FIELDS)
|
|
72
|
+
issues = []
|
|
73
|
+
observed = Counter()
|
|
74
|
+
valid = Counter()
|
|
75
|
+
keys = set()
|
|
76
|
+
|
|
77
|
+
for row in rows:
|
|
78
|
+
line = rows.line_num
|
|
79
|
+
if None in row or any(row[field] is None for field in DATA_FIELDS):
|
|
80
|
+
issues.append({"code": "invalid_row", "line": line, "detail": "欄位數與標頭不符"})
|
|
81
|
+
continue
|
|
82
|
+
try:
|
|
83
|
+
day = iso_date(row["date"].strip())
|
|
84
|
+
except ValueError as exc:
|
|
85
|
+
issues.append({"code": "invalid_row", "line": line, "detail": str(exc)})
|
|
86
|
+
continue
|
|
87
|
+
if not start <= day <= end:
|
|
88
|
+
continue
|
|
89
|
+
observed[day] += 1
|
|
90
|
+
symbol = row["symbol"].strip()
|
|
91
|
+
details = {"line": line, "date": day.isoformat(), "symbol": symbol}
|
|
92
|
+
if not symbol:
|
|
93
|
+
issues.append({"code": "invalid_row", **details, "detail": "股票代號空白"})
|
|
94
|
+
continue
|
|
95
|
+
key = (day, symbol)
|
|
96
|
+
if key in keys:
|
|
97
|
+
issues.append({"code": "duplicate_key", **details})
|
|
98
|
+
keys.add(key)
|
|
99
|
+
problem = validate_values(row)
|
|
100
|
+
if problem:
|
|
101
|
+
issues.append({"code": "invalid_row", **details, "detail": problem})
|
|
102
|
+
else:
|
|
103
|
+
valid[day] += 1
|
|
104
|
+
|
|
105
|
+
calendar_days = Counter()
|
|
106
|
+
backfill = []
|
|
107
|
+
for offset in range((end - start).days + 1):
|
|
108
|
+
day = start + timedelta(days=offset)
|
|
109
|
+
status, source = calendar.get(day, ("unknown", None))
|
|
110
|
+
calendar_days[status] += 1
|
|
111
|
+
details = {"date": day.isoformat(), "calendar_status": status, "source": source}
|
|
112
|
+
if status == "unknown":
|
|
113
|
+
issues.append({"code": "calendar_unknown", **details, "rows": observed[day]})
|
|
114
|
+
if status == "open" and not valid[day]:
|
|
115
|
+
issues.append({"code": "missing_daily_data", **details, "rows": observed[day]})
|
|
116
|
+
backfill.append({**details, "reason": "開市但沒有可用日線列"})
|
|
117
|
+
if status in ("closed", "settlement_only") and observed[day]:
|
|
118
|
+
issues.append({"code": "unexpected_daily_data", **details, "rows": observed[day]})
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
"schema_version": 1,
|
|
122
|
+
"dataset": "TWSE daily OHLCV",
|
|
123
|
+
"range": {"start": start.isoformat(), "end": end.isoformat()},
|
|
124
|
+
"input_sha256": {"daily_csv": data_hash, "calendar_csv": calendar_hash},
|
|
125
|
+
"calendar_days": dict(sorted(calendar_days.items())),
|
|
126
|
+
"input_rows_in_range": sum(observed.values()),
|
|
127
|
+
"issue_counts": dict(sorted(Counter(issue["code"] for issue in issues).items())),
|
|
128
|
+
"issues": issues,
|
|
129
|
+
"backfill": backfill,
|
|
130
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: twse-audit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Offline TWSE daily OHLCV CSV auditing against a supplied market calendar
|
|
5
|
+
Author: liangyiK
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/liangyiK/twse-audit
|
|
8
|
+
Project-URL: Repository, https://github.com/liangyiK/twse-audit
|
|
9
|
+
Project-URL: Issues, https://github.com/liangyiK/twse-audit/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/liangyiK/twse-audit/blob/main/CHANGELOG.md
|
|
11
|
+
Keywords: twse,taiwan,ohlcv,csv,audit,market-calendar
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# twse-audit
|
|
30
|
+
|
|
31
|
+
Offline auditing of TWSE daily OHLCV CSV files against a supplied market calendar.
|
|
32
|
+
Produces a deterministic JSON issue report and dates needing backfill.
|
|
33
|
+
Python 3.10+, standard library only, no runtime dependencies.
|
|
34
|
+
|
|
35
|
+
[繁體中文](https://github.com/liangyiK/twse-audit/blob/main/README.zh-TW.md) · [Contributing](https://github.com/liangyiK/twse-audit/blob/main/CONTRIBUTING.md) · [Changelog](https://github.com/liangyiK/twse-audit/blob/main/CHANGELOG.md)
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
Install from a local checkout:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
python -m pip install .
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The distribution name is `twse-audit`; the Python package is `twse_audit`.
|
|
46
|
+
After a release is published to PyPI, installation will be
|
|
47
|
+
`python -m pip install twse-audit`. This repository does not establish that a
|
|
48
|
+
PyPI release already exists.
|
|
49
|
+
|
|
50
|
+
## One-minute example
|
|
51
|
+
|
|
52
|
+
From the repository root after installation:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
twse-audit --csv examples/daily.csv --calendar examples/calendar.csv --start 2018-12-21 --end 2018-12-23 --output audit.json
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The equivalent module command is:
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
python -m twse_audit --csv examples/daily.csv --calendar examples/calendar.csv --start 2018-12-21 --end 2018-12-23 --output audit.json
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The synthetic example reports a duplicate symbol/date on December 21, missing
|
|
65
|
+
usable daily data on the Saturday open session of December 22, and unexpected
|
|
66
|
+
data on the closed December 23 session. Exit code **1 is expected**.
|
|
67
|
+
The output matches `examples/expected-report.json` byte for byte.
|
|
68
|
+
Omit `--output` to write the same UTF-8/LF JSON to stdout.
|
|
69
|
+
The output file is written to a temporary file in the same directory and then
|
|
70
|
+
replaced; its parent directory must exist. Output cannot resolve to either
|
|
71
|
+
input path. Report contents contain no input paths.
|
|
72
|
+
|
|
73
|
+
## Input formats
|
|
74
|
+
|
|
75
|
+
Both files are UTF-8 CSV (an optional UTF-8 BOM is accepted), with a header.
|
|
76
|
+
Required column names are case-sensitive; extra columns are allowed.
|
|
77
|
+
Use ISO `YYYY-MM-DD` dates. The inclusive range is selected by `--start` and `--end`.
|
|
78
|
+
|
|
79
|
+
Daily data:
|
|
80
|
+
|
|
81
|
+
```csv
|
|
82
|
+
date,symbol,open,high,low,close,volume
|
|
83
|
+
2018-12-21,0050,30,33,29,32,1000
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Symbols remain strings, including leading zeros. Prices must be finite positive
|
|
87
|
+
decimal numbers; low/high must cover open and close. Volume is a nonnegative
|
|
88
|
+
integer number of shares. The duplicate key is `(date, symbol)`; this format
|
|
89
|
+
assumes one daily row per symbol. Convert thousands separators, ROC dates and
|
|
90
|
+
other source formats before auditing.
|
|
91
|
+
|
|
92
|
+
Calendar:
|
|
93
|
+
|
|
94
|
+
```csv
|
|
95
|
+
date,status,source
|
|
96
|
+
2018-12-21,open,synthetic
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Each date must be unique, and `source` must be nonempty. It records the supplied
|
|
100
|
+
evidence reference; the tool does not fetch or verify that reference.
|
|
101
|
+
|
|
102
|
+
| Status | Meaning and behavior |
|
|
103
|
+
| --- | --- |
|
|
104
|
+
| `open` | A trading session; no valid daily rows produces an issue and a backfill date. |
|
|
105
|
+
| `closed` | No trading; any observed daily rows produce an issue. |
|
|
106
|
+
| `settlement_only` | Settlement without trading; any observed daily rows produce an issue. |
|
|
107
|
+
| `unknown` | An issue is always reported; never added to backfill. |
|
|
108
|
+
|
|
109
|
+
A date missing from the calendar becomes `unknown` with a null source.
|
|
110
|
+
Weekends, typhoon closures and settlement-only days follow the supplied calendar;
|
|
111
|
+
there is no weekday heuristic.
|
|
112
|
+
|
|
113
|
+
## Exit codes
|
|
114
|
+
|
|
115
|
+
| Code | Meaning |
|
|
116
|
+
| --- | --- |
|
|
117
|
+
| 0 | No issues. |
|
|
118
|
+
| 1 | Issues found, including unknown calendar dates. A report is produced. |
|
|
119
|
+
| 2 | Input, argument or execution error. No successful report is produced. |
|
|
120
|
+
|
|
121
|
+
Input validation errors leave an existing report untouched. Successful file
|
|
122
|
+
output replaces the report atomically on the destination filesystem.
|
|
123
|
+
|
|
124
|
+
## Report fields
|
|
125
|
+
|
|
126
|
+
Schema version 1 preserves the following top-level order:
|
|
127
|
+
|
|
128
|
+
| Field | Contents |
|
|
129
|
+
| --- | --- |
|
|
130
|
+
| `schema_version` | Integer `1`. |
|
|
131
|
+
| `dataset` | `TWSE daily OHLCV`. |
|
|
132
|
+
| `range` | Inclusive `start` and `end`. |
|
|
133
|
+
| `input_sha256` | SHA-256 of the exact `daily_csv` and `calendar_csv` bytes. |
|
|
134
|
+
| `calendar_days` | Day counts by status, sorted by status name. |
|
|
135
|
+
| `input_rows_in_range` | Observed rows with a parseable date in the range and required fields present. |
|
|
136
|
+
| `issue_counts` | Counts by issue code, sorted by code. |
|
|
137
|
+
| `issues` | Ordered issue objects: row issues in input order, followed by calendar issues in date order. |
|
|
138
|
+
| `backfill` | Open dates without usable daily rows, with calendar status, source and Chinese reason. |
|
|
139
|
+
|
|
140
|
+
Issue codes are `invalid_row`, `duplicate_key`, `calendar_unknown`,
|
|
141
|
+
`missing_daily_data` and `unexpected_daily_data`. Depending on the issue, fields
|
|
142
|
+
include a CSV `line`, `date`, `symbol`, `detail`, `calendar_status`, `source`,
|
|
143
|
+
and observed `rows`. Details and backfill reasons retain their Chinese wording.
|
|
144
|
+
Identical input bytes and arguments produce identical JSON bytes.
|
|
145
|
+
|
|
146
|
+
For Python callers, `twse_audit.core.audit(data_path, calendar_path, start, end)`
|
|
147
|
+
accepts `pathlib.Path` inputs and `datetime.date` bounds and returns a dictionary.
|
|
148
|
+
The core reads and validates inputs without printing or writing a report.
|
|
149
|
+
|
|
150
|
+
## Limitations
|
|
151
|
+
|
|
152
|
+
Coverage is checked at the market-day level: one valid row makes an open day
|
|
153
|
+
covered. Per-symbol completeness requires a daily listing universe, which is
|
|
154
|
+
not implemented. A duplicate is reported but can still count as usable if its
|
|
155
|
+
values pass validation. Invalid dates and malformed rows may be reported even
|
|
156
|
+
when they cannot be assigned to the requested range. Files are read into memory.
|
|
157
|
+
The report lists backfill dates; it does not download or repair data, validate
|
|
158
|
+
calendar evidence, update a dashboard or replay announcement timing.
|
|
159
|
+
|
|
160
|
+
## Roadmap — not implemented
|
|
161
|
+
|
|
162
|
+
- Official source format conversion.
|
|
163
|
+
- Resumable backfill.
|
|
164
|
+
- Per-symbol coverage checks using a daily listing universe.
|
|
165
|
+
|
|
166
|
+
## Development and license
|
|
167
|
+
|
|
168
|
+
See [CONTRIBUTING.md](https://github.com/liangyiK/twse-audit/blob/main/CONTRIBUTING.md) for offline standard-library tests and CI.
|
|
169
|
+
Only synthetic fixtures belong in this repository. Licensed under the
|
|
170
|
+
[MIT License](https://github.com/liangyiK/twse-audit/blob/main/LICENSE).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
.gitattributes
|
|
2
|
+
CHANGELOG.md
|
|
3
|
+
CONTRIBUTING.md
|
|
4
|
+
LICENSE
|
|
5
|
+
MANIFEST.in
|
|
6
|
+
README.md
|
|
7
|
+
README.zh-TW.md
|
|
8
|
+
pyproject.toml
|
|
9
|
+
examples/calendar.csv
|
|
10
|
+
examples/daily.csv
|
|
11
|
+
examples/expected-report.json
|
|
12
|
+
src/twse_audit/__init__.py
|
|
13
|
+
src/twse_audit/__main__.py
|
|
14
|
+
src/twse_audit/cli.py
|
|
15
|
+
src/twse_audit/core.py
|
|
16
|
+
src/twse_audit.egg-info/PKG-INFO
|
|
17
|
+
src/twse_audit.egg-info/SOURCES.txt
|
|
18
|
+
src/twse_audit.egg-info/dependency_links.txt
|
|
19
|
+
src/twse_audit.egg-info/entry_points.txt
|
|
20
|
+
src/twse_audit.egg-info/top_level.txt
|
|
21
|
+
tests/check_golden.py
|
|
22
|
+
tests/test_audit.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
twse_audit
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Standalone byte comparison used by CI; no third-party dependencies."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
|
|
9
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main():
|
|
13
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
14
|
+
output = Path(directory) / "report.json"
|
|
15
|
+
arguments = [
|
|
16
|
+
"--csv", str(ROOT / "examples/daily.csv"),
|
|
17
|
+
"--calendar", str(ROOT / "examples/calendar.csv"),
|
|
18
|
+
"--start", "2018-12-21", "--end", "2018-12-23",
|
|
19
|
+
]
|
|
20
|
+
expected = (ROOT / "examples/expected-report.json").read_bytes()
|
|
21
|
+
module = [sys.executable, "-m", "twse_audit"]
|
|
22
|
+
commands = [module]
|
|
23
|
+
if os.environ.get("TWSE_AUDIT_CHECK_CONSOLE") == "1":
|
|
24
|
+
commands.append(["twse-audit"])
|
|
25
|
+
for command in commands:
|
|
26
|
+
file_run = subprocess.run(command + arguments + ["--output", str(output)],
|
|
27
|
+
capture_output=True)
|
|
28
|
+
if file_run.returncode != 1 or file_run.stdout or output.read_bytes() != expected:
|
|
29
|
+
raise SystemExit(f"Golden file check failed: {file_run!r}")
|
|
30
|
+
stdout_run = subprocess.run(command + arguments, capture_output=True)
|
|
31
|
+
if stdout_run.returncode != 1 or stdout_run.stdout != expected:
|
|
32
|
+
raise SystemExit(f"Golden stdout check failed: {stdout_run!r}")
|
|
33
|
+
print("Golden bytes match; exit code 1 for file and stdout.")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
if __name__ == "__main__":
|
|
37
|
+
main()
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Regression tests using only synthetic data and the standard library."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import csv
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
import unittest
|
|
13
|
+
from unittest.mock import patch
|
|
14
|
+
|
|
15
|
+
from twse_audit import __version__
|
|
16
|
+
from twse_audit.cli import write_report
|
|
17
|
+
from twse_audit.core import audit, iso_date
|
|
18
|
+
|
|
19
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
20
|
+
START = "2018-12-21"
|
|
21
|
+
END = "2018-12-23"
|
|
22
|
+
DATA_FIELDS = ("date", "symbol", "open", "high", "low", "close", "volume")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AuditTests(unittest.TestCase):
|
|
26
|
+
def setUp(self):
|
|
27
|
+
self.temporary = tempfile.TemporaryDirectory()
|
|
28
|
+
self.addCleanup(self.temporary.cleanup)
|
|
29
|
+
self.directory = Path(self.temporary.name)
|
|
30
|
+
self.daily = self.directory / "daily.csv"
|
|
31
|
+
self.calendar = self.directory / "calendar.csv"
|
|
32
|
+
self.output = self.directory / "report.json"
|
|
33
|
+
self.write_csv(self.daily, DATA_FIELDS, [
|
|
34
|
+
(START, "0050", "30", "33", "29", "32", "1000"),
|
|
35
|
+
("2018-12-22", "0050", "30", "33", "29", "32", "0"),
|
|
36
|
+
])
|
|
37
|
+
self.write_csv(self.calendar, ("date", "status", "source"), [
|
|
38
|
+
(START, "open", "synthetic"),
|
|
39
|
+
("2018-12-22", "open", "synthetic"),
|
|
40
|
+
(END, "closed", "synthetic"),
|
|
41
|
+
])
|
|
42
|
+
|
|
43
|
+
def write_csv(self, path, fields, rows):
|
|
44
|
+
with path.open("w", encoding="utf-8", newline="") as handle:
|
|
45
|
+
writer = csv.writer(handle, lineterminator="\n")
|
|
46
|
+
writer.writerow(fields)
|
|
47
|
+
writer.writerows(rows)
|
|
48
|
+
|
|
49
|
+
def run_cli(self, *, daily=None, calendar=None, start=START, end=END, output=None):
|
|
50
|
+
command = [
|
|
51
|
+
sys.executable, "-m", "twse_audit",
|
|
52
|
+
"--csv", str(daily or self.daily),
|
|
53
|
+
"--calendar", str(calendar or self.calendar),
|
|
54
|
+
"--start", start, "--end", end,
|
|
55
|
+
]
|
|
56
|
+
if output is not None:
|
|
57
|
+
command.extend(["--output", str(output)])
|
|
58
|
+
environment = os.environ.copy()
|
|
59
|
+
# Exercise the source package from an unrelated working directory.
|
|
60
|
+
environment["PYTHONPATH"] = str(ROOT / "src")
|
|
61
|
+
return subprocess.run(command, cwd=self.directory, env=environment, capture_output=True)
|
|
62
|
+
|
|
63
|
+
def test_example_bytes_file_and_stdout(self):
|
|
64
|
+
expected = (ROOT / "examples/expected-report.json").read_bytes()
|
|
65
|
+
arguments = dict(daily=ROOT / "examples/daily.csv",
|
|
66
|
+
calendar=ROOT / "examples/calendar.csv")
|
|
67
|
+
file_run = self.run_cli(**arguments, output=self.output)
|
|
68
|
+
self.assertEqual(file_run.returncode, 1, file_run.stderr)
|
|
69
|
+
self.assertEqual(file_run.stdout, b"")
|
|
70
|
+
self.assertEqual(file_run.stderr, b"")
|
|
71
|
+
self.assertEqual(self.output.read_bytes(), expected)
|
|
72
|
+
stdout_run = self.run_cli(**arguments)
|
|
73
|
+
self.assertEqual(stdout_run.returncode, 1, stdout_run.stderr)
|
|
74
|
+
self.assertEqual(stdout_run.stdout, expected)
|
|
75
|
+
|
|
76
|
+
def test_valid_leading_zero_saturday_and_output_equality(self):
|
|
77
|
+
stdout_run = self.run_cli()
|
|
78
|
+
self.assertEqual(stdout_run.returncode, 0, stdout_run.stderr)
|
|
79
|
+
report = json.loads(stdout_run.stdout)
|
|
80
|
+
self.assertEqual(report["calendar_days"], {"closed": 1, "open": 2})
|
|
81
|
+
self.assertEqual(report["input_rows_in_range"], 2)
|
|
82
|
+
self.assertEqual(report["issues"], [])
|
|
83
|
+
self.assertEqual(report["backfill"], [])
|
|
84
|
+
file_run = self.run_cli(output=self.output)
|
|
85
|
+
self.assertEqual(file_run.returncode, 0, file_run.stderr)
|
|
86
|
+
self.assertEqual(self.output.read_bytes(), stdout_run.stdout)
|
|
87
|
+
|
|
88
|
+
def test_unknown_missing_and_explicit_are_not_backfill(self):
|
|
89
|
+
self.write_csv(self.calendar, ("date", "status", "source"), [
|
|
90
|
+
(START, "open", "synthetic"),
|
|
91
|
+
("2018-12-22", "unknown", "synthetic"),
|
|
92
|
+
])
|
|
93
|
+
run = self.run_cli()
|
|
94
|
+
self.assertEqual(run.returncode, 1, run.stderr)
|
|
95
|
+
report = json.loads(run.stdout)
|
|
96
|
+
self.assertEqual(report["calendar_days"], {"open": 1, "unknown": 2})
|
|
97
|
+
self.assertEqual(report["issue_counts"], {"calendar_unknown": 2})
|
|
98
|
+
self.assertEqual(report["backfill"], [])
|
|
99
|
+
self.assertEqual([(item["date"], item["source"], item["rows"])
|
|
100
|
+
for item in report["issues"]],
|
|
101
|
+
[("2018-12-22", "synthetic", 1), (END, None, 0)])
|
|
102
|
+
|
|
103
|
+
def test_ohlc_and_nan_volume_invalid_only_days_need_backfill(self):
|
|
104
|
+
self.write_csv(self.daily, DATA_FIELDS, [
|
|
105
|
+
(START, "0050", "30", "31", "29", "32", "1000"),
|
|
106
|
+
("2018-12-22", "0050", "30", "33", "29", "32", "NaN"),
|
|
107
|
+
])
|
|
108
|
+
run = self.run_cli()
|
|
109
|
+
self.assertEqual(run.returncode, 1, run.stderr)
|
|
110
|
+
report = json.loads(run.stdout)
|
|
111
|
+
self.assertEqual(report["issue_counts"], {"invalid_row": 2, "missing_daily_data": 2})
|
|
112
|
+
self.assertEqual([item["detail"] for item in report["issues"][:2]],
|
|
113
|
+
["最低價與最高價未涵蓋開盤價、收盤價", "成交股數須為非負整數"])
|
|
114
|
+
self.assertEqual(report["issues"][0]["symbol"], "0050")
|
|
115
|
+
self.assertEqual([item["date"] for item in report["backfill"]],
|
|
116
|
+
[START, "2018-12-22"])
|
|
117
|
+
self.assertTrue(all(item["reason"] == "開市但沒有可用日線列"
|
|
118
|
+
for item in report["backfill"]))
|
|
119
|
+
|
|
120
|
+
def assert_error_preserves_files(self, **arguments):
|
|
121
|
+
self.output.write_bytes(b"existing report\n")
|
|
122
|
+
before = {path: path.read_bytes()
|
|
123
|
+
for path in (self.daily, self.calendar, self.output)}
|
|
124
|
+
run = self.run_cli(**{"output": self.output, **arguments})
|
|
125
|
+
self.assertEqual(run.returncode, 2, run.stderr)
|
|
126
|
+
self.assertEqual(run.stdout, b"")
|
|
127
|
+
# The message is localized and its bytes follow the console encoding
|
|
128
|
+
# (cp950 on Traditional Chinese Windows), so check it is a handled error.
|
|
129
|
+
self.assertTrue(run.stderr.strip())
|
|
130
|
+
self.assertNotIn(b"Traceback", run.stderr)
|
|
131
|
+
for path, content in before.items():
|
|
132
|
+
self.assertEqual(path.read_bytes(), content)
|
|
133
|
+
self.assertEqual(list(self.directory.glob(".twse_audit_*")), [])
|
|
134
|
+
|
|
135
|
+
def test_missing_daily_column_preserves_report_and_inputs(self):
|
|
136
|
+
self.write_csv(self.daily, ("date", "symbol"), [(START, "0050")])
|
|
137
|
+
self.assert_error_preserves_files()
|
|
138
|
+
|
|
139
|
+
def test_missing_calendar_column_preserves_report_and_inputs(self):
|
|
140
|
+
self.write_csv(self.calendar, ("date", "status"), [(START, "open")])
|
|
141
|
+
self.assert_error_preserves_files()
|
|
142
|
+
|
|
143
|
+
def test_reversed_range_preserves_report_and_inputs(self):
|
|
144
|
+
self.assert_error_preserves_files(start=END, end=START)
|
|
145
|
+
|
|
146
|
+
def test_output_cannot_alias_either_input(self):
|
|
147
|
+
for path in (self.daily, self.calendar,
|
|
148
|
+
self.directory / "subdir" / ".." / "daily.csv"):
|
|
149
|
+
with self.subTest(output=path):
|
|
150
|
+
self.assert_error_preserves_files(output=path)
|
|
151
|
+
|
|
152
|
+
def test_repeat_runs_identical(self):
|
|
153
|
+
first = self.run_cli(output=self.output)
|
|
154
|
+
first_bytes = self.output.read_bytes()
|
|
155
|
+
second = self.run_cli(output=self.output)
|
|
156
|
+
self.assertEqual((first.returncode, second.returncode), (0, 0))
|
|
157
|
+
self.assertEqual(self.output.read_bytes(), first_bytes)
|
|
158
|
+
|
|
159
|
+
def test_core_returns_dict_without_printing_or_writing(self):
|
|
160
|
+
before = {path: path.read_bytes() for path in self.directory.iterdir()}
|
|
161
|
+
with contextlib.redirect_stdout(io.StringIO()) as stdout:
|
|
162
|
+
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
|
163
|
+
report = audit(self.daily, self.calendar, iso_date(START), iso_date(END))
|
|
164
|
+
self.assertIsInstance(report, dict)
|
|
165
|
+
self.assertEqual(stdout.getvalue(), "")
|
|
166
|
+
self.assertEqual(stderr.getvalue(), "")
|
|
167
|
+
self.assertEqual({path: path.read_bytes() for path in self.directory.iterdir()}, before)
|
|
168
|
+
self.assertEqual(__version__, "0.1.0")
|
|
169
|
+
|
|
170
|
+
def test_failed_replace_preserves_existing_report_and_cleans_temporary(self):
|
|
171
|
+
self.output.write_bytes(b"existing report\n")
|
|
172
|
+
with patch("twse_audit.cli.Path.replace", side_effect=OSError("synthetic failure")):
|
|
173
|
+
with self.assertRaises(OSError):
|
|
174
|
+
write_report(self.output, "replacement\n")
|
|
175
|
+
self.assertEqual(self.output.read_bytes(), b"existing report\n")
|
|
176
|
+
self.assertEqual(list(self.directory.glob(".twse_audit_*")), [])
|
|
177
|
+
|
|
178
|
+
def test_settlement_only_with_data_is_unexpected(self):
|
|
179
|
+
self.write_csv(self.calendar, ("date", "status", "source"), [
|
|
180
|
+
(START, "settlement_only", "synthetic"),
|
|
181
|
+
("2018-12-22", "open", "synthetic"),
|
|
182
|
+
(END, "closed", "synthetic"),
|
|
183
|
+
])
|
|
184
|
+
run = self.run_cli()
|
|
185
|
+
self.assertEqual(run.returncode, 1, run.stderr)
|
|
186
|
+
report = json.loads(run.stdout)
|
|
187
|
+
self.assertEqual(report["issue_counts"], {"unexpected_daily_data": 1})
|
|
188
|
+
self.assertEqual(report["issues"][0]["calendar_status"], "settlement_only")
|
|
189
|
+
self.assertEqual(report["backfill"], [])
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
if __name__ == "__main__":
|
|
193
|
+
unittest.main()
|