Skip to content

Commit 5a576d6

Browse files
committed
expose library module
1 parent 7784cfb commit 5a576d6

File tree

5 files changed

+59
-19
lines changed

5 files changed

+59
-19
lines changed

absbox/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from absbox.client import API, Endpoints, EnginePath, PickApiFrom,LIBRARY
77
from absbox.local.util import guess_pool_flow_header, unifyTs, mkTbl, readAeson
88
from absbox.local.base import *
9-
from absbox.local.cmp import comp_engines
9+
from absbox.local.cmp import compResult
1010
from absbox.local.china import 信贷ABS, SPV
1111
from absbox.local.generic import Generic
1212
from absbox.deal import mkDeal, mkDealsBy, setDealsBy, prodDealsBy, setAssumpsBy, prodAssumpsBy

absbox/client.py

Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,8 @@ class LibraryEndpoints(str, enum.Enum):
105105
Query = "query"
106106
Run = "run" # run a deal from the library
107107
Add = "add" # add new deal to library
108+
Cmd = "cmd" # add new deal to library
108109
Get = "get" # get deal from library
109-
# Data = "data"
110-
# DataList = "data/list"
111-
# DealFetch = "deal/fetch"
112-
# ReportFetch = "data/report"
113110

114111

115112
class LibraryPath(str, enum.Enum):
@@ -181,7 +178,7 @@ def pingApi(x):
181178
if len(r)>0:
182179
return API(r[0],**kwargs)
183180
else:
184-
raise AbsboxError(f"❌{MsgColor.Error.value}No valid API found in list match current lib version {libVersion}, from list:{apiResps}")
181+
raise AbsboxError(f"❌ No valid API found in list match current lib version {libVersion}, from list:{apiResps}")
185182

186183

187184
@dataclass
@@ -226,7 +223,7 @@ def __post_init__(self) -> None:
226223
else:
227224
self.url = isValidUrl(self.url).rstrip("/")
228225

229-
console.print(f"{MsgColor.Info.value}Connecting engine server -> {self.url}")
226+
console.print(f" Connecting engine server -> {self.url}")
230227

231228
if self.lang not in ["chinese", "english"]:
232229
raise AbsboxError(f"❌Invalid language:{self.lang}, only support 'chinese' or 'english' ")
@@ -373,7 +370,7 @@ def run(self, deal,
373370
"""
374371

375372
if (not isinstance(poolAssump, tuple)) and (poolAssump is not None):
376-
raise AbsboxError(f"❌{MsgColor.Error.value} poolAssump should be a tuple but got {type(poolAssump)}")
373+
raise AbsboxError(f"❌ poolAssump should be a tuple but got {type(poolAssump)}")
377374

378375

379376
# if run req is a multi-scenario run
@@ -391,9 +388,9 @@ def run(self, deal,
391388

392389
if result is None or 'error' in result or 'Left' in result:
393390
leftVal = result.get("Left","")
394-
raise AbsboxError(f"❌{MsgColor.Error.value}Failed to get response from run: {leftVal}")
391+
raise AbsboxError(f"❌ Failed to get response from run: {leftVal}")
395392
result = result['Right']
396-
rawWarnMsg = map( lambda x:f"{MsgColor.Warning.value}{x['contents']}", filter_by_tags(result[RunResp.LogResp.value], enumVals(ValidationMsg)))
393+
rawWarnMsg = map( lambda x:f" {x['contents']}", filter_by_tags(result[RunResp.LogResp.value], enumVals(ValidationMsg)))
397394
if rawWarnMsg and showWarning:
398395
console.print("Warning Message from server:\n"+"\n".join(list(rawWarnMsg)))
399396

@@ -439,11 +436,11 @@ def runByScenarios(self, deal,
439436

440437
if result is None or 'error' in result or "Left" in set(tz.concat([ _.keys() for _ in result.values()])):
441438
leftVal = { k:v['Left'] for k,v in result.items() if "Left" in v }
442-
raise AbsboxError(f"❌{MsgColor.Error.value}Failed to get response from run: {leftVal}")
439+
raise AbsboxError(f"❌ Failed to get response from run: {leftVal}")
443440

444441
result = tz.valmap(lambda x:x['Right'] ,result)
445442

446-
rawWarnMsgByScen = {k: [f"{MsgColor.Warning.value}{_['contents']}" for _ in filter_by_tags(v[RunResp.LogResp.value], enumVals(ValidationMsg))] for k, v in result.items()}
443+
rawWarnMsgByScen = {k: [f" {_['contents']}" for _ in filter_by_tags(v[RunResp.LogResp.value], enumVals(ValidationMsg))] for k, v in result.items()}
447444
rawWarnMsg = list(tz.concat(rawWarnMsgByScen.values()))
448445

449446
if showWarning and len(rawWarnMsg)>0:
@@ -982,7 +979,7 @@ def add(self, d, **p):
982979
,"name": d.name
983980
,"version": p.get("version",0)
984981
,"period": p.get("period",0)
985-
,"stage": p.get("stage","")
982+
,"stage": p.get("stage","draft")
986983
,"comment": p.get("comment","")
987984
,"permission": p.get("permission","700")
988985
,"tags": p.get("tags",[])
@@ -998,6 +995,16 @@ def add(self, d, **p):
998995

999996
console.print(f"✅ add success with deal id={r['dealId']}, name={r['name']}")
1000997

998+
def cmd(self, p):
999+
if not hasattr(self, "token"):
1000+
raise AbsboxError(f"❌ No token found, please call login() to login")
1001+
1002+
deal_library_url = self.url+f"/{LibraryEndpoints.Cmd.value}"
1003+
1004+
r = self._send_req(pickle.dumps(p), deal_library_url,headers={"Authorization": f"Bearer {self.token}"} )
1005+
1006+
return r
1007+
10011008
def get(self, q):
10021009
if not hasattr(self, "token"):
10031010
raise AbsboxError(f"❌ No token found, please call login() to login")
@@ -1042,13 +1049,14 @@ def run(self, _id, **p):
10421049
r = self._send_req(bRunReq, deal_library_url
10431050
, headers={"Authorization": f"Bearer {self.token}"
10441051
,"Content-Type":"application/octet-stream"})
1045-
1052+
if 'error' in r:
1053+
raise AbsboxError(f"❌ error from server:{r['error']}")
10461054
try:
10471055
result = r['result']
10481056
runInfo = tz.dissoc(r, 'result')
1049-
console.print(f"✅ run success with deal")
1057+
console.print(f"✅ run success with deal: {runInfo['deal']['name']}|{runInfo['deal']['id']}")
10501058
except Exception as e:
1051-
raise AbsboxError(f"❌ message from API server:{result},\n,{e}")
1059+
raise AbsboxError(f"❌ message from API server:\n,{e}")
10521060
try:
10531061
if read and isinstance(result, list):
10541062
return (runInfo, Generic.read(result))
@@ -1059,6 +1067,38 @@ def run(self, _id, **p):
10591067
except Exception as e:
10601068
raise AbsboxError(f"❌ Failed to read result with error = {e}")
10611069

1070+
# def batch(self, runInputs, **p):
1071+
# """ run multiple deals with assumptions, return a map with deal name with id """
1072+
#
1073+
# if not hasattr(self, "token"):
1074+
# raise AbsboxError(f"❌ No token found, please call login() to login")
1075+
#
1076+
# deal_library_url = self.url+f"/{LibraryEndpoints.BatchRun.value}"
1077+
# read = p.get("read", True)
1078+
#
1079+
# r = self._send_req(bRunReq, deal_library_url
1080+
# , headers={"Authorization": f"Bearer {self.token}"
1081+
# ,"Content-Type":"application/octet-stream"})
1082+
#
1083+
# try:
1084+
# result = r['result']
1085+
# runInfo = tz.dissoc(r, 'result')
1086+
# console.print(f"✅ run success with deal")
1087+
# except Exception as e:
1088+
# raise AbsboxError(f"❌ message from API server:{result},\n,{e}")
1089+
# try:
1090+
# if read and isinstance(result, list):
1091+
# return (runInfo, Generic.read(result))
1092+
# elif read and isinstance(result, dict):
1093+
# return (runInfo, tz.valmap(Generic.read, result))
1094+
# else:
1095+
# return (runInfo, result)
1096+
# except Exception as e:
1097+
# raise AbsboxError(f"❌ Failed to read result with error = {e}")
1098+
1099+
1100+
1101+
10621102
def _send_req(self, _req, _url: str, timeout=10, headers={})-> dict | None:
10631103
"""generic function send request to server
10641104

absbox/local/cmp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def compDf(x, y):
2222
if pd.api.types.is_numeric_dtype(cmp[column][nameA]) and pd.api.types.is_numeric_dtype(cmp[column][nameB]):
2323
result[column, 'diff'] = cmp[column][nameA].fillna(0) - cmp[column][nameB].fillna(0)
2424
#return result.sort_index(axis=1,level=1)
25-
return result.reindex(axis=1, level=1, labels=[nameA, nameB, 'diff'])
25+
return result.reindex(axis=1, level=1, labels=[nameA, nameB, 'diff']).sort_index(axis=1,level=0)
2626

2727
# r1 -> Left
2828
# r2 -> Right

absbox/local/component.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1065,7 +1065,7 @@ def mkMod(y: dict) -> tuple:
10651065
, earlyReturnNone(mkDs, mbal)
10661066
, earlyReturnNone(mkDsRate, mrate)]))
10671067
case ["计提利息", *bndNames] | ["calcInt", *bndNames]:
1068-
return mkTag(("CalcBondInt", [vList(bndNames, str)]))
1068+
return mkTag(("CalcBondInt", vList(bndNames, str)))
10691069
case ["计提支付费用", source, target, m] | ["calcAndPayFee", source, target, m]:
10701070
(l, s) = mkMod(m)
10711071
return mkTag(("CalcAndPayFee", [l, vStr(source), vList(target, str), s]))

docs/source/library.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ User can access the ``Deal Library`` through the component from ``absbox``.
1717
Self host & Cloud host
1818
^^^^^^^^^^^^^^^^^^^^^^^^^^
1919
There is a public ``Deal Library`` instance hosted on the cloud.
20-
User can also host his/her own instance of the ``Deal Library`` on own server with commerial terms.
20+
User can also host his/her own instance of the ``Deal Library`` on own server with commerial terms ( check with :ref:`Email & Slack`).
2121

2222

2323
Tutorial

0 commit comments

Comments
 (0)