Lame joke: A physicist, mathematician and engineer …

It might be unknown by many of you that I have a PhD in mathematics and work in the Oil & Gas industry. After all these years the latter field, I am actually trying to gain some knowledge of Oil & Gas. It is hard for me, as I rate myself as being extremely poor at acquiring knowledge. My brain is quite old now, so often it is a case of information going in one synapse and out the other. O&G has a lot of engineering discipline surrounding it, and, what with my recent mathematical musings, it brings to mind an old joke about a physicist, mathematician and engineer. It goes something like this …

So, a physicist, mathematician and engineer were asked to find the volume of a big red rubber ball. The physicist drops the ball into water, and measures the volume of water displaced. The mathematician gets some calipers, measures the diameter of the ball, and calculates the volume mathematically. The engineer, on the other hand, picks up the ball, writes down its serial number, and looks up the volume in the big red rubber ball specification table.

Well, I didn’t necessarily say that it was a funny joke.

Posted in Uncategorized | 1 Comment

Simplification of defuzzification in Fuzzy Logic

I have just noticed that my article on Datalog has had far more hits than my articles normally do. The unit conversion program arose because I was interested in another problem: preparing sets of accounts and investment track records. I have written a C program that already does that, but I am thinking of investing in the US market, and that introduces the problem of currency exhange. It raises the question: “how much is a share worth?”. The answer to that question is dependent on time, the value of a share, and the exchange rate. There is nothing necessarily especially difficult about programming a deterministic solution oneself, but it is the kind of problem that lends itself well to Datalog. It is a topic that I may well return to in a later post.

In the meantime, the whole point of my post is to throw out some ideas I had about Fuzzy Logic. Being an investor, I am interested in decision-making processes, and how mathematics and statistics might give me an edge. I am very very new to Fuzzy Logic, and still trying to absorb some basic terminology, and even underlying ideas.

So, it may seem a little presumptuous to say that I have some ideas that may contribute to the field of Fuzzy Logic. To that end, I have written a little article entitled “Simplification of defuzzification in Fuzzy Logic”. Its abstract is:

In the traditional Fuzzy Logic approach, each consequent is expressed as a fuzzy set. Typically, these sets are combined to form a complex shape whose COG (Centre of Gravity) is computed. This article argues that fuzzy consequents can be replaced by crisp consequents. By partitioning the solution space, a lot of elaborate modelling and computation is removed. An example is shown in which the simplified approach gives an answer which is very similar to a more elaborate process.

The article has lots of mathy-type terms, so I can’t really produce the content here. You can download or view a PDF version straight from my site, though: . Some knowledge of Fuzzy Logic is assumed, so don’t expect to be able to pick it up without knowing something about the field. I intend to write an introductory article for the complete beginner at some point. So, my apologies in advance if it is not quite the material you were hoping for. Be warned: I am terrible at reviewing my own work. There may well be inaccuracies in it. To me, the fun is more in coming up with the ideas than in the spell-checking.

I feel as if I am only just dipping below the surface of some of these concepts, and believe there may be some unification between Fuzzy Logic, Bayesian reasoning, and naive heuristic algorithms waiting to be uncovered.

I would really like to extend a huge “thank you” to the readers of my blog.


Posted in Uncategorized | Leave a comment

Logic programming example: unit conversion using Datalog

Logic programming can reduce your code size, and make deductions based on facts. I’ll illustrate this using pyDatalog, a Datalog implementation in Python 3, to create a unit conversion program. I provide it wil some basic facts about how many meters, miles and feet there are in an inch, together with two conversion rules. Using those rules, I can use Datalog to “automagically” convert between any two units, even though I haven’t explicitly told it how to perform the conversion.

Let’s start with the completed code first:

from pyDatalog import pyDatalog
from pyDatalog.pyDatalog import create_terms as terms
from pyDatalog.pyDatalog import ask

pyDatalog.create_terms('scale') # the long way of doing it
terms('A, B, C, V')

scale['meter', 'inch'] = 39.3700787
scale['mile', 'inch'] = 63360.0
scale['feet', 'inch'] = 12.0

scale[A, B] =  1/scale[B, A]
scale[A,B] = scale[A,C] * scale[C, B]

print(scale['inch', 'meter'] == V)
print(scale['mile', 'meter'] == V)

conv[V, A, B] = V * scale[A, B]
print(conv[3, 'mile', 'meter'] == V)
print(conv[1, 'meter', 'feet'] == V)

There is a division bug in pyDatalog v 0.14.6, so if you want to run the example, you will need to check out changeset b1a5df9 until a new version is released.

Now let me walk through the code. First, I import the pyDatalog module, and define some convenience functions:

from pyDatalog import pyDatalog
from pyDatalog.pyDatalog import create_terms as terms
from pyDatalog.pyDatalog import ask

Next, let’s create some terms: scale, which is a function (actually a term) where we specify how one unit relates to another, and A,B,C, V, which we think of as matching “variables”:

pyDatalog.create_terms('scale') # the long way of doing it
terms('A, B, C, V')

Then, let use give some facts about how to scale between various units:

scale['meter', 'inch'] = 39.3700787
scale['mile', 'inch'] = 63360.0
scale['feet', 'inch'] = 12.0

So, these facts state that 1 meter has 39.3700787 inches, and so on. They look like functions, but they are in fact terms:

In [3]: type(scale)
Out[3]: pyDatalog.pyParser.Term

The same applies for A, B, C, and V. So far, so good. But what if we want to convert, say, inches into meters instead of meters into inches? Then we need an inverse rule:

scale[A, B] =  1/scale[B, A]

Let’s test it:

In [5]: print(scale['inch', 'meter'] == V)

Datalog has used the inverse rule to “go the other way”. There is some minor magic going on here. Note that we didn’t specify which fact to use for inversion, Datalog figured it out for itself.

Now let’s cast some real magic. Specify a transition rule:

scale[A,B] = scale[A,C] * scale[C, B]

which states that you can get from unit A to B if there exists another unit C that serves as an intermediate conversion. Now test it:

In [6]: print(scale['mile', 'meter'] == V)

Good. It’s cleverness doesn’t stop there:

In [7]: scale['league', 'mile'] = 3.45233834

In [8]: print(scale['league', 'meter'] == V)

Notice how there is no simple way to convert from leagues to meters. Datalog must deduce a chain of transitions in order to obtain the result.

To round things off, let’s define a convenience function, “conv”, which converts V units in A into units of B:

conv[V, A, B] = V * scale[A, B]

Perhaps we could have used a simple python function for that, but let’s keep with the paradigm. We can then ask questions like: what is 3 miles in meters:

In [9]: print(conv[3, 'mile', 'meter'] == V)

Bon apetitite.

Posted in Computers | Tagged , , | Leave a comment

#encfs – easy userspace file encryption on Linux

BLUF: encfs provides unfussy user-level mount/unmount of an encrypted directory that can be migrated across machines.

Ah, encfs, where have you been all my life? I have been storing passwords in Keepassx. It is an excellent cross-platform password manager, but it is GUI-only. It is also not a file storage mechanism. I like to access passwords from the command line, and I have yet to find any good tools that I like. Most of them just plain don’t work due to their age. for example, “cpm” is a console password manager available in Debian. When I try to run it, it bails out complaining “Can’t attach to parent!”. A search on Google reveals that it has problems with the more modern kernels. That’s hardly ideal.

To install encfs on Debian is straightforward:
sudo apt-get install encfs

Create two directories, e.g. ~/encrypted and ~/decrypted. Mount them: encfs ~/encrypted ~/decrypted
Enter a password that you want to use.
cd ~/decrypted
Created files, subdirectories, and edit away.
You can unmount the directory by typing
fusermount -u ~/decrypted
It’s that simple!

Mileage will depend on use-case, and it is by no means the hammer for every security nail. It does, however, work for me. Points to note: + simple and easy to set up and use
+ The directory has a separate password, distinct from user login. Skim-reading suggests that it can be PAM-enabled and mounted transparently, though.
+ Directory structure is preserved, so it is possible that crackers will be able to deduce the approximate size, quantity and
directory layout of the decrypted directory. File and directory names are themselves encrypted, though. Some might not like that idea, but it works for me
+ mounting is preserved across login sessions. That is great for convenience, although might be considered a security risk. Unmounted it when you exit the system if it’s a concern to you.

So, based on an initial valuation, encfs is an excellent tool. I sometimes use Truecrypt, which an excellent tool, but it seems more difficult to use on a command-line only environment. The GUI is “OK”, but it will be fiddly to use in my Linux environment. I also find the Truecrypt a bit tedious to set up, especially if I have migrated machines. It’s not “too” bad, but getting it to remember key files and preferred mount points is a bit of a chore. In encfs, I wrote a script called “enc” which does the mounting and unmounting for me. Job done.

Posted in Uncategorized | Leave a comment

PDF on 2-stage growth DCF calculation explanation

If you have been following my posts on 2-stage DCFs, you may be interested in a PDF that I have written that explains where all the formulae come from. I intend to write more in the article, but it stands alone as-is, and shows how Damodaran arrives at his 2007 valuation for 3M. You can obtain the article here:

I was thinking of creating a javascript page that does a two-stage calculation for you, so that people don’t have to fiddle around with Excel or Fortran. All in good time, though.

Have fun.

Posted in Uncategorized | Leave a comment

Magic Hat portfolio: CNCT in, BSY out

The Magic Hat portfolio on Stockopedia
( is an experiment by me to see if a human can improve on a mechanical Greeblatt Magic Formula screen. I am trying to weed out “mistakes” that I feel the screening commits: unseasoned companies, scams, foreign companies (particularly Chinese), fishy accounting, and statistical quirks. Apart from that, I am agnostic as to the sector the company operates in, although I will try to avoid heavy concentration in any one sector. I will mostly apply “Strategic Ignorance”, by which I mean that I wont try to be clever in my stockpicking. My picking will be mostly mechanical.

There were two candidates for ejection this month: BSY (British Sky Broadcasting) and SMWH (WH Smith). BSY had a slightly lower Magic Formula score than SMWH. Also, some back-of-the-envelope calculations suggested to me that BSY was much closer to my estimate of its intrinsic value than was SMWH. So out it goes.

BSY returned 27.8% over its holding period since Feb 2012. The Footsie returned 16.1% over the same period. Not bad, but not outstanding, either.

Added to the portfolio was CNCT (Connect), which is a distributor formerly named Smith News. I have not much else to say, as the selection was mainly about the numbers.

The median earnings yield for the shares selected by Stockopedia for the Greenblatt screen was 17.1%. This is a slight reduction from last month, which was at 18%. All of the earning’s yields were at least 10%, however. This suggests to me that the market is offering good odds.

We shall see.

Happy investing to you all.

Posted in Magic Formula Investing | Leave a comment

$SAL.L – SpaceandPeople – a valuation

BLUF: Estimated value: £30m. Market cap: £9.9m based on a share price of 51p.

The share price of SAL (SpaceandPeople) continues to drift lower, and has flatlined, with a downward drift, since its profit warning in April 2014. I have estimated that its equity is worth around £30m using a two-phase growth model.

Here is the Fortran program that does the calculation:

! calcs at 05-Sep-2014
b0 = 2279 ! operating profit y/e 31-Dec-2014
taxr = 0.21 !
a0 = b0 * (1.0 - taxr)
theta1 = 1.0 - 1.0/2.04 ! retention rate
g1 = 0.227 * theta1 ! ROCE * retention rate
h1 = 0.1 ! just use Aswath's Twitter Aug-2014 valuation

r = (1+g1)/(1+h1)
p1 = a0 * (1- theta1) * r * (1- r**5) / (1-r)
print *, "p1 = ", p1

gt = 0.025 ! per Aswath, again
ct = 0.08 
pt0 = a0 * r ** 5 * (1 + gt) /ct
print *, "pt0 = ", pt0
voa = p1 + pt0
print *, "voa = ", voa
cash = 1883 ! actually net cash
cross = 0.0
debt = 0.0
voo = 0.0
voe = voa + cash + cross - debt-voo
print *, "voe = ", voe ! value of equity
end program

There’s nothing complicated there. The source code is also in my github aswath repo; which is freely available. You may be interested to know that there is an online Fortran compiler and executer. How cool is that? You can copy and paste the code into the source area, tweak it as you wish.

The growth phase starts with a base operating profit of £2279k. Using figures mostly from Stockopedia, I use a ROCE of 22.7%. Dividend cover is 2.04, go it is retaining around 50% of its earnings, so growth should be at about 10% pa. The cost of capital to the firm can be a whole calculation exercise in itself, as it has many moving parts. You would need betas, equity risk premiums, and adjust for leverage (because the model uses a firm valuation, rather than starting from an equity one). I just used 10%, which is what Aswath seems to end up mostly in his cost of capital calcs anyway. I’m being a little sloppy, it’s true, but I’m using that figure anyway.

In the terminal phase, growth is more moderate, where I have used a risk-free rate of 2.5%, and a cost of capital of 8%. SAL has net cash of £1883k.

When you tie all those figures together, you end up with a valuation of £39m. There is a lot of implied upside in this valuation. The valuation is, of course, only as good as the assumptions that go into it. As we saw in my recent valution of TSCO (Tesco), I changed my assumptions about its likely dividend stream, and that significantly changed my estimate of value.

 Update 07-Sep-2014 : Corrected a mistake in the program, which lowers the estimated value of equity from £39m to £30m. A0 is after-tax operating profits, not before-tax.

Posted in Uncategorized | Tagged | Leave a comment