Implementation of the simplest investment strategy based on API MOEX (Moscow Exchange)
Introduction
In this hot time, cryptocurrency is worth remembering not only about high instant speculative income, but also about the fact that your money can work and earn your whole life. Being a supporter of fundamental analysis when choosing investment objects, for several years I have preferred to keep money in securities. I went through several stages of the formation of an investment portfolio suitable for my psychological stability, reviewed the composition of the portfolio several times, and gradually came to what I have now.
The essence of the strategy: with the help of a simple technical analysis in the form of tracking simple moving averages, you find the trend reversal point and sell or buy an asset. I am in no way agitating for you to immediately rush and start trading on the exchange, because it works 100%. This only works (!) In combination with an understanding of the fundamental processes taking place in the company.
Two options for applying the strategy
First option ')
I will not go into the most interesting jungles of the theory of the formation of the right investment portfolio, I will tell only about such a thing as rebalancing. Rebalancing is the periodic equalization of the proportions of assets in a portfolio through the sale of risen prices and the purchase of depreciating assets. There is some debate about the effectiveness of this action, but I hold the position that this is a good practice. The question remains - how to spend and at what time.
Some people think that it is necessary to rebalance in a certain month and the entire portfolio, others believe that it is necessary to catch convenient moments (unfortunately this is not always possible). Therefore, I try to combine these two approaches in the implementation of rebalancing.
Second option
Also, every investor has a depressed speculator, and this speculative streak periodically wakes up in each of us. Of course, it is best if she wakes up at a quiet time, and not during the correction, when the brain stubbornly convinces “Sell-sell-sell”. To feed our domestic speculator, we can use the simplest strategy that so many traders use and at the same time it is fairly simple and reliable. The strategy of "following the trend" ( description ). Maybe you have met these terms earlier, for example, on the forex market or on other near market resources, but in terms of a combination of speculation + investing there is a significant difference that makes you look at this strategy from the other side.
I will cite as an example a couple of companies that I follow and consider them quite good in a fundamental sense (good business, reporting, the presence of dividends):
Example 1: Enel
Example 2: Aeroflot
The red circles mark the intersection points of two moving averages with different periods, which is a signal that the trend is strong enough and you can make a decision on the action (buying / selling), in accordance with the fundamental situation. For example, an aeroflot could be sold for a quarter, precisely because of its last quarterly report. Many speculators have enough of this factor to start selling. For a long-term investor, this is a signal that the average purchase price can be well averaged (to buy additional paper at a lower price) or to rebalance.
Technical part
Since I don’t like to sit down at the terminal, and my broker does not provide trend tracking functions, I decided to study the available description of the Moscow Exchange API , the query guide and write a script that will inform me about the trend change for the tools I’m interested in (read all securities of which the portfolio consists ") by mail.
To begin with, a small class was written:
Class code
classemitent{ public $name; public $cost; // public $trand; // public $closeCost; // public $average50; // 50 public $average15; // 15 public function getPrice($emitent,$format){ $uri = 'https://iss.moex.com/iss/engines/stock/markets/shares/securities/'.$emitent.$format; $result = file_get_contents($uri); $resultObject = json_decode($result,true); /* @var $resultObject type */ $this->cost = $resultObject['marketdata']['data'][2][12]; return $this->cost; } public function getAverage50($emitent,$format){ $historyPrice = []; $historydata = []; $date1 = date("ymd",strtotime("-1 days")); $date2 = date("ymd",strtotime("-100 days")); $uri = 'https://iss.moex.com/iss/history/engines/stock/markets/shares/boards/TQBR/securities/'.$emitent.$format.'?from='.$date2.'&till='.$date1; $result = file_get_contents($uri); $resultObject = json_decode($result,true); $historydata = $resultObject['history']['data']; $historydata_reverse = array_reverse($historydata); for ($i=0;$i<50;$i++){ array_push($historyPrice,$historydata_reverse[$i][11]); } $average50 = array_sum($historyPrice)/count($historyPrice); return $average50; } public function getAverage15($emitent,$format){ $historyPrice = []; $historydata = []; $date1 = date("ymd",strtotime("-1 days")); $date2 = date("ymd",strtotime("-50 days")); $uri = 'https://iss.moex.com/iss/history/engines/stock/markets/shares/boards/TQBR/securities/'.$emitent.$format.'?from='.$date2.'&till='.$date1; $result = file_get_contents($uri); $resultObject = json_decode($result,true); $historydata = $resultObject['history']['data']; $historydata_reverse = array_reverse($historydata); for ($i=0;$i<15;$i++){ array_push($historyPrice,$historydata_reverse[$i][11]); } $average15 = array_sum($historyPrice)/count($historyPrice); return $average15; } }
From the subtle points that I took from the directory:
History - request prices from the desired period of time Stock - trading system (engines) "Stock market and deposit market" Shares - specific market (markets) "Stock Market" TQBR - specific trading mode (boards) "T + Promotions and DR"
Server response is either json or xml. You get an array of data. The data in the array may vary depending on the request you are sending. The descriptions of the array fields are stored in the same data in the “COLUMNS” block. Values ​​- in the "DATA" block.
A full description of all the fields relating, for example, to the stock market, can be viewed on this page . (By the way, I found this description only when preparing the article).
Comment. If you take a period of more than 100 days, then you need to make several requests there by moving the array pointer. The situation is described on the last page of the Moex API manual.
After that, the script itself was written ( for the quality of the code with sticks, please do not beat ):
It receives from the json array, in the same folder, a list of tickers and a trend direction label. Requests prices for the specified time intervals and calculates the values ​​of simple moving averages by the formula:
Where P is the closing price, and n is the number of time intervals for which price values ​​are taken.
Next, it determines the current direction depending on whether the value is smaller or smaller than the average (15-day) than the large value (50-day). It compares the current direction with the saved one and sends a notification to the mailbox when the value changes. Then I open the news by ticker and analyze the situation.
Total
The exchange provides access to information for free, with a delay of 20 minutes. For intra-day speculation, the data is not suitable, but to write any tools that will help make decisions in the medium term is very good. On the move, for example, an indicator of reaching the target price. Many brokers and consultants post recommendations on target prices in open access and you can easily write a script that will track the price. In yahoo.finance, for example, this tool first broke, and then it was completely removed. Also, public overseas services crookedly receive information about the prices of our issuers.
I hope this information will help you in the future more convenient to control your portfolio, as it helped me.
PS I want to note that trend monitoring refers to the technical analysis of stocks. Many fundamental investors have a negative attitude towards TA, considering it to be fortune-telling, prediction, etc. But my point of view is that TA is more likely an assistant investor in decision making, only confirming any hypothesis. But in any case, not a tool for peremptory approval. As they like to repeat in the environment of non-professional financial consultants, everything written above is not a guide to action and a recommendation for making deals.