Skip to content

Commit

Permalink
add get_current_price api
Browse files Browse the repository at this point in the history
Former-commit-id: acf7996
  • Loading branch information
foolcage committed Jul 4, 2019
1 parent 547d1f4 commit 07553f1
Show file tree
Hide file tree
Showing 10 changed files with 74 additions and 41 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
[![github](https://img.shields.io/github/stars/zvtvz/zvt.svg)](https://github.com/zvtvz/zvt)
[![image](https://img.shields.io/pypi/v/zvt.svg)](https://pypi.org/project/zvt/)
[![image](https://img.shields.io/pypi/l/zvt.svg)](https://pypi.org/project/zvt/)
[![image](https://img.shields.io/pypi/pyversions/zvt.svg)](https://pypi.org/project/zvt/)
[![Build Status](https://api.travis-ci.org/zvtvz/zvt.svg?branch=master)](https://travis-ci.org/zvtvz/zvt)
[![codecov.io](https://codecov.io/github/zvtvz/zvt/coverage.svg?branch=master)](https://codecov.io/github/zvtvz/zvt)
[![HitCount](http://hits.dwyl.io/zvtvz/zvt.svg)](http://hits.dwyl.io/zvtvz/zvt)

**Read this in other languages: [English](README-en.md).**

Expand Down
4 changes: 1 addition & 3 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
[![image](https://img.shields.io/pypi/v/zvt.svg)](https://pypi.org/project/zvt/)
[![github](https://img.shields.io/github/stars/zvtvz/zvt.svg)](https://github.com/zvtvz/zvt)
[![image](https://img.shields.io/pypi/l/zvt.svg)](https://pypi.org/project/zvt/)
[![image](https://img.shields.io/pypi/pyversions/zvt.svg)](https://pypi.org/project/zvt/)
[![Build Status](https://api.travis-ci.org/zvtvz/zvt.svg?branch=master)](https://travis-ci.org/zvtvz/zvt)
[![codecov.io](https://codecov.io/github/zvtvz/zvt/coverage.svg?branch=master)](https://codecov.io/github/zvtvz/zvt)
[![HitCount](http://hits.dwyl.io/zvtvz/zvt.svg)](http://hits.dwyl.io/zvtvz/zvt)
## ZVT是什么?

ZVT是在[fooltrader](https://github.com/foolcage/fooltrader)的基础上重新思考后编写的量化项目,其包含可扩展的数据recorder,api,因子计算,选股,回测,交易,定位为**中低频** **多级别** **多标的** **多因子** 全市场分析和交易框架。
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
# For a discussion on single-sourcing the version across setup.py and the
# project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.0.5', # Required
version='0.0.6', # Required

# This is a one-line description or tagline of what your project does. This
# corresponds to the "Summary" metadata field:
Expand Down
3 changes: 3 additions & 0 deletions zvt/accounts/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
# -*- coding: utf-8 -*-
from zvt.accounts.ccxt_account import CCXTAccount

CCXTAccount.init()
40 changes: 22 additions & 18 deletions zvt/accounts/ccxt_account.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,45 @@
# -*- coding: utf-8 -*-
import json

import ccxt

from zvt.domain import COIN_EXCHANGES
from zvt.settings import HTTP_PROXY, HTTPS_PROXY


class CCXTAccount(object):
def __init__(self, exchanges=COIN_EXCHANGES) -> None:
self.exchange_conf = {}
self.exchanges = exchanges

self.init_exchange_conf()
exchanges = COIN_EXCHANGES
exchange_conf = {}

def init_exchange_conf(self):
for exchange in self.exchanges:
@classmethod
def init(cls):
for exchange in cls.exchanges:
import pkg_resources

resource_package = 'zvt'
resource_path = 'accounts/{}.json'.format(exchange)
config_file = pkg_resources.resource_filename(resource_package, resource_path)

with open(config_file) as f:
self.exchange_conf[exchange] = json.load(f)
cls.exchange_conf[exchange] = json.load(f)

def get_tick_limit(self, exchange):
return self.exchange_conf[exchange]['tick_limit']
@classmethod
def get_tick_limit(cls, exchange):
return cls.exchange_conf[exchange]['tick_limit']

def get_kdata_limit(self, exchange):
return self.exchange_conf[exchange]['kdata_limit']
@classmethod
def get_kdata_limit(cls, exchange):
return cls.exchange_conf[exchange]['kdata_limit']

def get_safe_sleeping_time(self, exchange):
return self.exchange_conf[exchange]['safe_sleeping_time']
@classmethod
def get_safe_sleeping_time(cls, exchange):
return cls.exchange_conf[exchange]['safe_sleeping_time']

def get_ccxt_exchange(self, exchange_str):
@classmethod
def get_ccxt_exchange(cls, exchange_str) -> ccxt.Exchange:
exchange = eval("ccxt.{}()".format(exchange_str))
exchange.apiKey = self.exchange_conf[exchange_str]['apiKey']
exchange.secret = self.exchange_conf[exchange_str]['secret']
exchange.apiKey = cls.exchange_conf[exchange_str]['apiKey']
exchange.secret = cls.exchange_conf[exchange_str]['secret']
# set to your proxies if need
exchange.proxies = {'http': 'http://127.0.0.1:10081', 'https': 'http://127.0.0.1:10081'}
exchange.proxies = {'http': HTTP_PROXY, 'https': HTTPS_PROXY}
return exchange
29 changes: 27 additions & 2 deletions zvt/api/technical.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pandas as pd
from sqlalchemy.orm import Session

from zvt.accounts.ccxt_account import CCXTAccount
from zvt.api.common import get_data, decode_security_id
from zvt.api.common import get_security_schema, get_kdata_schema
from zvt.domain import get_db_engine, TradingLevel, Provider, get_store_category, SecurityType, get_db_session, \
Expand All @@ -19,7 +20,8 @@ def init_securities(df, security_type='stock', provider=Provider.EASTMONEY):
db_engine = get_db_engine(provider, store_category=store_category)
security_schema = get_security_schema(security_type)

current = get_securities(security_type=security_type, columns=[security_schema.id,security_schema.code], provider=provider)
current = get_securities(security_type=security_type, columns=[security_schema.id, security_schema.code],
provider=provider)
df = df[~df['id'].isin(current['id'])]

df.to_sql(security_schema.__tablename__, db_engine, index=False, if_exists='append')
Expand Down Expand Up @@ -102,10 +104,32 @@ def get_kdata(security_id, level=TradingLevel.LEVEL_1DAY.value, provider='eastmo
end_timestamp=end_timestamp, filters=filters, session=session, order=order, limit=limit)


def get_current_price(security_list=None, security_type=SecurityType.coin):
result = {}
if security_type == SecurityType.coin:
if security_list:
for security_id in security_list:
a, exchange, code = decode_security_id(security_id)
assert SecurityType(a) == security_type
ccxt_exchange = CCXTAccount.get_ccxt_exchange(exchange_str=exchange)

if not ccxt_exchange:
raise Exception('{} not support'.format(exchange))

orderbook = ccxt_exchange.fetch_order_book(code)

bid = orderbook['bids'][0][0] if len(orderbook['bids']) > 0 else None
ask = orderbook['asks'][0][0] if len(orderbook['asks']) > 0 else None
security_id = f'coin_{exchange}_{code}'
result[security_id] = (bid, ask)

return result


if __name__ == '__main__':
# print(get_securities())
# print(get_kdata(security_id='stock_sz_300027', provider='netease'))
print(get_kdata(security_id='coin_binance_EOS/USDT', provider='ccxt', level=TradingLevel.LEVEL_1MIN))
# print(get_kdata(security_id='coin_binance_EOS/USDT', provider='ccxt', level=TradingLevel.LEVEL_1MIN))
# print(get_finance_factor(security_id='stock_sh_601318', session=get_db_session('eastmoney')))
# a = get_stock_category('stock_sz_000029')
# print(a)
Expand All @@ -120,3 +144,4 @@ def get_kdata(security_id, level=TradingLevel.LEVEL_1DAY.value, provider='eastmo
# print(df)
#
# print(get_securities(codes=['000338', '000778', '600338'], exchanges=['sz']))
print(get_current_price(['coin_huobipro_EOS/USDT', 'coin_binance_EOS/USDT']))
11 changes: 4 additions & 7 deletions zvt/recorders/ccxt/coin_kdata_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,18 @@ def request(self, url=None, method='get', param=None, path_fields=None):
size = param['size']
ccxt_level = param['ccxt_level']
level = param['level']
ccxt_account: CCXTAccount = param['ccxt_account']

ccxt_exchange = ccxt_account.get_ccxt_exchange(security_item.exchange)
ccxt_exchange = CCXTAccount.get_ccxt_exchange(security_item.exchange)

if ccxt_exchange.has['fetchOHLCV']:
limit = ccxt_account.get_kdata_limit(security_item.exchange)
limit = CCXTAccount.get_kdata_limit(security_item.exchange)

limit = min(size, limit)

kdata_list = []

try:
if ccxt_account.exchange_conf[security_item.exchange]['support_since']:
if CCXTAccount.exchange_conf[security_item.exchange]['support_since']:
kdatas = ccxt_exchange.fetch_ohlcv(security_item.code,
timeframe=ccxt_level,
since=start_timestamp)
Expand Down Expand Up @@ -82,7 +81,6 @@ def __init__(self, security_type=SecurityType.coin, exchanges=['binance'], codes

self.ccxt_trading_level = to_ccxt_trading_level(level)
self.start_timestamp = to_pd_timestamp(start_timestamp)
self.ccxt_account = CCXTAccount(exchanges=exchanges)

super().__init__(security_type, exchanges, codes, batch_size, force_update, sleeping_time, fetching_style,
default_size, contain_unfinished_data, level, one_shot, kdata_use_begin_time=True)
Expand All @@ -102,8 +100,7 @@ def generate_request_param(self, security_item, start, end, size, timestamp):
'start_timestamp': to_time_str(start),
'size': size,
'level': self.level,
'ccxt_level': self.ccxt_trading_level,
'ccxt_account': self.ccxt_account
'ccxt_level': self.ccxt_trading_level
}


Expand Down
3 changes: 1 addition & 2 deletions zvt/recorders/ccxt/coin_meta_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@ class CoinMetaRecorder(Recorder):

def __init__(self, batch_size=10, force_update=False, sleeping_time=10, exchanges=COIN_EXCHANGES) -> None:
super().__init__(batch_size, force_update, sleeping_time)
self.ccxt_account = CCXTAccount(exchanges=exchanges)
self.exchanges = COIN_EXCHANGES

def run(self):
for exchange_str in self.exchanges:
exchange = self.ccxt_account.get_ccxt_exchange(exchange_str)
exchange = CCXTAccount.get_ccxt_exchange(exchange_str)
try:
markets = exchange.fetch_markets()
df = pd.DataFrame()
Expand Down
9 changes: 3 additions & 6 deletions zvt/recorders/ccxt/coin_tick_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@ class MyApiWrapper(ApiWrapper):
def request(self, url=None, method='get', param=None, path_fields=None):
security_item = param['security_item']
size = param['size']
ccxt_account: CCXTAccount = param['ccxt_account']

ccxt_exchange = ccxt_account.get_ccxt_exchange(security_item.exchange)
ccxt_exchange = CCXTAccount.get_ccxt_exchange(security_item.exchange)

if ccxt_exchange.has['fetchTrades']:
limit = ccxt_account.get_tick_limit(security_item.exchange)
limit = CCXTAccount.get_tick_limit(security_item.exchange)

limit = min(size, limit)

Expand Down Expand Up @@ -70,7 +69,6 @@ def __init__(self, security_type=SecurityType.coin, exchanges=['binance'], codes
self.data_schema = get_kdata_schema(security_type=security_type, level=TradingLevel.LEVEL_TICK)

self.start_timestamp = to_pd_timestamp(start_timestamp)
self.ccxt_account = CCXTAccount(exchanges=exchanges)

super().__init__(security_type, exchanges, codes, batch_size, force_update, sleeping_time, fetching_style,
default_size, contain_unfinished_data, TradingLevel.LEVEL_TICK, one_shot,
Expand All @@ -91,8 +89,7 @@ def generate_request_param(self, security_item, start, end, size, timestamp):
return {
'security_item': security_item,
'start_timestamp': to_time_str(start),
'size': size,
'ccxt_account': self.ccxt_account
'size': size
}


Expand Down
10 changes: 9 additions & 1 deletion zvt/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
DATA_SAMPLE_ZIP_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'datasample.zip'))

# please change the path to your real store path
DATA_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'data'))
DATA_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'datasample'))

UI_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'ui'))

Expand All @@ -27,3 +27,11 @@

# 覆盖维度 银行/保险/企业/券商 创业板 中小板 主板
SAMPLE_STOCK_CODES = ['000001', '000783', '000778', '603220', '601318', '000338', '002572', '300027']

HTTP_PROXY = None
if not HTTP_PROXY:
HTTP_PROXY = os.environ.get('HTTP_PROXY')

HTTPS_PROXY = None
if not HTTPS_PROXY:
HTTPS_PROXY = os.environ.get('HTTPS_PROXY')

0 comments on commit 07553f1

Please sign in to comment.