Quarterly Results Analysis with Python

Every quarter when results come out, I spend sufficient hours looking at the financial results of the stocks I am tracking to elicit nagging comments from my better half. So developed this simple python script which does the analysis and generates me the PDF which I email to myself to look at during office commute.

The code as always is available at my github page here.

Some sample plots

Intend to update the scripts for other analysis as and when I get some time.

It’s there to serve you, not to guide you

 stock market 
My colleague is a hard core trader. He intellectually understands the Gardner mentality to investing but doesn’t believes in it.
Most of his investing is based on momentum and he trades on news. 

With the recent crush his trades like many have decreased and he is daily looking at the market movement trying to guess if it will rebound or see a new lower bottom. 

Today as we were discussing markets, got reminded of the following Berkshire letter of 1987 about market. 

From: 1987 letter 
Ben Graham, my friend and teacher, long ago described the mental attitude toward market fluctuations that I believe to be most conducive to investment success. He said that you should imagine market quotations as coming from a remarkably accommodating fellow named Mr. Market who is your partner in a private business. Without fail, Mr. Market appears daily and names a price at which he will either buy your interest or sell you his.

Even though the business that the two of you own may have economic characteristics that are stable, Mr. Market’s quotations will be anything but. For, sad to say, the poor fellow has incurable emotional problems. At times he feels euphoric and can see only the favorable factors affecting the business. When in that mood, he names a very high buy-sell price because he fears that you will snap up his interest and rob him of imminent gains.

At other times he is depressed and can see nothing but trouble ahead for both the business and the world. On these occasions he will name a very low price, since he is terrified that you will unload your interest on him.

Mr. Market has another endearing characteristic: He doesn’t mind being ignored. If his quotation is uninteresting to you today, he will be back with a new one tomorrow. Transactions are strictly at your option. Under these conditions, the more manic-depressive his behavior, the better for you.

But, like Cinderella at the ball, you must heed one warning or everything will turn into pumpkins and mice: Mr. Market is there to serve you, not to guide you. It is his pocketbook, not his wisdom, that you will find useful. If he shows up some day in a particularly foolish mood, you are free to either ignore him or to take advantage of him, but it will be disastrous if you fall under his influence. Indeed, if you aren’t certain that you understand and can value your business far better than Mr. Market, you don’t belong in the game. As they say in poker, “If you’ve been in the game 30 minutes and you don’t know who the patsy is, you’re the patsy.”

Ben’s Mr. Market allegory may seem out-of-date in today’s investment world, in which most professionals and academicians talk of efficient markets, dynamic hedging and betas. Their interest in such matters is understandable, since techniques shrouded in mystery clearly have value to the purveyor of investment advice. After all, what witch doctor has ever achieved fame and fortune by simply advising “Take two aspirins”?

The value of market esoterica to the consumer of investment advice is a different story. In my opinion, investment success will not be produced by arcane formulae, computer programs or signals flashed by the price behavior of stocks and markets. Rather an investor will succeed by coupling good business judgment with an ability to insulate his thoughts and behavior from the super-contagious emotions that swirl about the marketplace. In my own efforts to stay insulated, I have found it highly useful to keep Ben’s Mr. Market concept firmly in mind.

Following Ben’s teachings, Charlie and I let our marketable equities tell us by their operating results – not by their daily, or even yearly, price quotations – whether our investments are successful. The market may ignore business success for a while, but eventually will confirm it. As Ben said: “In the short run, the market is a voting machine but in the long run it is a weighing machine.” The speed at which a business’s success is recognized, furthermore, is not that important as long as the company’s intrinsic value is increasing at a satisfactory rate. In fact, delayed recognition can be an advantage: It may give us the chance to buy more of a good thing at a bargain price.

Living With The Black Swan


From about 2000 years, in many European languages, a black swan was a metaphor for something that was clearly impossible. And then black swans were found in Australia. So a black swan became a metaphor for a completely unexpected event actually occurs, one we had not imagined was impossible. Black swans appear regularly – Skype, iPhone, the Cloud…. If a black swan landed in your marketplace, would you recognize it? Most companies don’t. It’s no coincidence that the average age of companies – big companies – is falling fast, at the same time that black swan events are increasing.

You never see black swans coming – you have to be ready to respond when they arrive. 

This talk is about the kind of thinking and organizational structure that can help you live successfully with the black swans. It is about how to build an innovative, responsive, enduring organization

Goes well with this post on antifragile.

Inspite of the environment and not because of it


Here’s a stab from Rohit Chauhan’s model portfolio update.

As an investor, our portfolio cannot be built on hope. As a result, i am not picking or retaining stocks based on some macro event or grand thesis playing out (restructuring of PSU or removal of subsidies etc). I would like to hold companies in the portfolio which can perform inspite of the environment and not because of it.

All my investor/trader buddies are excited about the recent bull run and the prospect of Modi as PM.

Exact words that I want to convey to my enthusiastic investor buddies!!

Totally agree with him. And interestingly this applies not just to stocks! Just substitute portfolio with career!!

Uncertainty is the friend of the buyer of long-term values

I am half way with this excellent book, The Warren Buffett Portfolio by Robert G. Hagstrom. Here are some of the most popular highlights by Kindle users from amazon.com for this book.

Loved the idea of viewing building a portfolio to building a company!!

Buffett does not adjust the discount rate for uncertainty. If one investment appears riskier than another, he keeps the discount rate constant and, instead, adjusts the purchase price.

Review annual reports from a few years back, paying special attention to what management said then about strategies for the future. • Compare those plans to today’s results: How fully were they realized? • Compare the strategies of a few years ago to this year’s strategies and ideas: How has the thinking changed? • Compare the annual reports of the company you are interested in with reports from similar companies in the same industry. It is not always easy to find exact duplicates, but even relative performance comparison can yield insights.

Buffett tells us that, in a low-interest-rate environment, he adjusts the discount rate upward. When bond yields dipped below 7 percent, Buffett adjusted his discount rate up to 10 percent. If interest rates work themselves higher over time, he has successfully matched his discount rate to the long-term rate. If they do not, he has increased his margin of safety by three additional points.

“The goal of each investor,” says Buffett, “should be to create a portfolio (in effect, a `company’) that will deliver him or her the highest possible look-through earnings a decade or so from now.”

“Charlie and I let our marketable equities tell us by their operating results-not by their daily, or even yearly, price quotations-whether our investments are successful,” explains Buffett. “The market may ignore business success for a while, but it eventually will confirm it.”

“Take the probability of loss times the amount of possible loss from the probability of gain times the amount of possible gain. That is what we’re trying to do,” says Buffett. “It’s imperfect, but that’s what it is all about.”

“You are neither right nor wrong because the crowd disagrees with you. You are right because your data and reasoning are right.”

“Face up to two unpleasant facts: the future is never clear and you pay a very high price in the stock market for a cheery consensus. Uncertainty is the friend of the buyer of long-term values.”

“Your goal as an investor should be simply to purchase, at a rational price, a part interest in an easily understandable business whose earnings are virtually certain to be materially higher, five, ten, and twenty years from now,” explains Buffett. “Over time, you will find only a few companies that meet these standards-so when you see one that qualifies, you should buy a meaningful amount of stock.”

Warren Buffett applies three tenets about a company’s management: (1) rationality, (2) candor, and (3) resisting the institutional imperative.

And then there was this mention of uncertainty, how could I resist? 🙂

A Simple Fortran code to Simulate Stochastic Stock Price Movement

Stochastic_Stock_fortran_ProgramA few months ago I posted this pgplot powered fortran animation program on calculating the approximate value of PI by Monte Carlo method using random numbers.

And the other found myself reading about random or stochastic phenomenons. After reading about stochastic processes, I was invariably reminded of the stock market. The most stochastic place one can imagine.

After a bit of googling and a bit of tinkering, created the following program.

Given the annual drift, volatility, initial price and number of trials, the program simulates the movement of a stock price.

     program MonteCarloStocks
     double precision a,b,c
     character(len=100) buffer
     integer i,n,noarg,IARGC

     if(noarg == 4) then     
       CALL GETARG (1, buffer)
       read(buffer,'(f6.2)') a
       CALL GETARG (2, buffer)
       read(buffer,'(f6.2)') b
       CALL GETARG (3, buffer)
       read(buffer,'(f6.2)') c
       CALL GETARG (4, buffer)
       read(buffer,'(i7)') i
       print *, a,b,c,i
       write(*,'(a)',advance='no') "Please enter annual drift :"
       write(*,'(a)',advance='no') "Please enter annual Volatility :"
       write(*,'(a)',advance='no') "Please enter Initial Price :"
       write(*,'(a)',advance='no') "Please enter no of iteration :"
     end if
     call monte(a,b,c,i)
     call system("stock.xls")
     end program
     subroutine monte(driftyearly,volatility,initialprice,not)
     double precision driftyearly,volatility,initialprice
     double precision driftdaily,voldaily,p,pri(252),PPND16
     integer,parameter :: nod=252
     integer not
     driftyearly = driftyearly/100
     volatility  = volatility/100
     call random_seed
     if(not <= 0) not=1
     if(not >=25000) not =25000
     do j=1,not
        do i=2,nod
         call random_number(p)
         p=PPND16 (p, IFAULT)
         end do
     end do    
     end subroutine

!	ALGORITHM AS241  APPL. STATIST. (1988) VOL. 37, NO. 3
!	Produces the normal deviate Z corresponding to a given lower
!	tail area of P; Z is accurate to about 1 part in 10**16.
!	The hash sums below are the sums of the mantissas of the
!	coefficients.   They are included for use in checking
!	transcription.
     		CONST2, A0, A1,	A2, A3, A4, A5, A6, A7, B1, B2, B3, &
                B4, B5, B6, B7,                                 &
     		C0, C1, C2, C3, C4, C5, C6, C7,	D1, D2, D3, D4, D5, &
     		D6, D7, E0, E1, E2, E3, E4, E5, E6, E7, F1, F2, F3, &
     		F4, F5, F6, F7, P, Q, R
	PARAMETER (ZERO = 0.D0, ONE = 1.D0, HALF = 0.5D0,           &
     		   SPLIT1 = 0.425D0, SPLIT2 = 5.D0,                 &
     		   CONST1 = 0.180625D0, CONST2 = 1.6D0)
!	Coefficients for P close to 0.5
	PARAMETER (A0 = 3.3871328727963666080D0, &
     		   A1 = 1.3314166789178437745D+2,&
!	HASH SUM AB    55.88319 28806 14901 4439
!	Coefficients for P not close to 0, 0.5 or 1.
	PARAMETER (C0 = 1.42343711074968357734D0,&
!	HASHSUMCD49.33206503301610289036
!	CoefficientsforPnear0or1.
!	HASH SUM EF    47.52583 31754 92896 71629
	Q = P - HALF
	  R = CONST1 - Q * Q
	  PPND16 = Q * (((((((A7 * R + A6) * R + A5) * R + A4) * R + A3)  &
     			* R + A2) * R + A1) * R + A0) /  &
     		      (((((((B7 * R + B6) * R + B5) * R + B4) * R + B3)  &
     			* R + B2) * R + B1) * R + ONE)
	    R = P
	    R = ONE - P
	    IFAULT = 1
	    PPND16 = ZERO
	  R = SQRT(-LOG(R))
	    R = R - CONST2
	    PPND16 = (((((((C7 * R + C6) * R + C5) * R + C4) * R + C3)  &
     			* R + C2) * R + C1) * R + C0) /  &
     		     (((((((D7 * R + D6) * R + D5) * R + D4) * R + D3) &
     			* R + D2) * R + D1) * R + ONE)
	    R = R - SPLIT2
	    PPND16 = (((((((E7 * R + E6) * R + E5) * R + E4) * R + E3)  &
     			* R + E2) * R + E1) * R + E0) /  &
     		     (((((((F7 * R + F6) * R + F5) * R + F4) * R + F3)  &
     			* R + F2) * R + F1) * R + ONE)
	  IF (Q .LT. ZERO) PPND16 = - PPND16

Cool I would say.

An example of Monte Carlo method in action.


For a change, I am posting a poem that was written by Rudyard Kipling in 1895.

I liked this when I first read it in school, but today read it and saw in the context of value investors. Liked it more.

One of my favourite poems in the English language 🙂

If you can keep your head when all about you
Are losing theirs and blaming it on you;
If you can trust yourself when all men doubt you,
But make allowance for their doubting too:
If you can wait and not be tired by waiting,
Or being lied about, don’t deal in lies,
Or being hated don’t give way to hating,
And yet don’t look too good, nor talk too wise;

If you can dream—and not make dreams your master;
If you can think—and not make thoughts your aim,
If you can meet with Triumph and Disaster
And treat those two impostors just the same:
If you can bear to hear the truth you’ve spoken
Twisted by knaves to make a trap for fools,
Or watch the things you gave your life to, broken,
And stoop and build ’em up with worn-out tools;

If you can make one heap of all your winnings
And risk it on one turn of pitch-and-toss,
And lose, and start again at your beginnings
And never breathe a word about your loss:
If you can force your heart and nerve and sinew
To serve your turn long after they are gone,
And so hold on when there is nothing in you
Except the Will which says to them: ‘Hold on!’

If you can talk with crowds and keep your virtue,
Or walk with Kings—nor lose the common touch,
If neither foes nor loving friends can hurt you,
If all men count with you, but none too much:
If you can fill the unforgiving minute
With sixty seconds’ worth of distance run,
Yours is the Earth and everything that’s in it,
And—which is more—you’ll be a man, my son!

Darwin Portfolio – How Charles Darwin Can Help Build a Stock Portfolio

Darwin Portfolio

A post on Charles Darwin by a friend reminded me an approach I am experimenting in terms of cleaning my stock portfolio.

As I have discussed here, I am a Gardener now when it comes to investing. I find selecting and buying lot easier than selling.

For buying I have a system or at least a framework but selling lacks any systematic approach. So while reading the book Seeking Wisdom from Darwin to Charlie Munger by Peter Bevelin,I thought of taking Darwin’s help.

Now every quarter and during annual results, I assess the stocks in my portfolio using 4 variables, ROE, Cash by Net Profit, Debt to Equity and growth of each additional rupee invested.

Gather this data into this Excel sheet and then rank them. Consistent lower ranks are the ones that need to go. So Darwin’s survival of the fittest in action. I also use this sheet to evaluate a potential new stock for the portfolio.

Getting this sheet populated is simple, hard part is acting on the information it reveals. .

Here’s the excel sheet if anyone is interested.

My Favourite Quotes by Warren Buffett

I was looking at my stock portfolio’s performance today. Latter that activity led me to revisit some of my favourite quotes by Warren Buffett !!

My current most fav one is in bold. Which one do you like the most?


  • If past history was all there was to the game, the richest people would be librarians.
  • Chains of habit are too light to be felt until they are too heavy to be broken.
  • You only have to do a very few things right in your life so long as you don’t do too many things wrong.
  • When you combine ignorance and leverage, you get some pretty interesting results.
  • Risk comes from not knowing what you’re doing.
  • I don’t look to jump over 7-foot bars: I look around for 1-foot bars that I can step over.
  • In the business world, the rearview mirror is always clearer than the windshield.
  • Price is what you pay. Value is what you get.
  • Wall Street is the only place that people ride to in a Rolls Royce to get advice from those who take the subway.
  • Time is the friend of the wonderful company, the enemy of the mediocre.
  • Should you find yourself in a chronically leaking boat, energy devoted to changing vessels is likely to be more productive than energy devoted to patching leaks.
  • A public-opinion poll is no substitute for thought.
  • Someone is sitting in the shade today because someone planted a tree a long time ago.

Are You a Gardener or Gambler ?

The other day, we were discussing investing in stock market across the lunch table. Everyone was recounting their experience with the market. Some did it once and are out. Some do it everyday and are making decent profit. Some invest for long term and forget.

As the discussion continued, I realised, there are basically two groups at that table. Gamblers and Gardeners. Those who see market as a gambling table and the one who treat it as a garden. Though gamblers outnumber gardeners.

As the discussion progressed, I pondered about my journey in investing. When I began investing especially in market, I looked at it as a gambler and my initial investments, though based on fundamentals were biased with recent speculation about the stock. My views were coloured. And my aim at that time was to get quick profits and re invest.

Thankfully the mindset has shifted and now my investing attitude is more of a Gardener. I see building a portfolio as planting seeds and tending them. I try not to speculate and only invest when I find value. This attitude doesn’t require daily work but just like a Gardener, requires tending, de-weeding and watering.

What do you think?
Are you a Gardener or Gambler when it comes to investing? What is your investing style?

Are You a Bayesian Investor?

Bayesian investor.jpg
Before you answer that, lets understand the Philosophy of Bayesian Inference with this simple example.

You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, even more difficult, test too! You are starting to believe that there may be no bugs in this code…

If you think this way, then congratulations, you already are a Bayesian practitioner! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident.

Via CamDavidsonPilon

Wells that’s it. If you invest based on evidence and use qualitative assessments rather than emotional speculation, you are a Bayesian Investor.

I, for one, am trying to follow this path, though not there yet!! Don’t use statistic and curves much but I do have a few quantitative metrics than I run through before digging deeper!!!

More on Bayesian_inference on Wikipedia