Python for Financial Engineering

HRT’s Head of Risk Python for Financial Engineering

Python for Financial Engineering We are designing a combined two-step approach called ‘FSBL’ to construct an optimal portfolio.

For the first step of establishing the stock pool, we derive the logic of designing our trading strategies from Piotroski F-Score. Piotroski scoring method is utilized to find the best value stocks, in which companies with F-Score of 9 are considered to be strong candidates. In addition, our FSBL strategy, we design a new model of FF-Score incorporating four criteria selected from the nine criteria of F-Score. For the next step of asset allocation, we use Black-Litterman model to construct the optimal portfolio.  

An empirical test in China A-share market from FY 2018-20 based on Python coding is conducted to further testify the validity and practicality of our FSBL model. Furthermore, two other classical and mathematical models for portfolio allocation, which are Mean Variance Optimization, and Parametric Portfolio Policy, will also be applied in our test as the comparison for the B-L model.  

Theoretical Foundation 

i. Piotroski F-Score 

In addition, Piotroski F-Scores are commonly used by financial investors to find the best value  stocks. In addition, the score is based on 9 criteria divided into 3 main categories, which is shown  in the table below. 

Table1-F-Score 9 criteria

Profitability
1. Return on Assets 1 point if it is positive in the current year, 0 otherwise
2. Operating Cash Flow 1 point if it is positive in the current year, 0 otherwise
3. Change in Return of  Assets1 point if ROA is higher in the current year compared to the previous one, 0 otherwise
4. Accruals 1 point if Operating Cash Flow/Total Assets is higher  than ROA in the current year, 0 otherwise
Leverage, Liquidity and Source of Funds
5. Change in Leverage  ratio1 point if the ratio is lower this year compared to the  previous one, 0 otherwise
6. Change in Current  ratio1 point if it is higher in the current year compared to the  previous one, 0 otherwise
7. Change in number of  shares1 point if now new shares were issued during the last  year
Operating Efficiency
8. Change in Gross  Margin1 point if it is higher in the current year compared to the  previous one, 0 otherwise
9. Change in Asset  Turnover ratio1 point if it is higher in the current year compared to the  previous one, 0 otherwise
Python for Financial Engineering

Summing up of all achieved points gives the final Piotroski F-Score, and stocks with  F-Score of 8-9 can be regarded as strong stock candidates. 

ii. Black-Litterman Model 

  

The Black-Litterman model uses the Markowitz mean-variance model as a framework, combines the capital asset pricing model proposed by Sharp and others, and adds the subjective investment perspective of investors based on their own judgments. Investors should set up their personal subjective perspectives. The corresponding confidence level is set, and we will use the Bayes method to combine the equilibrium returns and the subjective view return to get the posterior return rate.  

Finally, the posterior return rate is put into the Markowitz model, and the final portfolio weights are solved. Furthermore, this entire logic flow is clearly demonstrated in the diagram on the right-hand side. 

In other words, the B-L model weights the following two points to obtain the final expected asset return,  

1. Market equilibrium returns. The actual returns formed in the market are  obtained through the analysis of historical data (Posterior Source of  Information). 

2. Investors’ subjective views on returns. Which sets the corresponding  confidence level (Prior Source of Information). 

iii. Mean Variance Optimization 

Mean Variance Optimization (MVO) is a quantitative tool allowing investors to  arrange the allocation by considering the trade-off between risk and return. Mean  Variance Optimization generates a list of minimum variance portfolios with the  process shown in the process below.

iv. Random Forest  

Random Forest is one of the most prevalent machine learning methods in recent  years. Random forest is a strong classifier trained by integrating a series of decision  trees with Bagging parallel method, which can be applied to different scenarios of  classification and regression. Its process is as follows.  

Investors can use random forest model for their trading strategies. One of the examples in Quantopian is previous research of Random Forest Model that makes us of price and sentiment to predict if the short-term future return is positive or not.

FSBL: Empirical Test 

i. 1st step: FF-Score to establish our stock pool

The F-Score progress is a bit complicated, so we choose the most important four factors as our stock ranking criteria.  

We use: (1)ROE(return on equity) and dROE(change of ROE) to evaluate the company’s profitability 

 (2)dEPS(change in earnings per share) to evaluate the leverage and liquidity  (3)GPR( gross profit rate ) to evaluate the operating efficiency

But we can’t just simply add up the 4 factors’ data to get the stocks’ score, because different factor’s data is not additive. So the first thing we should do is x − x standardization: We calculate the standard score( σ every stock and add them up as every stock’s score. 

Then we pick the top 50 stocks as our initial stocks pool. 

Finally, the quantity and span of historical data influence our estimation of the stocks’ future performance greatly. So we scan every stock to exclude the ones with TTM (time to market) no longer than 5 years or incomplete data. 

The final stocks pool follows: 

ii. 2nd step:MVO Model to construct optimal portfolio 

1.To implement the Mean-Variance Model, firstly we should estimate the expected  returns and volatility of each stock in our pool.We use the five years’ mean-returns  as the expected returns and use the historical returns’ covariance to get historical  standard deviation as the expected volatility.And we use the mean-rate of China’s  government bond as the risk-free rate. 

2.Then if we want to get the MVO portfolio we can just calculate the efficient frontier  and select our favorite portfolio from the frontier.But that’s a bit boring, so firstly  let’s use an interesting approach. 

3.Monte Carlo Simulation: 

If we want to get the best portfolio, why can’t we just generate ‘all’ the possible  portfolio and select the best? So we generate 80000 random portfolios, from which  we look for the optimal portfolio with maximal sharpe ratio and minimal volatility.  The results follows:

Then we use the the historical price from 2018.10.23 to 2019.10.16 to complete the fund back testing. 

The fund back testing curve is as follows: 

But that doesn’t make us satisfied, we want to see how does this method work.So  we put the frontier, CML(capital and market line)and the method’s result on the  graph:  

The results are similar but not the same, if you watch carefully, you will see a small gap between the random portfolios’ boundary and the efficient frontier. Maybe you’ll say the gap is so small that we can ignore it. Is that true? 

So we pick up 50 stocks and do the test(draw the random portfolio and the efficient  frontier) 

The results follows:

Python for Financial Engineering
Theoretically the boundary of the random portfolio should be the efficient  frontier.But the gap between the random portfolio and the efficient frontier is  too big to ignore.So why does this happen? 

Firstly, let’s look back to the 2 MVO method’s results. I find that if we use an efficient  frontier, many stocks’ weights are 0, but if we use Monte Carlo Simulation, almost  all the stocks are bought. 

Try to explain this phenomenon, I generate some random portfolio of the 50 stocks  and check their wights,I find that the weights are scattered across the table and they  don’t gather together: 

Then I check the weights of the portfolio on the efficient frontier I find that many  stocks’ weights are approximately zero, the discovery is just like our earlier results:

7.Conclusion: one of the explanations maybe that the random portfolios’ weights  always scatter around and they don’t cluster near 0.But many of the efficient  frontier portfolios’ weights are 0.In other words,80000 is not ‘all’ and the 80000  random portfolios are not ‘all’ of the possible portfolios.So if we generate enough  random portfolios the simulation will be closer to the theory. 

We select four criteria  

iii. 3rdstep: B-L Model to construct optimal portfolio 

B-L model weights the following two points to obtain the final expected asset return. One is the market equilibrium returns. Furthermore, the actual returns formed in the market are obtained through the analysis of historical data (Posterior Source of Information). Lastly, the other is the investors’ subjective views on returns. 

The essence of B-L model lies on its Bayes shrinkage of return rate. The advantage of this approach is that it does not need investors to guess the return accurately, instead, they only need to input their views.

To some extent, the BL model is an extension of MVO, trying to fix MVO’s shortage of being sensible to the expected return. 

We choose the stock pool based on the result of the FF-score model, then we get ten  stocks. Then, we give two groups of views according to the analyst’s recommended  data gained from Uqer. 

iv. 4th step: Random Forest

Previous Research of Random Forest Model that utilizes price and sentiment to  predict if the short-term future return is positive or not 

The coding procedures include: 

➢ Retrieve data 

➢ Process data the get the indicators: calculate the indicators for each target;  normalized; read the data and integrate it; normalized training data is 0 ➢ Train the model using random forest: train and save random forest models;  update model with valid set data 

➢ Complete fund back testing: read data and integrate; calculate the volatility  & average return & drawdown 

The final result of random forest is: volatility= 14.33%; average return= 1.23%;  drawdown= -0.96612% 

v. Result analysis

Evaluation and Future Research Direction 

There is still space to improve for our FSBL trading strategy on Piotroski F-Score, B L model, and our empirical test.  

Updated research results on the Piotroski F-Score model can indicate that this model can  be further improved to provide better stock evaluation. For example, calculating F Score based on dynamically updated financial data of individual stocks can improve  the stock selection ability of the model. Besides, about F-Score itself, there are some  interesting questions to further delve into. Why 9 financial criteria? Are there any  other useful financial indicators? And why equal scale from 0 to 1? 

Conclusion 

First , by using our FF-score model, we successfully get a list of stocks which behaves  well in four aspects as our stock pool. After that we try three different methods to find  out the optimal portfolio from the stock pool. 

The mean-variance model and black-litterman model are both mathematical approaches. The black-litterman model, in fact , is the extension of MVO model as it makes up for  the shortage of MVO that there is no need to accurately guess the variance and return  of the stocks, and the adding view ensure that the portfolio weight will more or less  avoid the huge change of the optimal portfolio. In our approach, the MVO model  behaves a little better in return and volatility, while its allocated weight of each stock  in the portfolio is less even than the Bl model does. 

The rainforest model is a typical machine learning method. We try to use a random  forest model as a contrast. It achieves the lowest volatility among the three models  while its return rate is also the lowest.  

After practice, we have basically proved the practicability of our FSBL model,  although there still lies a series points to be improved, we are really glad that we all  improved a lot during the process of making this approach by our own efforts. 

References 

Da Silva, A. S., Lee, W., & Pornrojnangkool, B. (2009). The Black–Litterman model  for active portfolio management. The Journal of Portfolio Management, 35(2),  61-70. 

Mannor, S., & Tsitsiklis, J. (2011). Mean-variance optimization in Markov decision  processes. arXiv preprint arXiv:1104.5601. 

Mohr, J. H. M. (2012). Utility of Piotroski F-score for predicting growth-stock  returns. In MFIE Capital Working Paper. 

Novy-Marx, R. (2013). The quality dimension of value investing. Rnm. simon.  rochester. edu, 1-54. 

Piotroski, J. D. (2000). Value investing: The use of historical financial statement  information to separate winners from losers. Journal of Accounting Research, 1- 41.

Python for Financial Engineering Python for Financial Engineering

Walters, C. F. A. (2014). The Black-Litterman model in detail. Available at SSRN  1314585. Erlich, I., Venayagamoorthy, G. K., & Worawat, N. (2010, July). A mean-variance optimization  algorithm. In IEEE Congress on Evolutionary Computation (pp. 1-6). IEEE.

Python for Financial Engineering