Wednesday, January 4, 2023

SQL To Calculate Volatility

 I looked at different sites to find an easy formula to calculate stock volatility. Everybody is using Excel or some specialized software. In all cases, calculation is done for one position only. I wrote the following query to calculate volatility for all stocks in the database:

select t.id, t.currticker, 

       stddev(ln(p.close_price/p1.close_price)) * sqrt(252) volatility

from tickers t, prices p, prices p1

where t.id = p.tickerid

  and t.id = p1.tickerid

  and p1.trade_date = (select max(p2.trade_date) from prices p2

               where p2.tickerid = t.id

         and p2.trade_date < p.trade_date)

  and p.trade_date between current_date - 31 and current_date - 1

group by t.id, t.currticker


This query work on Postgresql (Version 12 and up, should work on earlier versions as well). To use Oracle, replace current_date with trunc(sysdate).  To use with MS SQLServer or mysql you nned to change date functions as well.

Tables and columns used:

tickers: table of stocks, 

  columns: id: internal id,

                 currtickers: stock ticker.

prices: daily stock prices, adjusted for splits,

  columns: tickerid: ticker id

                 close_price: ptice at closing,

                 trade_date: self-explaining.

This SQL calculates annualized volatility for the last 30 calendar days the way it's calculated on most financial sites. You can change parameters in the WHERE clause to change the range.

Thursday, May 12, 2022

The End of Cheap Labor

 Labor shortages everywhere. Not only in US, everywhere in the developed world. Lots of blame going around. Some blame COVID-19, some blame politicians. But problem is much deeper, than it appears at the first glance.

First, let's take a look at the US resident population pyramid:


We can see that the biggest age groups are 50 to 60 years old and 20 to 35 years old. Obviously, 50 to 60, that's the tail part of baby boomer generation (older boomers are gradually dying out). 20 to 35 are their children. This is the new labor force coming to market right now.

Overall picture is clear: we don't have any room for labor expansion in US, except immigration. Which is politically unpopular and repressed.

But we also know, that in the last 40 years (if not more) wages stagnated, with exception of the last 7-8 years. And that stagnation was the worst at the lowest level of wages. How do we reconcile those two pieces of information? Simple. Starting beginning of 1980s, China opened to the outside world. Adding almost a billion people to the world labor force. Rich countries moved a lot of production to China, depressing wages at home. But market works both ways. Wages in the rich countries have been depressed, but wages in China grew. 

There are still some potential to tap into cheap labor. There is a fast population growth in Africa. But businesses are reluctant to move production there because of political instability in most countries. And in stable countries, surprise!, population growth is mostly over as well.

There are only two ways to handle the current situation:

1. Permanent stagnation, obviously preferred by some business leaders, who wants hard money policies regardless of economic situation.

2. Policies, increasing labor participation and immigration. Which includes government sponsored child care, more government involvement in healthcare.

Of course, partially labor shortage can be solved by increased productivity, which requires increased investment from businesses. I will believe it when I see it. Last 20 years, most businesses tried to invest into productivity as little as possible. And again, in stagnation situation this won't happen, ever.


Wednesday, September 9, 2020

How To Destroy US Economy In Three Easy Steps

 OK, I admit, destroy is a way too strong a word here. Rather than being destroyed, US ecomony is on the way of becoming 3rd world economy. Something like Brasil. Or Honduras. Your choice.

What is the main difference between US economy and economies of less developed countries? I mean now, not 50 years ago? The answer is simple: Silicon Valley. Nobody can match the rate of innovation coming mostly from Northern California. 

Why is it happening? Brains. There are 3 universities in Northern California pulling the best brains from all over the world: Berkeley, Stanford and California Institute of Technology (Caltech). These brains create innovative companies, go to work for these companies, they created Silicon Valley as we know it. 

What do you need to do in order to destroy Silicon Valley? Restrict flow of brains. It's much easier done than you think.

Step 1: restrict visas for foreign students. Already done in 2018. Should I mention that these three universities only accept the brightest of the brightest? Why would US Government restrict the brightest from our universities? I have no idea. But it's done.

Step 2: restrict work visas. First of all, visas for internship. Not long ago, students could receive internship visa almost automatically if they have a job offer in US. Now it's almost impossible. And, of course, H-1B visas, which allow foreign employees work in US. Again, now it's practically impossible to get H-1B visa after internship visa expires, employee has to go to the home country and apply from there. The number of H-1B visas is very limited, so again, if a bright student somehow managed to get internship visa and started working for some innovative US company, after some time he or she has no choice, but return to the home country. Of course, current government has an explanation: we want America and Americans first. The only problem is that is a lie. Foreign contractors, not necessary the brightest, are easily and without many restrictions get L1 visas (transfer within company). 

Step 3: start trade wars and break up the Internet. We live in a globalized world. You can't fence yourself and be a competitive economy. But current government started trade wars with China and EU anyway. And now it's trying to create barriers in the Internet. For 30+ years US tried to keep the Net open and available for everybody, now government behaves almost like Chinese government. US government ordered video service TikTok to sell US operations to US company or to be shut down. Not many people know the history of Presidents rage: TikTok users pretended to sign up for Trump's rally in Tulsa, OK, and, of course, didn't come. US based TikTok users. Now government tries to tell us that TikTok sends user data back to China. Any proof? You can easily analyze net traffic. If it's encrypted, get the warrant and analyze it before encryption. We have US government behaving like some African government.

Of course, there is inertia. Of course, there are thousands of world class companies in Silicon Valley which aren't going anywhere any time soon. But damage is done. You can expect the rate of innovations to go down, you'll see less innovative companies created here. Decay takes time.

And remember, without Silicon Valley US is a 3rd world economy. There is nothing else which would make it outstanding in the world.


Wednesday, November 9, 2016

Trump Won. Now What?

First, several self-evident facts (you can search internet if you don't believe me).

During democratic presidencies stocks grow much better than during republican.

Any attepmt to restrict imports into US under any pretext will cause trade wars, which would really cost US hundreds of thousands, if not millions, of jobs, and a lot of investment income (or cause investment loss).

Current low interest rate environment is not a fluke. It's a consequence of demographics in the developed world. I don't see how this can be changed by any government. Any attempt to significantly raise rates is going to be disastous.

Changes in strategy

My current cash position is around 25%. Going to increase it to around 30%

I have too much money invested in conventional companies. Now it's mostly dead money. Most of new investment is going to networked economy. The only exception is defence sector. GOP, in their very non-corrupt wisdom, is going to throw a lot of money there (there is a consensus between Trump and other elected GOP members). Going to sell rallies. First candidates are conventional companies with significant exports.

Because I'm close to retirement age, I already moved a lot of money into fixed income CEFs. I am going to increase that portion. All talks about bond crush is huge BS. Yes, effective yields on bonds are going to go down and that requires some careful management.

Significant portion of money should go abroad, one way or another. So far, I used ADRs, looking for other opportunities.

Monday, February 29, 2016

Tell Warren Buffet: I Can Sleep On His Matress

Today Warren Buffet said the following: "Berkshire Hathaway is sitting with billions of dollars of euros in an insurance company ... in Europe and they will bear a negative rate. We would be better off with a big mattress in Europe that we just stick all this stuff in, if I could just find a person I trusted to sleep on that mattress." Quoted from here:
http://www.cnbc.com/2016/02/29/warren-buffett-were-a-more-aggressive-buyer-of-stocks-when-theyre-going-down.html
Well, tell Warren he's got his man (and woman, my wife). No problem, Berkshire Hathaway puts that mattress in some nice home somewhere in Europe, pays for the house, utilities and protection. And I just live here. I will sign an obligation to sleep on the mattress with money, no problem.
But come on! I don't understand why such a great investor keeps idiots to manage his money in Europe. There are a lot of different tools, all bearing interest, to keep your money in. You can invest in sovereign funds (well, Germany is effectively at zero interest, but it's not the only country in Euro zone). There are sub-soveregns (what we call munies in US), issued by provinces and municipalities. There are corporate notes, lots of which are issued by reliable, well-capitalized and profitable companies. What's the problem?
It's a problem for US retail investor. I'm looking for the last several years for some funds investing in Euro debt, and found essentially nothing. There are several funds, but in countries I'm not interested. When PIIGS panic hit (concerns about sovereign debts of Portugal, Italy, Ireland, Greece, Spain), I was ready to buy all of them with exception of Greece, didn't see any tools. Now I'd love to invest in sub-sovereigns, nothing.
For Berkshire Hathaway, having billions and established management in Europe, it's not the problem of finding investments. It's a problem of management. I bet I can find a lot of tools and build a good debt ladder for anything Berkshire can throw at it. European debt market is not as big as ours, but it's for sure orders of magnitude bigger than what Berkshire Hathaway has.

Wednesday, February 10, 2016

Why I Bought PayPal

Bought PayPal (PYPL) yesterday. Wanted to buy this great company for a long time, but didn't like the price. Now price is OK. Doesn't mean it can't go lower, nothing is certain. But fast growing company, part of internet financial revolution, trading at less that 20 future P/E and PEG 1.20 is cheap in my view.
There are several new growth areas for a company. First of all, now many companies offer PayPal as an option when paying for online purchases. Second is xoom.com. If you transfer money between countries, you know how outrageously expensive it is for small amounts. Xoom lets you transfer money much cheaper at better currency conversion rates that alternatives.
There are companies on the receiving side as well. I don't know how long Moneygram (MGI) and Western Union (WU) can survive. MGI, in my opinion, is walking dead. WU has bigger reach and a lot of loyal customers. I think those loyal customers are growing old and dying, and company will be dying with them.

Full disclosure: I have long position in PYPL and no positions in MGI and WU.

Saturday, January 23, 2016

Market Is Down. Now What?

Correct answer is "I don't know". Of course. I thought that Wednesday intra-day drop of more than 500 Dow points is a capitulation. Maybe even THE capitulation. Which signifies the end of bear market and a start of a new bull one. But there is one interesting fact which goes against it. Bottom on that day happened exactly at 2:30 ET. That was the time of Feb WTI futures expiration. Oil futures roll over usually doesn't create huge drop at expiration, although some analysts claim that's what happened. It looks like some huge dump of contracts in which buyer had to take delivery, but didn't want to. It also appears that a lot of trading algorithms are currently trained to trade stock ETFs in line with oil. It shouldn't be this way, but if high frequency guys use neural networks algos, that's how such networks would react, according to the last several months of trading. Unfortunately, HFT is the majority of trading now. Not complaining, just clarifying the reality in which we trade.
OK, so what is the current situation? China is in a big trouble. Widely advertised turn to consumer economics isn't happening. At the same time, workforce in the country is not the cheapest in the world anymore, banking system is still doesn't really exist, and nobody believes government statistics. Some analysts wonder why volatility of Chinese market affects much bigger US one. The answer is simple: hedge funds invested in China are getting margin calls and selling whatever they can. Plus HFT algos are doing their thing, magnifying the effect.
Next elephant in the room: sovereign wealth funds of oil producing countries. These funds are huge net sellers of everything they own in the last 6 months. They have to, budgets of these countries need money now. Of course, this selling is also magnified by algos.
Last, but not least, is a bunch of idiot fund managers invested in commodities (especially oil futures). They are losing money hand over fist, need to sell something to avoid margin calls, so they sell stocks and bonds.
Market direction will be defined by money balance, as usual. On one side above mentioned sellers. On the other side multiple funds investing money long term, not bothering with trading. In the long term, bulls always win. The main question: when sellers are going to be exausted?
Interesting trivia. I watched Rose Bowl Parade this year and was surprised how many bears were on the floats. Never seen that many.