[Vnpy Quantitative Investment from Scratch] 9. Fund Dynamic Calculation

[Vnpy Quantitative Investment from Scratch] 9. Fund Dynamic Calculation

overview

In the previous strategies, whether it is the built-in strategy of vnpy or the strategy written by ourselves, the lot size of a single transaction is fixed. This situation does not meet the requirements of risk management, nor can it make full use of the profitable funds to achieve the purpose of compound interest growth. Therefore, we need to add profit and loss calculations to the strategy, so that the real-time and accurate capital situation can be obtained within the strategy, so as to calculate the appropriate position according to the current amount of funds.

Why can't we get funds directly from vnpy

The backtest results of vnpy include a complete fund curve, why can it calculate the curve, but we can't get real-time funds through the API when the strategy is running?
From the source code of vnpy's backtesting file, we can see that the backtesting mechanism records all transaction records. And through the playback of k-line and transaction data, after the backtest is over, calculate the daily end-of-day funds based on the daily position and closing price.
insert image description here

Except for the above mechanism, vnpy does not provide any fund-related configuration when it is running on a real offer. Therefore, the fund management of each strategy needs to be handled by ourselves.

Implementation

We can add generic money management using the cta strategy template. Add the variable capital to the strategy, and make the parameters and variables of vnpy include this variable. In this way, when the strategy is initialized, we can set the initial funds through the configuration file. And after the strategy is run, the real-time funds are stored in the data file to ensure the coherence of the fund data.
At the same time, we add the calculation of profit and loss in the on_trade method, and update the result to the strategy in real time.

Extended transaction record function

Our previous transaction records only have the function of storage. At this time, we need to add two functions: the function of querying open position data and updating data status. To query open position data, only

Guess you like

Origin blog.csdn.net/u011687355/article/details/130336191