Skip to content

Commit

Permalink
added api helpers and updated util
Browse files Browse the repository at this point in the history
  • Loading branch information
rochi88 committed Feb 29, 2024
1 parent 249653e commit 82d4864
Show file tree
Hide file tree
Showing 11 changed files with 151 additions and 5 deletions.
2 changes: 2 additions & 0 deletions bdshare/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,5 @@
for market data
"""
from bdshare.stock.market import (get_market_inf, get_latest_pe, get_market_inf_more_data, get_market_depth_data)

from bdshare.util.store import Store
2 changes: 1 addition & 1 deletion bdshare/_version.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
version_info = (0, 5, 0)
version_info = (0, 5, 1)
__version__ = '.'.join(map(str, version_info))
Empty file added bdshare/api/__init__.py
Empty file.
30 changes: 30 additions & 0 deletions bdshare/api/api_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# -*- coding:utf-8 -*-
"""
Created on 2024/02/29
@author: Raisul Islam
@group : bdshare.xyz
@contact: [email protected]
"""
from bdshare.api import client
from bdshare.util import upass


PRICE_COLS = ['open', 'close', 'high', 'low', 'pre_close']
FORMAT = lambda x: '%.2f' % x
FREQS = {'D': '1DAY',
'W': '1WEEK',
'Y': '1YEAR',
}


def api_data(token=''):
"""
Initialize the API. For the first time, you can record your token credentials through bs.set_token('your token'). The temporary token can be passed in through this parameter.
"""
if token == '' or token is None:
token = upass.get_token()
if token is not None and token != '':
api = client.DataApi(token)
return api
else:
raise Exception('api init error.')
50 changes: 50 additions & 0 deletions bdshare/api/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# !/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Created on 2024/02/29
@author: Raisul Islam
@group : bdshare.xyz
"""

import pandas as pd
import simplejson as json
from functools import partial
import requests


class DataApi:

__token = ''
__http_url = 'https://api.bdshare.xyz'

def __init__(self, token, timeout=10):
"""
Parameters
----------
token: str
API TOKEN, Used for user authentication
"""
self.__token = token
self.__timeout = timeout

def query(self, api_name, fields='', **kwargs):
req_params = {
'api_name': api_name,
'token': self.__token,
'params': kwargs,
'fields': fields
}

res = requests.post(self.__http_url, json=req_params, timeout=self.__timeout)
result = json.loads(res.text)
if result['code'] != 0:
raise Exception(result['msg'])
data = result['data']
columns = data['fields']
items = data['items']

return pd.DataFrame(items, columns=columns)

def __getattr__(self, name):
return partial(self.query, name)
2 changes: 2 additions & 0 deletions bdshare/util/cons.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
TOKEN_F_P = 'tk.csv'
TOKEN_ERR_MSG = 'Please set the token voucher code of bdshare. If not, please visit https://bdshare.xyz to register and apply.'
4 changes: 2 additions & 2 deletions bdshare/util/store.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding:utf-8 -*-

import pandas as pd
import bdshare as ds
from pandas import compat
import os


Expand All @@ -21,7 +21,7 @@ def save_as(self, name, path, to='csv'):
if path is None:
path = self.path
file_path = '%s%s%s.%s'
if isinstance(name) and name is not '':
if isinstance(name, compat.string_types) and name is not '':
if (path is None) or (path == ''):
file_path = '.'.join([name, to])
else:
Expand Down
60 changes: 60 additions & 0 deletions bdshare/util/upass.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# -*- coding:utf-8 -*-

"""
Created on 2024/02/29
@author: Raisul Islam
@group : bdshare.xyz
@contact: [email protected]
"""

import pandas as pd
import os
import cons as ct

BK = 'bk'

def set_token(token):
df = pd.DataFrame([token], columns=['token'])
user_home = os.path.expanduser('~')
fp = os.path.join(user_home, ct.TOKEN_F_P)
df.to_csv(fp, index=False)


def get_token():
user_home = os.path.expanduser('~')
fp = os.path.join(user_home, ct.TOKEN_F_P)
if os.path.exists(fp):
df = pd.read_csv(fp)
return str(df.ix[0]['token'])
else:
print(ct.TOKEN_ERR_MSG)
return None


def set_broker(broker='', user='', passwd=''):
df = pd.DataFrame([[broker, user, passwd]],
columns=['broker', 'user', 'passwd'],
dtype=object)
if os.path.exists(BK):
all = pd.read_csv(BK, dtype=object)
if (all[all.broker == broker]['user']).any():
all = all[all.broker != broker]
all = all.append(df, ignore_index=True)
all.to_csv(BK, index=False)
else:
df.to_csv(BK, index=False)


def get_broker(broker=''):
if os.path.exists(BK):
df = pd.read_csv(BK, dtype=object)
if broker == '':
return df
else:
return df[df.broker == broker]
else:
return None


def remove_broker():
os.remove(BK)
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ requires = [
"requests",
"html5lib",
"pandas",
"simplejson",
]
build-backend = "setuptools.build_meta"
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = bdshare
version = 0.5.0
version = 0.5.1
author= Raisul Islam
author_email= [email protected]
description = A utility for crawling historical and Real-time Quotes of dse
Expand Down
3 changes: 2 additions & 1 deletion tests/test_dsex.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
Created on 2021-Jun-09
@author: Raisul Islam
'''
from bdshare import get_dsex_data
from bdshare import get_dsex_data, Store

df = get_dsex_data()
Store(data=df)
print(df.to_string())

0 comments on commit 82d4864

Please sign in to comment.