Category Archives: Topical

Includes posts on physics, philosophy, sciences, quantitative finance, economics, environment etc.

How to save a string to a local file in PHP?

This post is the second one in my geek series.

While programming my Theme Tweaker, I came across this problem. I had a string on my server in my php program (the tweaked stylesheet, in fact), and I wanted to give the user the option of saving it to a file his computer. I would’ve thought this was a common problem, and all common problems can be solved by Googling. But, lo and behold, I just couldn’t find a satisfactory solution. I found my own, and thought I would share it here, for the benefit of all the future Googlers yet to come and go.

Before we go into the solution, let’s understand what the problem is. The problem is in the division of labor between two computers — one is the server, where your WordPress and PHP are running; the other is the client’s computer where the viewing is taking place. The string we are talking about is on the server. We want to save it in a file on the client’s computer. The only way to do it is by serving the string as an html reply.

At first glance, this doesn’t look like a major problem. After all, servers regularly send strings and data to clients — that’s how we see anything on the the browser, including what you are reading. If it was just any PHP program that wants to save the string, it wouldn’t be a problem. You could just dump the string into a file on the server and serve the file.

But what do you do if you don’t want to give the whole world a way of dumping strings to files on your server? Well, you could do something like this:

<?php
header('Content-Disposition: attachment; filename="style.css"');
header("Content-Transfer-Encoding: ascii");
header('Expires: 0');
header('Pragma: no-cache');
print $stylestr ;
?>

So, just put this code in your foo.php that computes the string $stylestr and you are done. But our trouble is that we are working in the WordPress plugin framework, and cannot use the header() calls. When you try to do that, you will get the error message saying that header is already done dude. For this problem, I found the ingenious solution in one of the plugins that I use. Forgot which one, but I guess it is a common technique. The solution is to define an empty iFrame and set its source to what the PHP function would write. Since iFrame expects a full HTML source, you are allowed (in fact, obliged) to give the header() directives. The code snippet looks something like:

<iframe id="saveCSS" src="about:blank" style="visibility:hidden;border:none;height:1em;width:1px;"></iframe>
<script type="text/javascript">
var fram = document.getElementById("saveCSS");
<?php echo 'fram.src = "' . $styleurl .'"' ;
?>

Now the question is, what should the source be? In other words, what is $styleurl? Clearly, it is not going to be a static file on your server. And the purpose of this post is to show that it doesn’t have to be a file on the server at all. It is a two-part answer. You have to remember that you are working within the WordPress framework, and you cannot make standalone php files. The only thing you can do is to add arguments to the existing php files, or the plugins you have created. So you first make a submit button as follows:

<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]?>">
<div class="submit">
<input type="submit" name="saveCSS" title="Download the tweaked stylesheet to your computer" value="Download Stylesheet" />
</div>

Note that the name attribute of the button is “saveCSS.” Now, in the part of the code that handles submits, you do something like:

<?php
if (isset($_POST['saveCSS']))
$styleurl = get_option('siteurl') . '/' . "/wp-admin/themes.php?page=theme-tweaker.php&save" ;

?>

This is the $styleurl that you would give as the source of your iFrame, fram. Note that it is the same as your pluging page URL, except that you managed to add “?save” at the end of it. The next trick is to capture that argument and handle it. For that, you use the WordPress API function, add_action as:

<?php
if (isset($_GET['save'] ))
add_action('init', array(&$thmTwk, 'saveCSS'));
else
remove_action('init', array(&$thmTwk, 'saveCSS'));
?>

This adds a function saveCSS to the init part of your plugin. Now you have to define this function:

<?php
function saveCSS() {
header('Content-Disposition: attachment; filename="style.css"');
header("Content-Transfer-Encoding: ascii");
header('Expires: 0');
header('Pragma: no-cache');
$stylestr = "Whatever string you want to save";
ob_start() ;
print $stylestr ;
ob_end_flush() ;
die() ;
}
?>

Now we are almost home free. The only thing to understand is that you do need the die(). If your function doesn’t die, it will spew out the rest of the WordPress generated stuff into your save file, appending it to your string $stylestr.

It may look complicated. Well, I guess it is a bit complicated, but once you implement it and get it running, you can (and do) forget about it. At least, I do. That’s why I posted it here, so that the next time I need to do it, I can look it up.

The Razor’s Edge by W Somerset Maugham

May be it is only my tendency to see philosophy everywhere, but I honestly believe Maugham’s works are the classics they are because of their deep philosophical underpinnings. Their strong plots and Maugham’s masterful storytelling help, but what makes them timeless is the fact that Maugham gives voice to the restlessness of our hearts, and puts in words the stirring uncertainties of our souls. Our questions have always been the same. Where do we come from? What are we doing here? And where are we headed? Quo vadis?

Of all the books of this kind that I have read, and I have read many, The Razor’s Edge takes on the last question most directly. When Larry says, out of the blue, “The dead look so awfully dead.” we get an idea of what his quest, and indeed the inquiry of the book, is going to be.

Larry Darrell is as close to human flawlessness as Maugham ever gets. His cynical disposition always produced vivid characters that were flawed human beings. We are used to snobbishness in Elliott Templeton, fear and hypocrisy in the vicar of Blackstable, self-loathing even in the self-image of Philip Carey, frivolity in Kitty Garstin, undue sternness in Walter Fane, the ludicrous buffoonery of Dirk Stroeve, abysmal cruelty in Charles Strickland, ultimate betrayal in Blanche Stroeve, fatal alcoholism in Sophie, incurable promiscuity in Mildred — an endless parade of gripping characters, everyone of them as far from human perfection as you and me.

But human perfection is what is sought and found in Larry Darrell. He is gentle, compassionate, single-mindedly hardworking, spiritually enlightened, simple and true, and even handsome (although Maugham couldn’t help but bring in some reservations about it). In one word, perfect. So it is only with an infinite amount of vanity that anybody can identify himself with Larry (as I secretly do). And it is a testament to Maugham’s mastery and skill that he could still make such an idealistic character human enough for some people to see themselves in him.

As I plod on with these review posts, I’m beginning to find them a bit useless. I feel that whatever needed to be said was already well said in the books to begin with. And, the books being classics, others have also said much about them. So why bother?

Let me wind up this post, and possibly this review series, with a couple of personal observations. I found it gratifying that Larry finally found enlightenment in my native land of Kerala. Written decades before the hippie exodus for spiritual fulfillment in India, this book is remarkably prescient. And, as a book on what life is all about, and how to live it to its spiritual fullness in our hectic age, The Razor’s Edge is a must read for everybody.

House of Cards

We are in dire straits — no doubt about it. Our banks and financial edifices are collapsing. Those left standing also look shaky. Financial industry as a whole is battling to survive. And, as its front line warriors, we will bear the brunt of the bloodbath sure to ensue any minute now.

Ominous as it looks now, this dark hour will pass, as all the ones before it. How can we avoid such dark crises in the future? We can start by examining the root causes, the structural and systemic reasons, behind the current debacle. What are they? In my series of posts this month, I went through what I thought were the lessons to learn from the financial crisis. Here is what I think will happen.

The notion of risk management is sure to change in the coming years. Risk managers will have to be compensated enough so that top talent doesn’t always drift away from it into risk taking roles. Credit risk paradigms will be reviewed. Are credit limits and ratings the right tools? Will Off Balance Sheet instruments stay off the balance sheet? How will we account for leveraging?

Regulatory frameworks will change. They will become more intrusive, but hopefully more transparent and honest as well.

Upper management compensation schemes may change, but probably not much. Despite what the techies at the bottom think, those who reach the top are smart. They will think of some innovative ways of keeping their perks. Don’t worry; there will always be something to look forward to, as you climb the corporate ladder.

Nietzsche may be right, what doesn’t kill us, may eventually make us stronger. Hoping that this unprecedented financial crisis doesn’t kill us, let’s try to learn as much from it as possible.

Sections

Free Market Hypocrisy

Markets are not free, despite what the text books tell us. In mathematics, we verify the validity of equations by considering asymptotic or limiting cases. Let’s try the same trick on the statement about the markets being free.

If commodity markets were free, we would have no tariff restrictions, agricultural subsidies and other market skewing mechanisms at play. Heck, cocaine and heroine would be freely available. After all, there are willing buyers and sellers for those drugs. Indeed, drug lords would be respectable citizens belonging in country clubs rather than gun-totting cartels.

If labor markets were free, nobody would need a visa to go and work anywhere in the world. And, “equal pay for equal work” would be a true ideal across the globe, and nobody would whine about jobs being exported to third world countries.

Capital markets, at the receiving end of all the market turmoil of late, are highly regulated with capital adequacy and other Basel II requirements.

Derivatives markets, our neck of the woods, are a strange beast. It steps in and out of the capital markets as convenient and muddles up everything so that they will need us quants to explain it to them. We will get back to it in future columns.

So what exactly is free about the free market economy? It is free — as long as you deal in authorized commodities and products, operate within prescribed geographies, set aside as much capital as directed, and do not employ those you are not supposed to. By such creative redefinitions of terms like “free,” we can call even a high security prison free!

Don’t get me wrong. I wouldn’t advocate making all markets totally free. After all, opening the flood gates to the formidable Indian and Chinese talent can only adversely affect my salary levels. Nor am I suggesting that we deregulate everything and hope for the best. Far from it. All I am saying is that we need to be honest about what we mean by “free” in free markets, and understand and implement its meaning in a transparent way. I don’t know if it will help avoid a future financial meltdown, but it certainly can’t hurt.

Sections

Quant Culprits

Much has been said about the sins of the quants in their inability to model and price credit derivatives, especially Collateralized Debt Obligations (CDOs) and Mortgage Backed Securities (MBSs). In my opinion, it is not so much of a quant failure. After all, if you have the market data (especially default correlations) credit derivatives are not all that hard to price.

The failure was really in understanding how much credit and market risks were inter-related, given that they were independently managed using totally different paradigms. I think an overhauling is called for here, not merely in modeling and pricing credit risks, also in the paradigms and practices used in managing them.

Ultimately, we have to understand how the whole lifecycle of a trade is managed, and how various business units in a financial institution interact with each other bearing one common goal in mind. It is this fascination of mine with the “big picture” that inspired me to write The Principles of Quantitative Development, to be published by Wiley Finance in 2010.

Sections

Where Credit is Due

While the market risk managers are getting grilled for the financial debacle we are in, the credit controllers are walking around with that smug look that says, “Told you so!” But systemic reasons for the financial turmoil hide in our credit risk management practices as well.

We manage credit risk in two ways — by demanding collateral or by credit limit allocation. In the consumer credit market, they correspond to secure lending (home mortgages, for instance) and unsecured loans (say, credit lines). The latter clearly involves more credit risk, which is why you pay obscene interests on outstanding balances.

In dealing with financial counterparties, we use the same two paradigms. Collateral credit management is generally safe because the collateral involved cannot be used for multiple credit exposures. But when we assign each counterparty a credit limit based on their credit ratings, we have a problem. While the credit rating of a bank or a financial institution may be accurate, it is almost impossible to know how much credit is loaded against that entity (because options and derivatives are “off balance sheet” instruments). This situation is akin to a bank’s inability to check how much you have drawn against your other credit lines, when it offers you an overdraft facility.

The end result is that even in good times, the leverage against the credit rating can be dangerously high without counterparties realizing it. The ensuing painful deleveraging takes place when a credit event (such as lowering of the credit rating) occurs.

Sections

Hedging Dilemma

Ever wonder why those airfares are quick to climb, but slow to land? Well, you can blame the risk managers.

When the oil price hit $147 a barrel in July ’08, with all the pundits predicting sustained $200 levels, what would you have done if you were risk managing an airline’s exposure to fuel? You would have ran and paid an arm and a leg to hedge it. Hedging would essentially fix the price for your company around $150 level, no matter how the market moved. Now you sit back and relax, happy in the knowledge that you saved your firm potentially millions of dollars.

Then, to your horror, the oil price nosedives, and your firm is paying $100 more than it should for each barrel of oil. (Of course, airlines don’t buy WTI, but you know what I mean.) So, thanks to the risk managers’ honest work, airlines (and even countries) are now handing over huge sums of money to energy traders. Would you rather be a trader or a risk manager?

And, yes, the airfares will come down, but not before the risk managers take their due share of flak.

Sections

Risky Business

Just as 9/11 was more of an intelligence failure rather than a security lapse, the subprime debacle is a risk management breakdown, not merely a regulatory shortcoming. To do anything useful with this rather obvious insight, we need to understand why risk management failed, and how to correct it.

Risk management should be our first line of defense — it is a preventive mechanism, while regulatory framework (which also needs beefing up) is a curative, reactive second line.

The first reason for the inadequacy of risk management is the lack of glamour the risk controllers in a financial institution suffer from, when compared to their risk taking counterparts. (Glamour is a euphemism for salary.) If a risk taker does his job well, he makes money. He is a profit centre. On the other hand, if a risk controller does his job well, he ensures that the losses are not disproportionate. But in order to limit the downside, the risk controller has to limit the upside as well.

In a culture based on performance incentives, and where performance is measured in terms of profit, we can see why the risk controller’s job is sadly under-appreciated and under-compensated.

This imbalance has grave implications. It is the conflict between the risk takers and risk managers that enforces the corporate risk appetite. If the gamblers are being encouraged directly or indirectly, it is an indication of where the risk appetite lies. The question then is, was the risk appetite a little too strong?

The consequences of the lack of equilibrium between the risk manager and the risk taker are also equally troubling. The smarter ones among the risk management group slowly migrate to “profit generating” (read trading or Front Office) roles, thereby exacerbating the imbalance.

The talent migration and the consequent lack of control are not confined merely within the walls of a financial institution. Even regulatory bodies could not compete with the likes of Lehman brothers when hunting for top talent. The net result was that when the inevitable meltdown finally began, we were left with inadequate risk management and regulatory defenses.

Sections

Ambition vs. Greed

Growing up in a place like India, I was told early in life that ambition was a bad thing to have. It had a negative connotation closer to greed than drive in its meaning. I suspect this connotation was rather universal at some point in time. Why else would Mark Anthony harp on Brutus calling Caesar ambitious?

Greed, or its euphemistic twin ambition, probably had some role to play in the pain and suffering of the current financial turmoil and the unfolding economic downturn. But, it is not just the greed of Wall Street. Let’s get real. Jon Steward may poke fun at the twenty something commodity trader earning his thirty million dollar bonus by pushing virtual nothingness around, but nobody complained when they were (or thought they were) making money. Greed is not confined to those who ran fifty billion dollar Ponzi schemes; it is also in those who put their (and other people’s) money in such schemes expecting a too-good-to-be-true rate of returns. They were also made of the sterner stuff.

Let’s be honest about it. We in the financial industry are in the business of making money, for others and for ourselves. We don’t get into this business for philanthropic or spiritual reasons. We get into it because we like the rewards. Because we know that “how to get rich quick” or “how to get even richer” is the easiest sell of all.

We hear a lot about how the CEOs and other fat cats made a lot of money while other normal folks suffered. It is true that the profits were “private” while the losses are public, which is probably why the bailout plan did not get much popular support. But with or without the public support, bailout plan or not, like it or not, the pain is going to be public.

Sure, the CEOs of financial institutions with their private jets and eye-popping bonuses were guilty of ambition, but the fat cats didn’t all work in a bank or a hedge fund. It is the legitimization of greed that fueled this debacle, and nobody is innocent of it.

Sections

The Big Bang Theory – Part II

After reading a paper by Ashtekar on quantum gravity and thinking about it, I realized what my trouble with the Big Bang theory was. It is more on the fundamental assumptions than the details. I thought I would summarize my thoughts here, more for my own benefit than anybody else’s.

Classical theories (including SR and QM) treat space as continuous nothingness; hence the term space-time continuum. In this view, objects exist in continuous space and interact with each other in continuous time.

Although this notion of space time continuum is intuitively appealing, it is, at best, incomplete. Consider, for instance, a spinning body in empty space. It is expected to experience centrifugal force. Now imagine that the body is stationary and the whole space is rotating around it. Will it experience any centrifugal force?

It is hard to see why there would be any centrifugal force if space is empty nothingness.

GR introduced a paradigm shift by encoding gravity into space-time thereby making it dynamic in nature, rather than empty nothingness. Thus, mass gets enmeshed in space (and time), space becomes synonymous with the universe, and the spinning body question becomes easy to answer. Yes, it will experience centrifugal force if it is the universe that is rotating around it because it is equivalent to the body spinning. And, no, it won’t, if it is in just empty space. But “empty space” doesn’t exist. In the absence of mass, there is no space-time geometry.

So, naturally, before the Big Bang (if there was one), there couldn’t be any space, nor indeed could there be any “before.” Note, however, that the Ashtekar paper doesn’t clearly state why there had to be a big bang. The closest it gets is that the necessity of BB arises from the encoding of gravity in space-time in GR. Despite this encoding of gravity and thereby rendering space-time dynamic, GR still treats space-time as a smooth continuum — a flaw, according to Ashtekar, that QG will rectify.

Now, if we accept that the universe started out with a big bang (and from a small region), we have to account for quantum effects. Space-time has to be quantized and the only right way to do it would be through quantum gravity. Through QG, we expect to avoid the Big Bang singularity of GR, the same way QM solved the unbounded ground state energy problem in the hydrogen atom.

What I described above is what I understand to be the physical arguments behind modern cosmology. The rest is a mathematical edifice built on top of this physical (or indeed philosophical) foundation. If you have no strong views on the philosophical foundation (or if your views are consistent with it), you can accept BB with no difficulty. Unfortunately, I do have differing views.

My views revolve around the following questions.

These posts may sound like useless philosophical musings, but I do have some concrete (and in my opinion, important) results, listed below.

There is much more work to be done on this front. But for the next couple of years, with my new book contract and pressures from my quant career, I will not have enough time to study GR and cosmology with the seriousness they deserve. I hope to get back to them once the current phase of spreading myself too thin passes.