This project does not currently guarantee any backward compatibility, so please upgrade with caution. As the author’s thoughts evolve, some things that were once considered important may become less so, and thus may not be maintained. Whether the addition of some new elements will be useful to you needs to be assessed by yourself.
The example shown here relies on data, factor, trader, please read docs
The core concept of the system is visual, and the name of the interface corresponds to it one-to-one, so it is also uniform and extensible.
You can write and run the strategy in your favorite ide, and then view its related targets, factor, signal and performance on the UI.
Rest api and standalone UI
It is more flexible and more scalable, more suitable for handling real-time market data and user interaction.
Combined with the dynamic tag system provided by ZVT, it offers a trading approach that combines AI with human intervention.
The few lines of code above has done: data capture, persistence, incremental update, machine learning, prediction, and display results.
Once you are familiar with the core concepts of the system, you can apply it to any target in the market.
The key is tradable entity type, and the value is the schema. The system provides unified record (record_data) and query (query_data) methods for the schema.
>>> Index.record_data()
>>> df=Index.query_data(filters=[Index.category=='scope',Index.exchange='sh'])
>>> print(df)
id entity_id timestamp entity_type exchange code name list_date end_date publisher category base_point
0 index_sh_000001 index_sh_000001 1990-12-19 index sh 000001 上证指数 1991-07-15 None csindex scope 100.00
1 index_sh_000002 index_sh_000002 1990-12-19 index sh 000002 A股指数 1992-02-21 None csindex scope 100.00
2 index_sh_000003 index_sh_000003 1992-02-21 index sh 000003 B股指数 1992-08-17 None csindex scope 100.00
3 index_sh_000010 index_sh_000010 2002-06-28 index sh 000010 上证180 2002-07-01 None csindex scope 3299.06
4 index_sh_000016 index_sh_000016 2003-12-31 index sh 000016 上证50 2004-01-02 None csindex scope 1000.00
.. ... ... ... ... ... ... ... ... ... ... ... ...
25 index_sh_000020 index_sh_000020 2007-12-28 index sh 000020 中型综指 2008-05-12 None csindex scope 1000.00
26 index_sh_000090 index_sh_000090 2009-12-31 index sh 000090 上证流通 2010-12-02 None csindex scope 1000.00
27 index_sh_930903 index_sh_930903 2012-12-31 index sh 930903 中证A股 2016-10-18 None csindex scope 1000.00
28 index_sh_000688 index_sh_000688 2019-12-31 index sh 000688 科创50 2020-07-23 None csindex scope 1000.00
29 index_sh_931643 index_sh_931643 2019-12-31 index sh 931643 科创创业50 2021-06-01 None csindex scope 1000.00
[30 rows x 12 columns]
EntityEvent
We have tradable entity and then events about them.
Market quotes
the TradableEntity quote schema follows the following rules:
{entity_shema}{level}{adjust_type}Kdata
entity_schema
TradableEntity class,e.g., Stock,Stockus.
level
>>> for level in IntervalLevel:
print(level.value)
adjust type
>>> for adjust_type in AdjustType:
print(adjust_type.value)
Note: In order to be compatible with historical data, the pre-reset is an exception, {adjust_type} is left empty
Note the optional parameter provider, which represents the data provider.
A schema can have multiple providers, which is the cornerstone of system stability.
So, you should be able to answer the following three questions now:
What data is there?
How to record data?
How to query data?
For more advanced usage and extended data, please refer to the data section in the detailed document.
Write strategy
Now we could write strategy basing on TradableEntity and EntityEvent.
The so-called strategy backtesting is nothing but repeating the following process:
At a certain time, find the targets which matching conditions, buy and sell them, and see the performance.
Two modes to write strategy:
solo (free style)
At a certain time, calculate conditions according to the events, buy and sell
formal
The calculation model of the two-dimensional index and multi-entity
a too simple,sometimes naive person (solo)
Well, this strategy is really too simple,sometimes naive, as we do most of the time.
When the report comes out, I look at the report.
If the institution increases its position by more than 5%, I will buy it, and if the institution reduces its position by more than 50%, I will sell it.
Show you the code:
# -*- coding: utf-8 -*-
import pandas as pd
from zvt.api import get_recent_report_date
from zvt.contract import ActorType, AdjustType
from zvt.domain import StockActorSummary, Stock1dKdata
from zvt.trader import StockTrader
from zvt.utils import pd_is_not_null, is_same_date, to_pd_timestamp
class FollowIITrader(StockTrader):
finish_date = None
def on_time(self, timestamp: pd.Timestamp):
recent_report_date = to_pd_timestamp(get_recent_report_date(timestamp))
if self.finish_date and is_same_date(recent_report_date, self.finish_date):
return
filters = [StockActorSummary.actor_type == ActorType.raised_fund.value,
StockActorSummary.report_date == recent_report_date]
if self.entity_ids:
filters = filters + [StockActorSummary.entity_id.in_(self.entity_ids)]
df = StockActorSummary.query_data(filters=filters)
if pd_is_not_null(df):
self.logger.info(f'{df}')
self.finish_date = recent_report_date
long_df = df[df['change_ratio'] > 0.05]
short_df = df[df['change_ratio'] < -0.5]
try:
self.trade_the_targets(due_timestamp=timestamp, happen_timestamp=timestamp,
long_selected=set(long_df['entity_id'].to_list()),
short_selected=set(short_df['entity_id'].to_list()))
except Exception as e:
self.logger.error(e)
if __name__ == '__main__':
entity_id = 'stock_sh_600519'
Stock1dKdata.record_data(entity_id=entity_id, provider='em')
StockActorSummary.record_data(entity_id=entity_id, provider='em')
FollowIITrader(start_timestamp='2002-01-01', end_timestamp='2021-01-01', entity_ids=[entity_id],
provider='em', adjust_type=AdjustType.qfq, profit_threshold=None).run()
So, writing a strategy is not that complicated.
Just use your imagination, find the relation of the price and the events.
Simple calculation can be done through query_data.
Now it’s time to introduce the two-dimensional index multi-entity calculation model.
Takes technical factors as an example to illustrate the calculation process:
In [7]: from zvt.factors import *
In [8]: factor = BullFactor(codes=['000338','601318'],start_timestamp='2019-01-01',end_timestamp='2019-06-10', transformer=MacdTransformer(count_live_dead=True))
data_df
two-dimensional index DataFrame read from the schema by query_data.
The origin of ZVT
The Three Major Principles of Stock Trading
Declaration
This project does not currently guarantee any backward compatibility, so please upgrade with caution.
As the author’s thoughts evolve, some things that were once considered important may become less so, and thus may not be maintained.
Whether the addition of some new elements will be useful to you needs to be assessed by yourself.
Read this in other languages: 中文.
Read the docs:https://zvt.readthedocs.io/en/latest/
Install
Main ui
Dash & Plotly UI
After the installation is complete, enter zvt on the command line
open http://127.0.0.1:8050/
Rest api and standalone UI
run following scripts:
https://github.com/zvtvz/zvt/blob/master/src/zvt/tasks/init_tag_system.py https://github.com/zvtvz/zvt/blob/master/src/zvt/tasks/stock_pool_runner.py https://github.com/zvtvz/zvt/blob/master/src/zvt/tasks/qmt_data_runner.py https://github.com/zvtvz/zvt/blob/master/src/zvt/tasks/qmt_tick_runner.py
After the installation is complete, enter zvt_server on the command line
Or run it from source code: https://github.com/zvtvz/zvt/blob/master/src/zvt/zvt_server.py
open http://127.0.0.1:8090/docs
Front end source code: https://github.com/zvtvz/zvt_ui
Change the env file: https://github.com/zvtvz/zvt_ui/blob/main/.env
Set {your server IP} to zvt_server IP
Then refer to the frontend’s README to start the frontend service.
open http://127.0.0.1:3000/trade
Behold, the power of zvt:
Data
China stock
USA stock
Hong Kong stock
And more
The key is tradable entity type, and the value is the schema. The system provides unified record (record_data) and query (query_data) methods for the schema.
EntityEvent
We have tradable entity and then events about them.
Market quotes
the TradableEntity quote schema follows the following rules:
TradableEntity class,e.g., Stock,Stockus.
level
adjust type
qfq
hfq
Finance factor
Three financial tables
And more
All schemas is registered in zvt_context.schemas, schema is table, data structure. The fields and meaning could be checked in following ways:
type the schema. and press tab to show its fields or .help()
Schemas defined in domain
From above examples, you should know the unified way of recording data:
Note the optional parameter provider, which represents the data provider. A schema can have multiple providers, which is the cornerstone of system stability.
Check the provider has been implemented:
You can use any provider to get the data, the first one is used by default.
One more example, the stock sector data recording:
Learn more about record_data
Refer to the scheduling recoding waydata runner
Market-wide stock selection
After recording the data of the whole market, you can quickly query the required data locally.
An example: the top 20 stocks with roe>8% and revenue growth>8% in the 2018 annual report
So, you should be able to answer the following three questions now:
For more advanced usage and extended data, please refer to the data section in the detailed document.
Write strategy
Now we could write strategy basing on TradableEntity and EntityEvent. The so-called strategy backtesting is nothing but repeating the following process:
At a certain time, find the targets which matching conditions, buy and sell them, and see the performance.
Two modes to write strategy:
At a certain time, calculate conditions according to the events, buy and sell
The calculation model of the two-dimensional index and multi-entity
a too simple,sometimes naive person (solo)
Well, this strategy is really too simple,sometimes naive, as we do most of the time.
Show you the code:
So, writing a strategy is not that complicated. Just use your imagination, find the relation of the price and the events.
Then refresh http://127.0.0.1:8050/,check the performance of your strategy.
More examples is in Strategy example
Be serious (formal)
Simple calculation can be done through query_data. Now it’s time to introduce the two-dimensional index multi-entity calculation model.
Takes technical factors as an example to illustrate the calculation process:
data_df
two-dimensional index DataFrame read from the schema by query_data.
factor_df
two-dimensional index DataFrame which calculating using data_df by transformer e.g., MacdTransformer.
result_df
two-dimensional index DataFrame which calculating using factor_df or(and) data_df. It’s used by TargetSelector.
e.g.,macd
The format of result_df is as follows:
filter_result is True or False, score_result is from 0 to 1
Combining the stock picker and backtesting, the whole process is as follows:
Env settings(optional)
History data
ZVT supports incremental data updates, and sharing historical data among users is encouraged for time-saving efficiency
Data providers
the data could be updated from different provider, this make the system stable.
Development
Clone
set up virtual env(python>=3.8),install requirements
Tests
Most of the features can be referenced from the tests
Contribution
code of conduct
Developers are also very welcome to provide more examples for zvt, and work together to improve the documentation.
Buy me a coffee
Contact
wechat:foolcage

wechat subscription:

zhihu:
https://zhuanlan.zhihu.com/automoney
Thanks