oaio-ai 1.0.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.
oaio_ai-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-2026 OAIO
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.
oaio_ai-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: oaio-ai
3
+ Version: 1.0.0
4
+ Summary: Python SDK for OAIO — free, keyless 0-100 market sentiment scores for stocks and crypto.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://oaio.io/developers
7
+ Project-URL: Repository, https://github.com/Kompweb/OAIO
8
+ Keywords: sentiment,stocks,crypto,fear-and-greed,market,finance
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Office/Business :: Financial :: Investment
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # oaio — OAIO Python SDK
17
+
18
+ Free, keyless 0–100 market sentiment scores for stocks and crypto, from
19
+ [oaio.io](https://oaio.io). One score per asset (Positive 60+, Neutral
20
+ 40–59, Negative below 40), plus a per-market index for stocks and for
21
+ crypto.
22
+
23
+ Stocks and crypto are **two separate tracks and are never mixed** —
24
+ every call names its track with `kind="stock"` or `kind="crypto"`.
25
+
26
+ Zero dependencies — Python standard library only. Python ≥ 3.9.
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ pip install oaio-ai
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ```python
37
+ from oaio import OAIO
38
+
39
+ oaio = OAIO() # optional: OAIO(base_url="https://oaio.io")
40
+ ```
41
+
42
+ Module-level functions bound to a default client are exported too:
43
+ `sentiment`, `market_sentiment`, `sentiment_history`, `market_history`,
44
+ `tape`.
45
+
46
+ ### `sentiment(symbol, kind=None)` — one asset's live reading
47
+
48
+ ```python
49
+ btc = oaio.sentiment("BTC", kind="crypto")
50
+ print(btc["score"], btc["label"], btc["price"]) # 21 Negative 59632.97
51
+ ```
52
+
53
+ `kind` is optional: omit it (or pass `"any"`) to try crypto first, then
54
+ stock.
55
+
56
+ ### `market_sentiment(kind)` — a whole market's index
57
+
58
+ ```python
59
+ stocks = oaio.market_sentiment("stock")
60
+ print(stocks["score"], stocks["label"]) # 51 Neutral
61
+ ```
62
+
63
+ ### `sentiment_history(symbol, kind)` — 90 days of daily scores
64
+
65
+ ```python
66
+ hist = oaio.sentiment_history("ETH", "crypto")
67
+ print(hist["days"], hist["points"][0]) # 90 {'day': ..., 'score': ..., ...}
68
+ ```
69
+
70
+ Each point says whether it was recorded live that day (`source:
71
+ "live"`) or recalculated with today's method (`"recalculated"`).
72
+
73
+ ### `market_history(kind)` — 90 days of a market index
74
+
75
+ ```python
76
+ crypto = oaio.market_history("crypto")
77
+ ```
78
+
79
+ ### `tape(items)` — up to 12 assets in one call
80
+
81
+ ```python
82
+ t = oaio.tape([
83
+ {"symbol": "BTC", "kind": "crypto"},
84
+ {"symbol": "AAPL", "kind": "stock"},
85
+ ])
86
+ for item in t["items"]:
87
+ reading = item["reading"] or {}
88
+ print(item["kind"], item["symbol"], reading.get("score"))
89
+ ```
90
+
91
+ ## Errors
92
+
93
+ Non-2xx responses raise `OAIOError` carrying the HTTP `status` and the
94
+ API's own error message:
95
+
96
+ ```python
97
+ from oaio import OAIOError
98
+
99
+ try:
100
+ oaio.sentiment("BTC", "bonds")
101
+ except OAIOError as err:
102
+ print(err.status, err.message)
103
+ ```
104
+
105
+ `status` is `0` for a client-side validation error raised before any
106
+ request was made.
107
+
108
+ ## Rate limit
109
+
110
+ The API is rate-limited to **60 requests per minute per IP**. A `429`
111
+ response raises an `OAIOError` like any other error.
112
+
113
+ ## Also available
114
+
115
+ - The same five reads as an MCP server for AI agents:
116
+ https://oaio.io/mcp (listed in the official MCP Registry as
117
+ `io.github.Kompweb/oaio`)
118
+ - Embeddable gauge images: https://oaio.io/gauge/stocks.png and
119
+ https://oaio.io/gauge/crypto.png
120
+ - Full API docs: https://oaio.io/developers
121
+
122
+ Educational only — not financial advice.
@@ -0,0 +1,107 @@
1
+ # oaio — OAIO Python SDK
2
+
3
+ Free, keyless 0–100 market sentiment scores for stocks and crypto, from
4
+ [oaio.io](https://oaio.io). One score per asset (Positive 60+, Neutral
5
+ 40–59, Negative below 40), plus a per-market index for stocks and for
6
+ crypto.
7
+
8
+ Stocks and crypto are **two separate tracks and are never mixed** —
9
+ every call names its track with `kind="stock"` or `kind="crypto"`.
10
+
11
+ Zero dependencies — Python standard library only. Python ≥ 3.9.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ pip install oaio-ai
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```python
22
+ from oaio import OAIO
23
+
24
+ oaio = OAIO() # optional: OAIO(base_url="https://oaio.io")
25
+ ```
26
+
27
+ Module-level functions bound to a default client are exported too:
28
+ `sentiment`, `market_sentiment`, `sentiment_history`, `market_history`,
29
+ `tape`.
30
+
31
+ ### `sentiment(symbol, kind=None)` — one asset's live reading
32
+
33
+ ```python
34
+ btc = oaio.sentiment("BTC", kind="crypto")
35
+ print(btc["score"], btc["label"], btc["price"]) # 21 Negative 59632.97
36
+ ```
37
+
38
+ `kind` is optional: omit it (or pass `"any"`) to try crypto first, then
39
+ stock.
40
+
41
+ ### `market_sentiment(kind)` — a whole market's index
42
+
43
+ ```python
44
+ stocks = oaio.market_sentiment("stock")
45
+ print(stocks["score"], stocks["label"]) # 51 Neutral
46
+ ```
47
+
48
+ ### `sentiment_history(symbol, kind)` — 90 days of daily scores
49
+
50
+ ```python
51
+ hist = oaio.sentiment_history("ETH", "crypto")
52
+ print(hist["days"], hist["points"][0]) # 90 {'day': ..., 'score': ..., ...}
53
+ ```
54
+
55
+ Each point says whether it was recorded live that day (`source:
56
+ "live"`) or recalculated with today's method (`"recalculated"`).
57
+
58
+ ### `market_history(kind)` — 90 days of a market index
59
+
60
+ ```python
61
+ crypto = oaio.market_history("crypto")
62
+ ```
63
+
64
+ ### `tape(items)` — up to 12 assets in one call
65
+
66
+ ```python
67
+ t = oaio.tape([
68
+ {"symbol": "BTC", "kind": "crypto"},
69
+ {"symbol": "AAPL", "kind": "stock"},
70
+ ])
71
+ for item in t["items"]:
72
+ reading = item["reading"] or {}
73
+ print(item["kind"], item["symbol"], reading.get("score"))
74
+ ```
75
+
76
+ ## Errors
77
+
78
+ Non-2xx responses raise `OAIOError` carrying the HTTP `status` and the
79
+ API's own error message:
80
+
81
+ ```python
82
+ from oaio import OAIOError
83
+
84
+ try:
85
+ oaio.sentiment("BTC", "bonds")
86
+ except OAIOError as err:
87
+ print(err.status, err.message)
88
+ ```
89
+
90
+ `status` is `0` for a client-side validation error raised before any
91
+ request was made.
92
+
93
+ ## Rate limit
94
+
95
+ The API is rate-limited to **60 requests per minute per IP**. A `429`
96
+ response raises an `OAIOError` like any other error.
97
+
98
+ ## Also available
99
+
100
+ - The same five reads as an MCP server for AI agents:
101
+ https://oaio.io/mcp (listed in the official MCP Registry as
102
+ `io.github.Kompweb/oaio`)
103
+ - Embeddable gauge images: https://oaio.io/gauge/stocks.png and
104
+ https://oaio.io/gauge/crypto.png
105
+ - Full API docs: https://oaio.io/developers
106
+
107
+ Educational only — not financial advice.
@@ -0,0 +1,24 @@
1
+ """OAIO — Python SDK for OAIO's keyless market sentiment API."""
2
+
3
+ from .client import (
4
+ OAIO,
5
+ OAIOError,
6
+ market_history,
7
+ market_sentiment,
8
+ sentiment,
9
+ sentiment_history,
10
+ tape,
11
+ )
12
+
13
+ __version__ = "1.0.0"
14
+
15
+ __all__ = [
16
+ "OAIO",
17
+ "OAIOError",
18
+ "sentiment",
19
+ "market_sentiment",
20
+ "sentiment_history",
21
+ "market_history",
22
+ "tape",
23
+ "__version__",
24
+ ]
@@ -0,0 +1,185 @@
1
+ """OAIO — Python SDK.
2
+
3
+ A thin, zero-dependency client (standard library only) for OAIO's
4
+ keyless public API — the same endpoints the website and the OAIO MCP
5
+ server use, so a reading from this SDK can never disagree with
6
+ oaio.io.
7
+
8
+ Parameter handling mirrors the OAIO MCP tools exactly: symbols are
9
+ trimmed and uppercased, kinds are lowercased, sentiment's kind is
10
+ optional ('any' tries crypto first, then stock), history for a whole
11
+ market uses the literal symbol MARKET, and tape items are encoded as
12
+ kind:SYMBOL pairs, comma-joined, max 12.
13
+ """
14
+
15
+ import json
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+
20
+ __all__ = ["OAIO", "OAIOError"]
21
+
22
+ DEFAULT_BASE_URL = "https://oaio.io"
23
+ _KINDS = ("crypto", "stock")
24
+ _USER_AGENT = "oaio-python/1.0.0"
25
+
26
+
27
+ class OAIOError(Exception):
28
+ """An OAIO API error, or a client-side validation error.
29
+
30
+ ``status`` is the HTTP status for an API error, or 0 for a
31
+ validation error raised before any request was made. The message
32
+ is the API's own error message when it sent one.
33
+ """
34
+
35
+ def __init__(self, message, status):
36
+ super().__init__(message)
37
+ self.message = message
38
+ self.status = status
39
+
40
+
41
+ def _symbol_of(value):
42
+ return value.strip().upper() if isinstance(value, str) else ""
43
+
44
+
45
+ def _kind_of(value):
46
+ return value.lower() if isinstance(value, str) else ""
47
+
48
+
49
+ class OAIO:
50
+ """Client for the OAIO API.
51
+
52
+ ``base_url`` overrides https://oaio.io. ``opener`` overrides the
53
+ urlopen callable (used by tests); it must accept a
54
+ urllib.request.Request and return a response with .status and
55
+ .read(), raising urllib.error.HTTPError for non-2xx like urlopen.
56
+ """
57
+
58
+ def __init__(self, base_url=DEFAULT_BASE_URL, opener=None):
59
+ self.base_url = str(base_url or DEFAULT_BASE_URL).rstrip("/")
60
+ self._opener = opener if opener is not None else urllib.request.urlopen
61
+
62
+ def _get(self, path):
63
+ request = urllib.request.Request(
64
+ self.base_url + path,
65
+ headers={"Accept": "application/json", "User-Agent": _USER_AGENT},
66
+ )
67
+ try:
68
+ response = self._opener(request)
69
+ except urllib.error.HTTPError as err:
70
+ response = err
71
+ status = getattr(response, "status", None) or response.getcode()
72
+ raw = response.read()
73
+ text = raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw)
74
+ data = None
75
+ if text:
76
+ try:
77
+ data = json.loads(text)
78
+ except ValueError:
79
+ data = None
80
+ if status < 200 or status >= 300:
81
+ if isinstance(data, dict) and isinstance(data.get("error"), str):
82
+ message = data["error"]
83
+ else:
84
+ message = "OAIO API error (HTTP %d)" % status
85
+ raise OAIOError(message, status)
86
+ return data if data is not None else text
87
+
88
+ def sentiment(self, symbol, kind=None):
89
+ """Live sentiment reading for one stock or crypto asset.
90
+
91
+ ``kind`` is optional: omit it (or pass "any") to try crypto
92
+ first, then stock.
93
+ """
94
+ sym = _symbol_of(symbol)
95
+ if not sym:
96
+ raise OAIOError("Missing symbol.", 0)
97
+ k = _kind_of(kind)
98
+ if k and k not in ("crypto", "stock", "any"):
99
+ raise OAIOError("Invalid kind — use crypto, stock, or any.", 0)
100
+ params = {"symbol": sym}
101
+ if k:
102
+ params["kind"] = k
103
+ return self._get("/api/v1/sentiment?" + urllib.parse.urlencode(params))
104
+
105
+ def market_sentiment(self, kind):
106
+ """The OAIO sentiment index for one whole market track."""
107
+ k = _kind_of(kind)
108
+ if k not in _KINDS:
109
+ raise OAIOError("kind must be crypto or stock.", 0)
110
+ return self._get("/api/market?kind=" + k)
111
+
112
+ def sentiment_history(self, symbol, kind):
113
+ """One asset's daily sentiment scores over the last 90 days."""
114
+ k = _kind_of(kind)
115
+ if k not in _KINDS:
116
+ raise OAIOError("kind must be crypto or stock.", 0)
117
+ sym = _symbol_of(symbol)
118
+ if not sym:
119
+ raise OAIOError("Missing symbol.", 0)
120
+ return self._get(
121
+ "/api/history?kind=%s&symbol=%s"
122
+ % (k, urllib.parse.quote(sym, safe=""))
123
+ )
124
+
125
+ def market_history(self, kind):
126
+ """A market index's daily values over the last 90 days."""
127
+ k = _kind_of(kind)
128
+ if k not in _KINDS:
129
+ raise OAIOError("kind must be crypto or stock.", 0)
130
+ return self._get(
131
+ "/api/history?kind=%s&symbol=%s"
132
+ % (k, urllib.parse.quote("MARKET", safe=""))
133
+ )
134
+
135
+ def tape(self, items):
136
+ """Live readings for up to 12 assets in one call.
137
+
138
+ ``items`` is a list of {"symbol": ..., "kind": ...} dicts.
139
+ The first 12 items are taken, then invalid ones are dropped —
140
+ the same order the MCP tool applies.
141
+ """
142
+ if not isinstance(items, (list, tuple)):
143
+ items = []
144
+ parts = []
145
+ for item in items[:12]:
146
+ if isinstance(item, dict):
147
+ sym = _symbol_of(item.get("symbol"))
148
+ k = _kind_of(item.get("kind"))
149
+ else:
150
+ sym, k = "", ""
151
+ if sym and k in _KINDS:
152
+ parts.append("%s:%s" % (k, sym))
153
+ if not parts:
154
+ raise OAIOError("items must name at least one {symbol, kind} pair.", 0)
155
+ return self._get(
156
+ "/api/v1/tape?items=" + urllib.parse.quote(",".join(parts), safe="")
157
+ )
158
+
159
+
160
+ _default_client = OAIO()
161
+
162
+
163
+ def sentiment(symbol, kind=None):
164
+ """Module-level shortcut bound to a default client."""
165
+ return _default_client.sentiment(symbol, kind)
166
+
167
+
168
+ def market_sentiment(kind):
169
+ """Module-level shortcut bound to a default client."""
170
+ return _default_client.market_sentiment(kind)
171
+
172
+
173
+ def sentiment_history(symbol, kind):
174
+ """Module-level shortcut bound to a default client."""
175
+ return _default_client.sentiment_history(symbol, kind)
176
+
177
+
178
+ def market_history(kind):
179
+ """Module-level shortcut bound to a default client."""
180
+ return _default_client.market_history(kind)
181
+
182
+
183
+ def tape(items):
184
+ """Module-level shortcut bound to a default client."""
185
+ return _default_client.tape(items)
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: oaio-ai
3
+ Version: 1.0.0
4
+ Summary: Python SDK for OAIO — free, keyless 0-100 market sentiment scores for stocks and crypto.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://oaio.io/developers
7
+ Project-URL: Repository, https://github.com/Kompweb/OAIO
8
+ Keywords: sentiment,stocks,crypto,fear-and-greed,market,finance
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Office/Business :: Financial :: Investment
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # oaio — OAIO Python SDK
17
+
18
+ Free, keyless 0–100 market sentiment scores for stocks and crypto, from
19
+ [oaio.io](https://oaio.io). One score per asset (Positive 60+, Neutral
20
+ 40–59, Negative below 40), plus a per-market index for stocks and for
21
+ crypto.
22
+
23
+ Stocks and crypto are **two separate tracks and are never mixed** —
24
+ every call names its track with `kind="stock"` or `kind="crypto"`.
25
+
26
+ Zero dependencies — Python standard library only. Python ≥ 3.9.
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ pip install oaio-ai
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ```python
37
+ from oaio import OAIO
38
+
39
+ oaio = OAIO() # optional: OAIO(base_url="https://oaio.io")
40
+ ```
41
+
42
+ Module-level functions bound to a default client are exported too:
43
+ `sentiment`, `market_sentiment`, `sentiment_history`, `market_history`,
44
+ `tape`.
45
+
46
+ ### `sentiment(symbol, kind=None)` — one asset's live reading
47
+
48
+ ```python
49
+ btc = oaio.sentiment("BTC", kind="crypto")
50
+ print(btc["score"], btc["label"], btc["price"]) # 21 Negative 59632.97
51
+ ```
52
+
53
+ `kind` is optional: omit it (or pass `"any"`) to try crypto first, then
54
+ stock.
55
+
56
+ ### `market_sentiment(kind)` — a whole market's index
57
+
58
+ ```python
59
+ stocks = oaio.market_sentiment("stock")
60
+ print(stocks["score"], stocks["label"]) # 51 Neutral
61
+ ```
62
+
63
+ ### `sentiment_history(symbol, kind)` — 90 days of daily scores
64
+
65
+ ```python
66
+ hist = oaio.sentiment_history("ETH", "crypto")
67
+ print(hist["days"], hist["points"][0]) # 90 {'day': ..., 'score': ..., ...}
68
+ ```
69
+
70
+ Each point says whether it was recorded live that day (`source:
71
+ "live"`) or recalculated with today's method (`"recalculated"`).
72
+
73
+ ### `market_history(kind)` — 90 days of a market index
74
+
75
+ ```python
76
+ crypto = oaio.market_history("crypto")
77
+ ```
78
+
79
+ ### `tape(items)` — up to 12 assets in one call
80
+
81
+ ```python
82
+ t = oaio.tape([
83
+ {"symbol": "BTC", "kind": "crypto"},
84
+ {"symbol": "AAPL", "kind": "stock"},
85
+ ])
86
+ for item in t["items"]:
87
+ reading = item["reading"] or {}
88
+ print(item["kind"], item["symbol"], reading.get("score"))
89
+ ```
90
+
91
+ ## Errors
92
+
93
+ Non-2xx responses raise `OAIOError` carrying the HTTP `status` and the
94
+ API's own error message:
95
+
96
+ ```python
97
+ from oaio import OAIOError
98
+
99
+ try:
100
+ oaio.sentiment("BTC", "bonds")
101
+ except OAIOError as err:
102
+ print(err.status, err.message)
103
+ ```
104
+
105
+ `status` is `0` for a client-side validation error raised before any
106
+ request was made.
107
+
108
+ ## Rate limit
109
+
110
+ The API is rate-limited to **60 requests per minute per IP**. A `429`
111
+ response raises an `OAIOError` like any other error.
112
+
113
+ ## Also available
114
+
115
+ - The same five reads as an MCP server for AI agents:
116
+ https://oaio.io/mcp (listed in the official MCP Registry as
117
+ `io.github.Kompweb/oaio`)
118
+ - Embeddable gauge images: https://oaio.io/gauge/stocks.png and
119
+ https://oaio.io/gauge/crypto.png
120
+ - Full API docs: https://oaio.io/developers
121
+
122
+ Educational only — not financial advice.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ oaio/__init__.py
5
+ oaio/client.py
6
+ oaio_ai.egg-info/PKG-INFO
7
+ oaio_ai.egg-info/SOURCES.txt
8
+ oaio_ai.egg-info/dependency_links.txt
9
+ oaio_ai.egg-info/top_level.txt
10
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ oaio
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "oaio-ai"
7
+ version = "1.0.0"
8
+ description = "Python SDK for OAIO — free, keyless 0-100 market sentiment scores for stocks and crypto."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ keywords = ["sentiment", "stocks", "crypto", "fear-and-greed", "market", "finance"]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Office/Business :: Financial :: Investment",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://oaio.io/developers"
20
+ Repository = "https://github.com/Kompweb/OAIO"
21
+
22
+ [tool.setuptools]
23
+ packages = ["oaio"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,207 @@
1
+ """OAIO Python SDK tests — unittest, urllib mocked via the opener."""
2
+
3
+ import json
4
+ import os
5
+ import sys
6
+ import unittest
7
+ import urllib.error
8
+ import urllib.parse
9
+
10
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
11
+
12
+ from oaio import OAIO, OAIOError # noqa: E402
13
+
14
+
15
+ class FakeResponse:
16
+ def __init__(self, status, body):
17
+ self.status = status
18
+ self._body = body.encode("utf-8") if isinstance(body, str) else body
19
+
20
+ def read(self):
21
+ return self._body
22
+
23
+ def getcode(self):
24
+ return self.status
25
+
26
+
27
+ def make_client(status=200, body=None):
28
+ if body is None:
29
+ body = {"ok": True}
30
+ calls = []
31
+
32
+ def opener(request):
33
+ calls.append(request.full_url)
34
+ text = body if isinstance(body, str) else json.dumps(body)
35
+ if status < 200 or status >= 300:
36
+ raise _http_error(request, status, text)
37
+ return FakeResponse(status, text)
38
+
39
+ return OAIO(opener=opener), calls
40
+
41
+
42
+ def _http_error(request, status, text):
43
+ import io
44
+
45
+ return urllib.error.HTTPError(
46
+ request.full_url, status, "error", {}, io.BytesIO(text.encode("utf-8"))
47
+ )
48
+
49
+
50
+ class SentimentTests(unittest.TestCase):
51
+ def test_symbol_uppercased_kind_omitted(self):
52
+ client, calls = make_client(200, {"symbol": "BTC", "score": 21})
53
+ data = client.sentiment("btc")
54
+ self.assertEqual(calls[0], "https://oaio.io/api/v1/sentiment?symbol=BTC")
55
+ self.assertEqual(data["score"], 21)
56
+
57
+ def test_symbol_trimmed_kind_lowercased(self):
58
+ client, calls = make_client()
59
+ client.sentiment(" aapl ", "Stock")
60
+ self.assertEqual(
61
+ calls[0], "https://oaio.io/api/v1/sentiment?symbol=AAPL&kind=stock"
62
+ )
63
+
64
+ def test_kind_any_passed_through(self):
65
+ client, calls = make_client()
66
+ client.sentiment("BTC", "any")
67
+ self.assertEqual(
68
+ calls[0], "https://oaio.io/api/v1/sentiment?symbol=BTC&kind=any"
69
+ )
70
+
71
+ def test_missing_symbol(self):
72
+ client, calls = make_client()
73
+ with self.assertRaises(OAIOError) as ctx:
74
+ client.sentiment(" ")
75
+ self.assertEqual(ctx.exception.message, "Missing symbol.")
76
+ self.assertEqual(ctx.exception.status, 0)
77
+ self.assertEqual(calls, [])
78
+
79
+ def test_invalid_kind(self):
80
+ client, calls = make_client()
81
+ with self.assertRaises(OAIOError) as ctx:
82
+ client.sentiment("BTC", "bonds")
83
+ self.assertEqual(
84
+ ctx.exception.message, "Invalid kind — use crypto, stock, or any."
85
+ )
86
+ self.assertEqual(calls, [])
87
+
88
+
89
+ class MarketTests(unittest.TestCase):
90
+ def test_market_sentiment_url(self):
91
+ client, calls = make_client()
92
+ client.market_sentiment("Crypto")
93
+ self.assertEqual(calls[0], "https://oaio.io/api/market?kind=crypto")
94
+
95
+ def test_market_sentiment_rejects_any_and_missing(self):
96
+ client, calls = make_client()
97
+ for bad in ("any", None, ""):
98
+ with self.assertRaises(OAIOError) as ctx:
99
+ client.market_sentiment(bad)
100
+ self.assertEqual(ctx.exception.message, "kind must be crypto or stock.")
101
+ self.assertEqual(calls, [])
102
+
103
+ def test_market_history_uses_market_symbol(self):
104
+ client, calls = make_client()
105
+ client.market_history("stock")
106
+ self.assertEqual(
107
+ calls[0], "https://oaio.io/api/history?kind=stock&symbol=MARKET"
108
+ )
109
+
110
+
111
+ class HistoryTests(unittest.TestCase):
112
+ def test_sentiment_history_url(self):
113
+ client, calls = make_client()
114
+ client.sentiment_history("eth", "crypto")
115
+ self.assertEqual(
116
+ calls[0], "https://oaio.io/api/history?kind=crypto&symbol=ETH"
117
+ )
118
+
119
+ def test_kind_validated_before_symbol(self):
120
+ client, _ = make_client()
121
+ with self.assertRaisesRegex(OAIOError, r"kind must be crypto or stock\."):
122
+ client.sentiment_history("", "bonds")
123
+ with self.assertRaisesRegex(OAIOError, r"Missing symbol\."):
124
+ client.sentiment_history("", "stock")
125
+
126
+
127
+ class TapeTests(unittest.TestCase):
128
+ def test_encoding(self):
129
+ client, calls = make_client()
130
+ client.tape(
131
+ [
132
+ {"symbol": "btc", "kind": "crypto"},
133
+ {"symbol": "AAPL", "kind": "stock"},
134
+ ]
135
+ )
136
+ self.assertEqual(
137
+ calls[0], "https://oaio.io/api/v1/tape?items=crypto%3ABTC%2Cstock%3AAAPL"
138
+ )
139
+
140
+ def test_first_12_taken_then_invalid_dropped(self):
141
+ client, calls = make_client()
142
+ items = [
143
+ {"symbol": "", "kind": "crypto"},
144
+ {"symbol": "X", "kind": "bonds"},
145
+ None,
146
+ ] + [{"symbol": "S%d" % i, "kind": "stock"} for i in range(15)]
147
+ client.tape(items)
148
+ sent = urllib.parse.unquote(calls[0].split("items=")[1]).split(",")
149
+ self.assertEqual(len(sent), 9)
150
+ self.assertEqual(sent[0], "stock:S0")
151
+ self.assertEqual(sent[8], "stock:S8")
152
+
153
+ def test_12_valid_items_all_go_out(self):
154
+ client, calls = make_client()
155
+ client.tape([{"symbol": "S%d" % i, "kind": "crypto"} for i in range(14)])
156
+ sent = urllib.parse.unquote(calls[0].split("items=")[1]).split(",")
157
+ self.assertEqual(len(sent), 12)
158
+ self.assertEqual(sent[11], "crypto:S11")
159
+
160
+ def test_no_valid_items(self):
161
+ client, calls = make_client()
162
+ with self.assertRaises(OAIOError) as ctx:
163
+ client.tape([])
164
+ self.assertEqual(
165
+ ctx.exception.message, "items must name at least one {symbol, kind} pair."
166
+ )
167
+ self.assertEqual(calls, [])
168
+
169
+
170
+ class ErrorTests(unittest.TestCase):
171
+ def test_api_json_error_maps(self):
172
+ client, _ = make_client(400, {"error": "kind must be crypto or stock."})
173
+ with self.assertRaises(OAIOError) as ctx:
174
+ client.market_sentiment("crypto")
175
+ self.assertEqual(ctx.exception.status, 400)
176
+ self.assertEqual(ctx.exception.message, "kind must be crypto or stock.")
177
+
178
+ def test_429(self):
179
+ client, _ = make_client(429, {"error": "Rate limit exceeded — slow down."})
180
+ with self.assertRaises(OAIOError) as ctx:
181
+ client.sentiment("BTC")
182
+ self.assertEqual(ctx.exception.status, 429)
183
+ self.assertEqual(ctx.exception.message, "Rate limit exceeded — slow down.")
184
+
185
+ def test_non_json_error_body_falls_back(self):
186
+ client, _ = make_client(502, "error code: 502")
187
+ with self.assertRaises(OAIOError) as ctx:
188
+ client.sentiment("BTC")
189
+ self.assertEqual(ctx.exception.status, 502)
190
+ self.assertEqual(ctx.exception.message, "OAIO API error (HTTP 502)")
191
+
192
+
193
+ class ClientTests(unittest.TestCase):
194
+ def test_base_url_override(self):
195
+ calls = []
196
+
197
+ def opener(request):
198
+ calls.append(request.full_url)
199
+ return FakeResponse(200, "{}")
200
+
201
+ client = OAIO(base_url="http://localhost:8788/", opener=opener)
202
+ client.market_sentiment("stock")
203
+ self.assertEqual(calls[0], "http://localhost:8788/api/market?kind=stock")
204
+
205
+
206
+ if __name__ == "__main__":
207
+ unittest.main()