openbb-akshare 0.3.5__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.
@@ -0,0 +1,142 @@
1
+ # Add these imports at the top
2
+ from datetime import datetime, timedelta
3
+ import os
4
+
5
+ # support logging
6
+ import logging
7
+ from logging.handlers import RotatingFileHandler
8
+
9
+ # Configure logging
10
+ def setup_logger():
11
+ # Create logs directory if it doesn't exist
12
+ log_dir = "logs"
13
+ log_file = os.path.join(log_dir, "openbb_akshare.log")
14
+ os.makedirs(log_dir, exist_ok=True)
15
+
16
+ # Log format
17
+ log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
18
+ formatter = logging.Formatter(log_format)
19
+
20
+ # Log to console
21
+ console_handler = logging.StreamHandler()
22
+ console_handler.setFormatter(formatter)
23
+
24
+ # Log to file (with rotation)
25
+ file_handler = RotatingFileHandler(
26
+ log_file,
27
+ maxBytes=1024 * 1024, # 1MB per file
28
+ backupCount=5, # Keep 5 backups
29
+ )
30
+ file_handler.setFormatter(formatter)
31
+
32
+ # Root logger configuration
33
+ logging.basicConfig(
34
+ level=logging.INFO, # Default level
35
+ handlers=[console_handler, file_handler]
36
+ )
37
+
38
+ def get_working_days(start_date: str, end_date: str) -> int:
39
+ """Calculate number of working days between two dates"""
40
+ start = datetime.strptime(start_date, "%Y%m%d")
41
+ end = datetime.strptime(end_date, "%Y%m%d")
42
+ days = 0
43
+ current = start
44
+
45
+ while current <= end:
46
+ # Skip weekends (5 = Saturday, 6 = Sunday)
47
+ if current.weekday() < 5:
48
+ days += 1
49
+ current += timedelta(days=1)
50
+
51
+ return days
52
+
53
+ def get_symbol_base(symbol: str) -> str:
54
+ """
55
+ Get the base symbol from a stock symbol with market suffix.
56
+ """
57
+ if "." in symbol:
58
+ base, market = symbol.split(".")
59
+ # Handle Hong Kong market special case (HKI -> HK)
60
+ if market == "HKI":
61
+ market = "HK"
62
+ return base
63
+ else:
64
+ # Raise exception if no market suffix is present
65
+ raise ValueError(f"Symbol '{symbol}' must include a market suffix (e.g., .SH, .SZ, .HK)")
66
+
67
+ def normalize_symbol(symbol: str) -> tuple[str, str, str]:
68
+ """
69
+ Normalize a stock symbol by determining its market and returning the standardized format.
70
+
71
+ Args:
72
+ symbol (str): Stock symbol with or without market suffix (e.g., "601006.SH" or "601006")
73
+
74
+ Returns:
75
+ tuple[str, str]: A tuple containing (normalized_symbol, market_suffix)
76
+
77
+ Examples:
78
+ >>> normalize_symbol("601006")
79
+ ("601006", "601006.SH", "SH")
80
+ >>> normalize_symbol("601006.SH")
81
+ ("601006", "601006.SH", "SH")
82
+ >>> normalize_symbol("0700.HK")
83
+ ("0700", "0700.HK", "HK")
84
+ >>> normalize_symbol("00700.HK")
85
+ ("00700", "00700.HK", "HK")
86
+ >>> normalize_symbol("00700")
87
+ ("00700", "00700.HK", "HK")
88
+ """
89
+ # If symbol already contains market suffix
90
+ if "." in symbol:
91
+ base, market = symbol.split(".")
92
+ # Handle Hong Kong market special case (HKI -> HK)
93
+ if market == "HKI":
94
+ market = "HK"
95
+ return base, f"{base}.{market}", market
96
+
97
+ # No market suffix, determine by pattern
98
+ # Shanghai market (starts with 6)
99
+ if symbol.startswith("6") and len(symbol) == 6:
100
+ return symbol, f"{symbol}.SH", "SH"
101
+
102
+ # Beijing market (starts with 43, 83, 87, 88, 92 or 93)
103
+ if (symbol.startswith("4") or symbol.startswith("8") or symbol.startswith("9")) and len(symbol) == 6:
104
+ return symbol, f"{symbol}.BJ", "BJ"
105
+
106
+ # Shenzhen market (starts with 000 or 300)
107
+ # TODO: check "00" at the moment, should be "000", "001", "002", "300"
108
+ if len(symbol) == 6 and (symbol.startswith("00") or symbol.startswith("300")):
109
+ return symbol, f"{symbol}.SZ", "SZ"
110
+
111
+ # Hong Kong market - 4 digits or 5 digits starting with 0
112
+ if len(symbol) == 4 and symbol.isdigit():
113
+ return symbol, f"{symbol}.HK", "HK"
114
+
115
+ # Check for 5-digit Hong Kong symbols that start with 0
116
+ if len(symbol) == 5 and symbol.isdigit() and symbol.startswith("0"):
117
+ return symbol, f"{symbol}.HK", "HK"
118
+
119
+ # Singapore market (typically ends with SI)
120
+ if symbol.endswith("SI"):
121
+ return symbol, f"{symbol}.SI", "SI"
122
+
123
+ # US market (default case - assume any remaining symbols are US stocks)
124
+ return symbol, f"{symbol}.US", "US"
125
+
126
+ def normalize_date(date: str) -> str:
127
+ """Normalize date format from %Y-%m-%d to %Y%m%d if needed."""
128
+ try:
129
+ # Try to parse the date with the hyphen format
130
+ date_obj = datetime.strptime(date, "%Y-%m-%d")
131
+ # If successful, convert to the desired format
132
+ return date_obj.strftime("%Y%m%d")
133
+ except ValueError:
134
+ # If parsing fails, return the original string
135
+ return date
136
+
137
+ # 示例调用
138
+ if __name__ == "__main__":
139
+ start_date = "20230101"
140
+ end_date = "20230110"
141
+ working_days = get_working_days(start_date, end_date)
142
+ print(f"从 {start_date} 到 {end_date} 的工作日数量: {working_days}")
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.3
2
+ Name: openbb-akshare
3
+ Version: 0.3.5
4
+ Summary: AKShare extension for OpenBB
5
+ License: AGPL-3.0-only
6
+ Author: Roger Ye
7
+ Author-email: shugaoye@yahoo.com
8
+ Requires-Python: >=3.9,<3.13
9
+ Classifier: License :: OSI Approved :: GNU Affero General Public License v3
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Dist: akshare (==1.16.98)
16
+ Requires-Dist: openbb-core (>=1.4.7,<2.0.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # How to Use AKShare as a Data Source for OpenBB
20
+
21
+ **OpenBB**, as an open-source financial data platform, is dedicated to providing free and transparent financial data interfaces for investors, analysts, and developers. For a detailed introduction to OpenBB and its usage, please refer to [Introduction to OpenBB and How to Use It to Aid Financial Data Analysis of China A-share and Hong Kong Stocks](https://medium.com/@shugaoye/introduction-to-openbb-and-how-to-use-it-to-aid-financial-data-analysis-of-china-a-share-and-hong-f4bbe480399a).
22
+
23
+ Although OpenBB supports multi-source data interfaces, the acquisition of financial data in China (including Hong Kong) mainly relies on Yahoo Finance. As a free basic data source, it can meet basic needs, but its coverage depth for the Chinese and Hong Kong markets is still insufficient. More importantly, mainland Chinese users need to use a VPN to access this service, creating significant usage barriers.
24
+
25
+ To enhance service capabilities in Greater China, OpenBB urgently needs to improve the implementation of localized financial data sources. The mainstream paid solutions include Wind, Eastmoney Choice, and 同花顺 iFind (mainly for institutional clients), while the free solutions focus on the open-source tool AKShare as the core solution. By integrating data interfaces from platforms such as Eastmoney, 同花顺, Tencent, Sina, and 雪球, AKShare has become one of the most comprehensive, up-to-date, and developer-friendly financial data aggregation libraries in the domestic Python ecosystem.
26
+
27
+ The `openbb_akshare` project, as a data source extension for OpenBB, enables seamless integration of AKShare data into the OpenBB platform. Below is a detailed usage guide:
28
+
29
+ ## 💻 Environment Setup and Installation Process
30
+
31
+ As developers, we primarily interact with the platform through the OpenBB Platform CLI. To integrate the AKShare data source, follow these steps to configure the development environment:
32
+
33
+ 1. **Create a Python Virtual Environment**
34
+
35
+ You can use `venv`, `uv`, or `poetry` to create a virtual environment. Here, we use venv (built into Python):
36
+
37
+ ```bash
38
+ # Create a virtual environment
39
+ python3 -m venv .venv
40
+
41
+ # Activate the virtual environment (Linux/Mac)
42
+ source .venv/bin/activate
43
+
44
+ # For Windows
45
+ .venv\Scripts\activate
46
+ ```
47
+
48
+ 2. **Install OpenBB Platform CLI**
49
+
50
+ Install the core OpenBB CLI via pip. Users in mainland China can configure a mirror for faster installation:
51
+
52
+ ```bash
53
+ # (Optional) Set a domestic mirror for pip
54
+ # For Linux/Mac
55
+ export PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple
56
+
57
+ # Install OpenBB CLI
58
+ pip install openbb-cli
59
+ ```
60
+
61
+ 3. **Install openbb_akshare**
62
+
63
+ Next, install the `openbb_akshare` extenstion to use the AKShare data source:
64
+
65
+ ```bash
66
+ # Install the AKShare data source extension
67
+ pip install openbb_akshare
68
+
69
+ # Rebuild OpenBB resources to activate the plugin
70
+ python -c "import openbb; openbb.build()"
71
+ ```
72
+
73
+ ## 🚀 Using the AKShare Data Source
74
+
75
+ ### Case 1: Query A-Share Company News (Vanke as an Example)
76
+
77
+ **Jupyter Notebook**:
78
+
79
+ ```Python
80
+ from openbb import obb
81
+ messages = obb.news.company("000002", provider="akshare")
82
+ for result in messages.results:
83
+ print(f"{result.title}")
84
+ ```
85
+
86
+ Output:
87
+
88
+ ```plaintext
89
+ 开源证券发布万科A研报,公司信息更新报告:销售均价有所提升,股东持续借款提供支持
90
+ 万科A出售2086万股库存股,金额1.36亿元
91
+ 万科A:已完成所有A股库存股出售 所得资金4.79亿元
92
+ ...
93
+ ```
94
+
95
+ **Using OpenBB CLI**:
96
+
97
+ ```bash
98
+ openbb
99
+ 2025 Jun 26, 03:11 (🦋) /news/ $ company --symbol 000002 --provider akshare
100
+ ```
101
+
102
+ After entering the command, the results will be displayed in a WebView, as shown below:
103
+
104
+ ![openbb04](docs/images/openbb04.png)
105
+
106
+ ### Case 2: Obtain Historical Stock Prices of Hong Kong Stocks (Hong Kong Telecom as an Example)
107
+
108
+ **Using OpenBB CLI**:
109
+
110
+ ```
111
+ 2025 Jun 26, 03:28 (🦋) /equity/price/ $ historical --symbol 06823 --provider akshare
112
+ ```
113
+
114
+ Results in WebView:![openbb05](docs/images/openbb05.png)
115
+
116
+ **Jupyter Notebook**:
117
+
118
+ ```Python
119
+ from openbb import obb
120
+ prices = obb.equity.price.historical(symbol='06823', start_date="2025-06-01", end_date="2025-06-10", provider="akshare")
121
+ prices.results[0].date, prices.results[0].open, prices.results[0].close, prices.results[0].high, prices.results[0].low, prices.results[0].volume
122
+ ```
123
+
124
+ Output:
125
+
126
+ ```
127
+ (datetime.date(2025, 6, 2), 11.28, 11.3, 11.3, 11.14, 10308375)
128
+ ```
129
+
130
+ ## 🌟 openbb_akshare Project Ecosystem
131
+
132
+ The `openbb_akshare` project is currently in an active development phase, and contributions from the open-source community are welcome:
133
+
134
+ ### Code Repositories
135
+
136
+ - **GitHub**: https://github.com/finanalyzer/openbb_akshare
137
+
138
+ - **GitCode (Domestic Mirror)**: https://gitcode.com/finanalyzer/openbb_akshare
139
+
140
+ ### Ways to Contribute
141
+
142
+ 1. Submit Issues to report data needs or bugs.
143
+
144
+ 2. Contribute PRs to optimize data source interfaces.
145
+
146
+ 3. Improve documentation to help more users.
147
+
148
+ Through the integration of AKShare and OpenBB, users in China can more conveniently access real-time and historical data for markets such as A-Shares and Hong Kong Stocks, providing strong data support for quantitative analysis and investment research.
@@ -0,0 +1,18 @@
1
+ openbb_akshare/__init__.py,sha256=nnHZUe51A_IJM5rU52f98zRYGIy_4-Rpt_Kvc_xtXkI,1309
2
+ openbb_akshare/models/__init__.py,sha256=m3gMD7E0l2sSs6hpLz247F7SmbdMTxNo8L91P2rq6vA,31
3
+ openbb_akshare/models/available_indices.py,sha256=fMQU8OOLaVZ3FEb3_jnZTZRP46iopSL58XOw-RwEeIw,2209
4
+ openbb_akshare/models/company_news.py,sha256=N37HR9pdI9ep9FM94xWmSxsqhNYHJz3eKKcR5t2T_EQ,3353
5
+ openbb_akshare/models/equity_historical.py,sha256=FikSpUpKlj0ppwLxaIm9ENF0NlS2XqysagKou0N2gQ0,3763
6
+ openbb_akshare/models/equity_quote.py,sha256=hiN2TD7Dys0yB62KsIuOWvrh1rdjjJovWY2P5ctR8Ig,4975
7
+ openbb_akshare/models/historical_dividends.py,sha256=7fQXyi7QwOPoUPvAf9Kbl0Y6frrhTzXHpaVtu5Xv8xc,3621
8
+ openbb_akshare/openbb.py,sha256=1brue1rid_-X-rBcDlEBu2IGrCuMYt_aJxEjXFxWgiY,1421
9
+ openbb_akshare/router.py,sha256=XS2FnACxp0RcL72mBScgUn6i0VrOFkZ94dxMgGkyheU,1512
10
+ openbb_akshare/utils/__init__.py,sha256=QbmiTSfL3BhE5-6KzGdMRWP2-G_laMNNZJWTkDMcoUU,30
11
+ openbb_akshare/utils/futures.csv,sha256=xSZ2tybp__tNIRH__7O27SYepPC3hfGUTYPtVoIxQts,8563
12
+ openbb_akshare/utils/helpers.py,sha256=er5RHe9nMgZIApb4RPtooW_IRuSQ80NE9gdIsoYaz10,8263
13
+ openbb_akshare/utils/references.py,sha256=okVRuo5B4xMrI4Xh0jrX_ljHzxiUQgXlVWkUrLk4b_A,49061
14
+ openbb_akshare/utils/tools.py,sha256=6RLoC5QQpBPBgZQpE7uqs7PYoT_mb1yrY6xP56xug3s,5041
15
+ openbb_akshare-0.3.5.dist-info/entry_points.txt,sha256=rFeXrX0kT9a8JxVyOUEXBAqhe8IyTXa4QB-YHlLkrYk,137
16
+ openbb_akshare-0.3.5.dist-info/METADATA,sha256=8jAd1AK9HkAq8KYFIofS6fkS0_XlyoL_SfqxAJ_JS7g,5940
17
+ openbb_akshare-0.3.5.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
18
+ openbb_akshare-0.3.5.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 2.1.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,6 @@
1
+ [openbb_core_extension]
2
+ openbb_akshare=openbb_akshare.router:router
3
+
4
+ [openbb_provider_extension]
5
+ openbb_akshare=openbb_akshare:provider
6
+