1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| BeginPackage["StockLink`"]
StockLink::usage="StockLink"; CloseLink::usage="CloseLink";
DailyKLine::usage="Get KLine data";
CandlestickData::usage="adjust KLine data to fit Candlestick Chart"; TradingChartData::usage="adjust KLine data to fit Trading Chart";
Begin["`Private`"]
StockLink[]:=Module[{conn}, conn=StartExternalSession["Python"]; ExternalEvaluate[conn," import baostock as bs lg=bs.login() "]; conn ];
CloseLink[conn_]:=Module[{}, ExternalEvaluate[conn," bs.logout() "]; DeleteObject[conn]; ];
MMAListToPythonList[list_]:=StringReplace[ToString[list,InputForm],{"\" "->"'","{"->"[","}"->"]"}]; DateObjectToStr[date_]:=DateString[date,"ISODate"];
DailyKLine[conn_,code_,startDate_,endDate_]:=Module[{}, raw=ExternalEvaluate[conn, StringTemplate[" rs = bs.query_history_k_data_plus('``', 'date,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST', start_date='``', end_date='``', frequency='d', adjustflag='3') data_list = {} while (rs.error_code == '0') & rs.next(): temp=rs.get_row_data() data_list[temp[0]]=temp[1:]; data_list"][code,DateObjectToStr[startDate],DateObjectToStr[endDate]]]; ToExpression[#]& /@ raw ];
CandlestickData[raw_]:=Table[{DateObject[key],raw[key][[1;;4]]},{key,Keys[raw]}]; TradingChartData[raw_]:=Table[{DateObject[key],raw[key][[1;;5]]},{key,Keys[raw]}];
End[]
EndPackage[]
|