Tuesday, September 04, 2012

Monitor ansys solves using matlab

prep/post of Workbench has improved in helping you monitor solves with better charting. I wrote a matlab script to monitor solves when workbench was still rudimentary in this functionality that I still use because I dont want to tie up a preppost license just to mionitor a job. It is pasted below and perhaps can be of use to other ansys users too. It is setup to poll solve.out every 15 sec -- you can change it to any other convenient interval on the pause instruction.

-------------


clear; clc; clf;
startTime = tic;

solvePath = 'C:\fea\pr1\_ProjectScratch\ScrF95A\'; % path  to folder where solve.out is being written.
jobName = 'blah'; % title you want to display on your monitor window.




inFile = fullfile(solvePath, 'solve.out');
dispHist = 200;
fileNum = rand(1,1);
% !erase monitorFile*.txt
while true
    scratchFile = ['monitorFile' num2str(fileNum) '.txt'];
    copyfile (inFile, scratchFile);
 
 
    fileHandle = fopen(scratchFile);
    tLine = fgetl(fileHandle);
    forceConvergence = [];
    momentConvergence = [];
    dispConvergence = [];
    timeStep = [];
    getInitialTime = true;
    while ischar(tLine)
     
        if getInitialTime
            k1 = strfind(tLine, 'CURRENT JOBNAME=');
            k2 = strfind(tLine, 'CP=');
            if ~isempty(k1) && ~isempty(k2)
                b1 = sscanf(tLine, ' CURRENT JOBNAME=file%sCP=%*f')';
                if length(b1) == 3
                    timeStep = [timeStep; b1];
                end
                b1='';
                getInitialTime = false;
            end
         
        end
     
     
        k = strfind(tLine, 'FORCE CONVERGENCE VALUE');
        if ~isempty(k)
            b1 = sscanf(tLine, '%*s%*s%*s%*s %f %*s %f')';
            if length(b1) == 2
                forceConvergence = [forceConvergence; b1];
            end
            b1='';
        end
        k = strfind(tLine, 'MOMENT CONVERGENCE VALUE');
        if ~isempty(k)
            b1 = sscanf(tLine, '%*s%*s%*s%*s %f %*s %f')';
            if length(b1) == 2
                momentConvergence = [momentConvergence; b1];
            end
            b1='';
        end
     
     
        k = strfind(tLine, 'DISP CONVERGENCE VALUE');
        if ~isempty(k)
            b1 = sscanf(tLine, '%*s%*s%*s%*s %f %*s %f')';
            if length(b1) == 2
                dispConvergence = [dispConvergence; b1];
            end
            b1='';
        end
        k1 = strfind(tLine, 'TIME =');
        k2 = strfind(tLine, 'TIME INC =');
        if ~isempty(k1) && ~isempty(k2)
            b1 = sscanf(tLine, '%*s %*s %*s %f %*s %*s %*s %f')';
            if length(b1) == 2
                timeStep = [timeStep; b1];
            end
            b1='';
        end
        k = strfind(tLine, 'ANSYS RUN COMPLETED');
        if ~isempty(k)
            subplot(411), title(['AC / ', jobName, ', ', datestr(now) ', ET: ' num2str(round(toc(startTime)/60)) ' min']);
            msgbox(['Analysis Complete: ', jobName]);
            return;
        end
     
        tLine = fgetl(fileHandle);
    end
 
    fclose(fileHandle);
    subplot(411)
    semilogy(forceConvergence(:, 1), 'b'); grid on; hold on;
    semilogy(forceConvergence(:, 2), 'm');
    %     legend('ForceConvergence', 'Criterion', 'Location', 'Best');
    title([jobName ': ' datestr(now) '     ET: ' num2str(round(toc(startTime)/60))  ' min']);
    [numRows, numCols] = size(forceConvergence);
    if numRows > dispHist
        axis([numRows-dispHist  numRows min(min(forceConvergence)) max(max(forceConvergence))]);
    end
 
        if ~isempty(momentConvergence)
            subplot(412)
            semilogy(momentConvergence(:, 1), 'b'); grid on; hold on;
            semilogy(momentConvergence(:, 2), 'm');
    %         legend('MomentConvergence', 'Criterion');
    title('Moment Convergence');
            [numRows, numCols] = size(momentConvergence);
            if numRows > dispHist
                axis([numRows-dispHist numRows min(min(momentConvergence)) max(max(momentConvergence))]);
            end
        end
 
    if ~isempty(dispConvergence)
        subplot(413)
        semilogy(dispConvergence(:, 1), 'b'); grid on; hold on;
        semilogy(dispConvergence(:, 2), 'm');
        %        legend('dispConvergence', 'Criterion');
        title('Disp Convergence');
        [numRows, numCols] = size(dispConvergence);
        if numRows > dispHist
            axis([numRows-dispHist numRows min(min(dispConvergence)) max(max(dispConvergence))]);
        end
    end
 
 
    if ~isempty(timeStep())
        subplot(414)
        plot(timeStep(:, 1), timeStep(:, 2), 'b-*'); grid on; hold on;
        ylabel([num2str(max(timeStep(:, 1))), ': Time step [s]']);
        xlabel('Time [s]');
        axis([0 max(timeStep(:, 1)) 0 1.2*max(timeStep(:, 2))])
    end
 
 
    pause(15)
 
end

Labels: , , , , , , ,

Monday, April 09, 2012

Mupad to setup state-space equations of vibrations using Lagrange’s equation



If you want to solve a dynamic system’s response (like a vibrating system) to arbitrary inputs using matlab’s control system toolbox it helps to have a symbolic math application setup the equations for you. There are many ways to skin a cat but here is the overall approach followed by a technique to use mupad / matlab’s symbolic math engine to setup the state space system.
Overall approach:
1.       Reduce the real system to a schematic of lumped parameters (springs, masses, dampers).
a.       This is the conceptual reduction of a continuous system to a finite dimensional system and you would probably like to do this manually.
2.       Set up the Lagrange equations. Many vibrations textbooks will show you how, eg. Rao, S.S., Mechanical Vibrations.
a.       This is easy to setup (the kinetic energy, potential energy and Rayleigh dissipation equations).
3.       Convert to equations of motion (mx’’ + cx’ + kx = F)
a.       This is tedious for complicated systems and you could spend a lot of time debugging your algebra if you do this manually. – this is the step this post attempts to help you automate.
4.       Convert to state space
a.       Somewhat tedious and this sample script below does a little to address it.

Mupad code: this code will setup equations of motion in state space form y’ = Ay+Bu for a m1 attached to ground with spring/mass and m2 and m3 are parallelly or independently attached to m1 with spring/damper. The system is not all that important. The way to use mupad / matlab to get the SS equations is the point here.


T:= 1/2 * m1 * x1md^2 + 1/2*m2*x2md^2 + 1/2*m3*x3md^2
V:= 1/2*k1*x1^2+1/2*k2*(x2-x1)^2+1/2*k3*(x3-x1)^2
R := 1/2*c1*x1d^2+1/2*c2*(x2d-x1d)^2+1/2*c3*(x3d-x1d)^2
dof1m:=diff(T, x1md);
dof1m:=subs(dof1m, x1md=x1'(t));
dof1m:=rewrite(diff(dof1m, t), D);
dof1:=collect(dof1m - diff(T, x1) + diff(R, x1d) + diff(V, x1), [x1, x2, x3, x1d, x2d, x3d]);
dof1:=collect(subs(dof1, x1=y1, x1d=y2, x2 = y3, x2d = y4, x3=y5, x3d=y6), [y1, y2, y3, y4, y5, y6]);
dof1:=subs(dof1, y1''(t) = y2d);
dof1:=(dof1=F1);
solve(dof1, y2d, IgnoreAnalyticConstraints)



dof2m:=diff(T, x2md);
dof2m:=subs(dof2m, x2md=x2'(t));
dof2m:=rewrite(diff(dof2m, t), D);
dof2:=collect(dof2m - diff(T, x2) + diff(R, x2d) + diff(V, x2), [x1, x2, x3, x1d, x2d, x3d]);
dof2:=collect(subs(dof2, x1=y1, x1d=y2, x2 = y3, x2d = y4, x3=y5, x3d=y6), [y1, y2, y3, y4, y5, y6]);
dof2:=subs(dof2, y3''(t) = y4d);
dof2:=(dof2=F2);
solve(dof2, y4d, IgnoreAnalyticConstraints)


dof3m:=diff(T, x3md);
dof3m:=subs(dof3m, x3md=x3'(t));
dof3m:=rewrite(diff(dof3m, t), D);
dof3:=collect(dof3m - diff(T, x3) + diff(R, x3d) + diff(V, x3), [x1, x2, x3, x1d, x2d, x3d]);
dof3:=collect(subs(dof3, x1=y1, x1d=y2, x2 = y3, x2d = y4, x3=y5, x3d=y6), [y1, y2, y3, y4, y5, y6]);
dof3:=subs(dof3, y5''(t) = y6d);
dof3:=(dof3=F3);
solve(dof3, y6d, IgnoreAnalyticConstraints)



Why would I choose such a solution approach?
1.       Why not a finite element model: Lumped parameter models are much faster and are helpful to have to try a large number of scenarios out quickly.
2.       Matlab is way cool.
3.       Why not differential equations solution: sure, why not? But I like thinking in laplace transforms / transfer functions / state space.
4.       Control system toolbox with functions like lsim, bode etc is very neat.
5.       You could potentially integrate your system into a feedback loop and design controllers very conveniently once you have your dynamics setup.
6.       “Ok, but why the Lagrange approach? I can write the equations of motion by inspection.” More power to you! I get confused with signs and subscripts with large number of DOF.
7.       “So why bother to post this. What have you really added?” I couldn’t find a good answer on the web on how to use mupad to setup a lagrangian approach to equations of motion. I spent a good number of hours on the wknd and this am figuring this out and want to share my hard-won wisdom. And I’ve been telling myself for years to become a more active blogger.
8.       “Is this the best way to do this in mupad?” Not likely. This is the attempt of a newbie with symbolic math (and I don’t plan to get a whole lot better in the symbolic world). But its more substantial that anything I found on the internets.

Labels: , , , , , , , , , , , , , , ,

Monday, January 25, 2010

The sorry waste of MBA programs


Well I’ve wasted the last decade getting an MBA and then making my way through a career in commodity markets that wasn’t fulfilling. I’ve revisited often over the years the assumptions and mis-impressions that premised my entry into MBA. I’ve done my best to talk logically to anyone who has approached me about the wisdom of doing an MBA in a top flight program and to dissuade them from pursuing the MBA – I’ve never deterred anyone to date. Perhaps no one could have deterred me from doing MBA either. But I must write my best reasoning here and leave it for google to carry my memes to new crops of MBA hopefuls.

So here are the myths and poor assumptions I held – if I had a different view on these factors perhaps I wouldn’t have taken the fork in the road that led me to the MBA.

Surely something so expensive is very scarce


The top 10 programs put out ~ 600 grads per year – that’s about 6,000/yr put together. If you add in their executive MBA, part time and other gimmicks they use to boost their revenue these top10s put out ~10k grads/year jointly. So what? In a work force of 130 MM people 10k is still a rarified circle you might think. But consider that there are the yesteryear vintages still trawling the job markets also plying their top10 brand and also that the number of GoldKinsey jobs are very finite (more below on this). Sadly in all the smoke-and-mirrors of the MBA application process the facts were available to me that the school I went to accepted 25% of the applicants and that they would put out 500+ graduates along with me from whom I would be distinguishable only in unflattering ways. Doldrum U. you think? – no this school has been consistently near the top of the businessweek top10 full time programs in the last decade (and much longer in fact). There was nothing scarce about the opportunity I was paying dearly for, and the facts were there to be evaluated though buried in heavy marketing hype. But if you knew the right questions to ask, the answers would have been apparent.

MBA will help me make a career transition


Somewhat so. In a good economy when labor supply is scarce employers are more willing to take chances on a career changer who thinks he has metamorphosed into something else. But you cant guarantee what the shape of the economy will be in the 12 months from your entry point into an MBA which is when the career benefits get locked in for you in the typical 2 year program – and if you are prescient about the state of the economy 12 months hence, you have better ways to make money than taking an MBA education. My experience was that employers saw me as a fat-dumb-happy 7 years experienced engineer who had grown lazy  -- and they were mostly on the mark. I wasn’t hungry and hence wouldn’t make the sacrifices in their nearly correct reckoning. But it begs the higher question: if you have the hunger for a career transition do you think the MBA enables you to make it? Moderately so, I think, with some retraining and putting you in front of employers. But if 80% of getting there is your hunger and 20% is the MBA, is that 20% boost worth $100k+ in outlays + foregoing 2 years of the surplus you would have generated staying in your job?

It’s the natural progression for the desi engineer

Where I come from, it was drilled in me from my earliest career discussions with my father that the path to nirvana was the IIT BS + IIM MBA. That was the golden combination. But I’m not holding this on my parents – its not my point at all. This was the orthodoxy of the times. _Everyone_ drilled this into their children. As it worked out, I went to neither. But the mindset was there that if you had the means you went for the top10 MBA. But the facts around us are that there are plenty of desi engineers who do pretty well with their BS or MS in engineering. Those who got MBAs are on expectation only a little better paid (expectation here means average value) – the vast majority of the MBAs are just 2 years older, with only few of them being fabulously better paid because they got to GoldKinsey. The people who get ahead in their careers typically do so, in my observation, by a combination of better technical skills and better management of people, not because of an MBA. Orthodoxy eventually becomes obsolete – if enough people over successive generations follow the same conventional wisdom it ceases to hold value. This is not controversial in the abstract, but somehow does not find resonance in the context of the desi engineer + mba track – so many people are doing it that its really not that scarce / special to command a rent. The IIT + IIM combo or the MIT BS + Harvard MBA will have cachet for a long time probably, but please don’t delude yourself into thinking that the school that is 80% of MIT + 80% of Harvard will get you anywhere as far – the power law applies here. If you are 80% of the way to the stratosphere there still a lot of birds flying at your level.

The doors to GoldKinsey will be wide open to me

This too is is a variant of the ‘there is no scarcity you are generating’ argument. The brochures of the top10 are replete with the cases and pictures of people who look just like you (only a little more scrubbed) who made it to GoldKinsey. You tie that with the notion that your 700+ gmat and willingness to fork over $100k+ entitles you to the coveted place in the GoldKinsey associate pool. Your wishful thinking is reinforced by the brochures and the mutual congratulation of MBA forums, which obscures the facts that there will be 500+ people vying for the 50 spots at GoldKinsey, that whatever your distinct qualities were coming into MBA, almost everyone in your cohort now looks the same to the GoldKinsey recruiting team, everyone except the 50 or so who do have the material.

And what is your radar cross-section to the GoldKinsey recruiting team you might ask? – hastily scrubbed and newly versed in the cynicism of the Nash equilibrium but ego already well inflated with a sense of entitlement nurtured in an incestuous cauldron of self-congratulation. You come across as an imprudent risk taker, one with a poor valuation of money and just plain dumb on expectation. On _expecation_; GoldKinsey knows there are some diamonds scattered about, not least because GoldKinsey put many of them there in the 1st place (these are the GoldKinsey former analysts). These are the ones who have a fully paid 2 year vacation biding their time before they return to a plum PE assignment and resume their ordained track to becoming masters of the universe. These are the ones who will be called up to speak at the recruiting receptions ‘impromptu’ while you hang on to their every word over brie and baba ganoush and crackers and you will at that watershed moment catch a glimpse of the eclipse of your post MBA prospects by these obviously better developed individuals who will smile at your over the wine just as surely as they will brush past you in the hallways tomorrow. You are to a first approximation only worth to them the points you will bid for an interview on the open list – don’t know what I am talking about? I hope you don’t get far enough along to find out. For that is sadly one of the dubious pieces of development one acquires in MBA: the crass appraisal of another’s utility.

To my observation, the 50 or so worth ones were indeed my betters, they had the goods, but guess what? – they had the goods when they arrived. The MBA didn’t transform them, and couldn’t have; with the mad dash to launch summer recruiting, brush up your case frameworks or practice your schmooze before you receive any substantial education makes the place take on more of an air of the anteroom in a debutante ball (how would I really know? -- but this writes good). To my eye, the MBA program allowed the diamonds in the rough the opportunity to present themselves in a relatively rarified showing – stay tuned for signaling theory.



The training is scarce, arcane and valuable

The professors are rock stars, they are the ‘thought-leaders’ such as it is. But there is not a lot thought here. Economics thinking is still fairly superficial compared to what you see in the natural sciences. These professors hobble themselves with dogmas like market efficiency, rational actors, risk neutrality – the odd behaviorist academic will do only a little to redress these punishingly childish assumptions. I sat dumbfounded through a labor economics class which spent much of its treatment on the ‘ceo salary as a trophy challenge’ apology for executive compensation, the ‘stock options align the risk appetite of the cXo with the shareholders interests’ apology and other matters of pertinence in the plush gulfstream jet sailing through the rarified upper reaches of the atmosphere, but this class would not condescend to talk about what makes the working-stiff show up to his blue collar job most days and be sober enough to turn the wrench.

The theory of marketing is doubly nebulous only served up with a stronger dose of rhetoric and unjustified conviction. The finance theory is a little more anchored in ground, and the naïve assumptions are honestly laid out but render the analysis of little use nonetheless – though atleast the finance discipline gets points for admitting its tenuous link to reality. But perhaps the most immutable words are from Andrew Lo: “In physics it takes three laws to explain 99% of the data; in finance it takes more than 99 laws to explain about 3%.”

As unimpressed as I am about the value of what is proferred as theory, let us take for argument that it is valuable. You can get 80-90% of the theory from lesser MBA programs where the professors wont be stars though with not quite the flourish and the theatrical delivery, but nonetheless on an objective measure it will be nearly as good. Is the cost delta of getting the material from the top10 MBA worthwhile? I don’t think it is.

The wisdom of the professors

In the classes I gleaned 3 pearls from the brilliant (I’m not kidding) professors who ambivalently viewed us as both the source of their ample rent and also as their gullible charges. Skilled in the delicate art of being indelicate with the stooges (that’s you the MBA aspirant) they made 3 points over and over.


  1. Econometric research shows that the only statistical outcome of getting an MBA is a 2 year increase in age. The research couldn’t show a change in salary, job satisfaction, or any of the other fleeting promises of the MBA but it did unequivocally show that people who get MBAs get to be 2 years older.
  2. Signaling: this is the finest idea you will read in this article IMO. The NPV on expectation is going to be –ve for getting a full time MBA (simple calcs later), but the ridiculous expenses are a signal. What makes an effective signal? – something that is absurdly expensive for a phony to display, but for a candidate with the legit package it is profitable to incur the expense. The implication is that the higher the expense of the MBA education, the better it becomes as a legitimate signal since the individuals with private information of their superior fitness will be more credible in displaying their qualities by incurring the handicap of the MBA expense “here I am $100k lighter, take me I am worthwhile and I know I will be able to make it back; if I was a faker I’d be ruining myself for I’d be found out in < 3 months”; the tacit admission the professors make here is “we know our classes and program wont transform you, but you get to hang out with the smartest profs here and get the chance to demonstrate your fitness by taking on the handicap”. Beautiful, elegant, marvelous theory I resort to banal praises here; it is at the confluence of evolutionary psychology and the economics of information and inverts the concept of adverse selection in a brilliant tour-de-force. Signalling theory finds it inspiration in the work of people like Amotz Zahavi reviewed adequately in Wikipedia: http://en.wikipedia.org/wiki/Signalling_theory, but magnificently in the books ‘The Selfish Gene’ and ‘The Mating Mind’ which invoke examples of male birds developing costly displays of colorful plumage to demonstrate their fitness to the female.
  3. Real options: a grand application of the theory of options to business flexibility a simple illustration is the option to operate a gold mine which has marginal cost of $1,100/oz. If the price of gold was $500/oz when the opportunity to invest was presented to you, you would say this mine is not profitable so there is no value I would give it other than zero. But wait, there is the probability however infinitesimal that the price of gold will rise above $1,100/oz and then I would be able to run this mine for a profit; when gold is below $1,100 you simply idle it, when it is in the money you run it. All good so far. But they shoehorn this concept in a mildly desperate attempt to apply it to the MBA value proposition. Its as if they were saying “we know the MBA  proposition is –ve NPV on expectation, but in the uncertainty of the world you’ll be better armed with it than without.” Not quite analogous to the gold mine, because the gold mine does not waste while you wait for it to get in the money; the MBA recruiting opportunity has a half life measurable in months / quarters. If you graduate in a shitty economy, it wont pay for most of you. EVER!
The simple NPV analysis

But as an investment any deal has a cost and a benefit. If you are setting aside the intellectual benefits (more on this) and looking at MBA as an investment, fine, do the analysis. I am lazy so I will give a simple and vulnerable calculation. But I think you will atleast grant me that it is not mischievously tweaked. I am assuming on expectation for all numbers below. He will incur $150k in expenses over 2 years ($90k in tuition, 40k in living expenses, 20k in forgone surplus of 2 years of working). He will get $10k of increased surplus each year after MBA on expectation – a few will get $200k jobs for five years, most will get $100k jobs, a small fraction <1% will get millions. At 5% discount rate (since I am taking expected cash flows I am just going risk free on the discount rate, if I were to use a lottery ticket cash flow I would use a high discount rate) and assuming a 30 year work span post MBA I get npv of -$13k. Before you whip out your HP12C in a preppie wall street strut please pause to note the moving parts above and that you could get any answer you want, but I feel my inputs are fairly uncontroversial and arrive at this result. This near-zero NPV is why your corporation finance professor in a passing sleight of hand will allude to the real-option value of the MBA. A lot of break-even / moderately value losing propositions are couched in the logic of real options.

In all of this diatribe of I haven’t had the chance to expose the intellectual vacuum that is the MBA program. I went to a program that prided itself as being rigorous and quantitative. But schooled in engineering I understood immediately that the curriculum and expectations of the professors were extremely unchallenging in both aspects; the tone was to dumb it down and the atmosphere did nothing to prod the already incurious MBA mind. There was little rigor in developing the theoretical under-pinnings, no one cared anyway, inquisitive questions I posed to professors without a ready motivation of how will this help me make more money (especially when asked of the performing star type professors) were treated with ridicule which was well received by a mirthful and mocking student body, provocative case write-ups invited the TF/prof to bleed all over them while trite, equivocating prose brought praise.

So could the MBA be good for anything? I can see some people who might actually get something good from it.


  • The rock star GoldKinsey ex-analyst with the fully paid ride can make a fantastic vacation out of it, kinda like a cruise with a delightful buffet of classes, clubs, networking opportunities and fawning acolytes.
  • The immigrant who has no other connection to America can make a good punt on credit. Don’t put your own money down, enjoy the ride for 2 years if you get a great job in America fine, pay back the loan. If you don’t, default! I cant imagine they have liens on your diploma, but even if they manage to do that what have you really lost? Return to India or wherever with an amazing experience of a lifetime on Citibank’s nickel.
The positive experiences from my MBA

Some nuggets I got from it included an exposure to the social sciences. In the coursework I saw a window into another world where people talked about political science and international relations, Coase’s theory of the firm, network externalities and other neat ideas. I also got to take a picture with some Nobel laureates. I got a handle on the literature to make inroads into lines of individual inquiry (I got a reading list). I learned to parse the finance media and cut through a lot of BS in making investing decisions – ultimately I lost more in 2008 in investments than the tuition I paid for the MBA, but I don’t know the counter-factual; I could’ve lost more.

I didn’t have google or blogs 10 years ago when I was looking into MBA. Perhaps the facts / logic even if they were served on a platter wouldn’t have made a difference to me. But perhaps you could be a little more open-minded than I and evaluate the situation for your individual self and not conform to an obsolete orthodoxy. Whatever you do, don’t feel motivated to get an MBA if you saw something here that you didn’t quite understand and want to learn more about it – that’s what Wikipedia is for.





Labels: , ,

Sunday, January 24, 2010

Review of Dawkins' The Greatest Show on Earth

Cogent exposition of evolution as you might expect of Dawkins and in some places polemical too. Good science thinking must be skeptical and argumentative but the tone in this book is sometimes of a science besieged. Dawkins conveys splendidly the fecundity of evolutionary theory in generating testable hypotheses and lending itself to falsification. And in later chapters he demonstrates the parsimony of evolutionary theory in explaining the relative distance of species. Popper would be pleased.

Labels: , ,

Thursday, August 30, 2007

The Hedge fund as a stop-loss order

A stop loss order is an instruction given to a broker to trade a security to “limit” the loss in a position. So if you hold a share of Google and you don’t want to bear a loss greater than Google stock dropping below $400/share you could place a stop loss order with your broker to sell the shares if the price drops below $400/share. This limits your downside in the position though it can be a naïve trade. There is an analogous instruction you can do for a stop-loss for a short position you might hold.

There’s been a fair amount of research on the liquidity effects of stop-loss orders in aggregate. Notably the ’87 crash is attributed to wholesale program trading where a large number of stop-loss orders aggravated the crash. As asset prices fell on the exchange, algorithms at various trading houses kicked in to automatically sell holdings to prevent further loss. The tremendous selling pressure of all these algorithms acting at once caused prices to continue their precipitous fall resulting in a single 1-day drop in the Dow of 22%. In the aftermath academics and market big-wigs argued about the extent to which stop-loss orders were responsible for the ’87 crash and what remedies / safe guards should be put in place.

Hedge funds have been described as all sorts of things ranging from market-neutral, shareholder activists, the brain-trust of Wall Street and what not, including “liquidity providers.” When people think of hedge funds as liquidity sources, they have in mind the strategy where a hedge fund provides liquidity to the market by being a buyer of illiquid assets. For instance one of the strategies of hedge funds is to buy off the run treasury bonds say 28.5 years to maturity, and sell the on the run T-bond (freshly issued, actively traded). This strategy stays essentially risk neutral (with some term risk that I am sure they hedge cleverly) and provides liquidity to the market because otherwise the 28.5 year bond might trade unreasonably low in price (the liquidity premium acting here).

But I’m thinking of hedge funds as a liquidity sink rather than their other claims as market participants. A hedge fund raises some money, called equity, and borrows huge multiples against that equity and uses this pool of cash to make investments. When the fund’s strategies are working out, this leverage is helpful. It magnifies the returns of the hedge fund. When the returns are poor, it causes plenty of distress for the fund and if the distress is widespread, it hurts other market participants too. When the hedge fund is sitting on losing positions, it has to post margin in the form of cash to its lenders. This cash comes from equity. When the firm runs out of equity the lenders seize the assets and sell them (if the fund doesn’t do it first). You can now see how this is like a huge stop-loss order. The positions are deteriorating and the fund has to sell them in distress en-masse causing a further drop in asset prices. From the standpoint of a hedge fund investor, his hedge fund is like a stop-loss order; he makes an equity investment say $100 million and the fund borrows say $1 billion against that equity. When that equity is all blown away, the investor simply says “alright liquidate the fund, I don’t want to lose anymore money.” That’s your stop-loss order on an institutional scale. Add up enough of these happening over a matter of days and weeks and you have your liquidity crisis.

Correlations on returns on assets are an interesting topic in a liquidity crunch. There’s all kinds of research, published or not, on the correlations of various assets. The idea here is that investors want to feel diversified because they feel less exposed to risk that way. So researchers aggregate all kinds of market data, assemble returns (daily price changes in assets) and do correlation analyses on them. But naïve analysis like that misses the point. Diversification is most needed on the way down. It turns out correlations are not stationary (not fixed over time to put it simply). Asset returns frequently get more correlated when markets are falling. You can see how this might happen due to an imploding hedge fund. The fund has exhausted its equity and is taken over by its lenders. They look at the book and start unloading the most liquid assets to recover whatever money they can and work down to less liquid assets. So while the hedge funds losses may have been due to sub-prime mortgage assets it was holding, the first thing the lenders sell is stock holdings because they can readily be sold. The stocks may be in anything, a oil services company in Oklahoma, a textile company in China, whatever. Now all these stocks that have no apparent connection with the real estate industry experience a crash because they are being dumped on the market in spades. The investor who thought he was diversifying his risk watches all his assets go down together just when he needed the diversification. Hedge funds are of course not the only ones responsible here, but they are a big part of it.

Could you profit from it? Perhaps. If you keep spare, invest able cash and know what you want to buy you can wait around for a liquidity crisis. Whatever happened this month of August 2007 was described laughably by Goldman Sachs as a 25 sigma event that assuming normal distributions happens once is 1000000……… years. The naïve, perhaps irresponsible and mischievous assumption here is that such market outcomes are subject to normal distributions. This is written about eloquently by Nicholas Taleb in “Fooled by Randomness” and “The Black Swan” and reviewed very nicely here:
http://econophysics.blogspot.com/2007/05/black-swan-well-thats-life.html

In any case, these once in 1000+ year events seem to happen more like every 5-10 years. So if you do your homework and have the stomach to buy when everyone else is selling you could make a handsome profit. Or may be not…

Labels: , ,

Friday, October 29, 2004

On Outsourcing

On Outsourcing

There is increasingly a climate of resentment against the trend in outsourcing. While India is getting a modest boost in economic well-being and enjoying a newly created slice of civil society (IT related professionals) which is bringing prosperity and libertarian values to some parts of India, we also note that America is in a sluggish, jobless recovery.

That the state of the US economy may be the outcome of a myriad factors such as overinvestment (spare capacity), the propping of the US dollar by China and Japan which keeps US exports uncompetitive, wasteful subsidies to the sugar/steel industry and shady deals with Halliburton, political risk in the specter of terrorism, and tax reform that has largely benefited the wealthiest who have the least marginal propensity to consume, is largely ignored by the popular media and little understood by the average American. All of these factors have downstream effects on the growth in jobs/wages but the media/masses are largely content in blaming direct effects where the causality is seemingly obvious – outsourcing being the chief one.

It is especially annoying to see fools like Lou Dobbs each night engaged in demagoguery and fear mongering – because we can see his prejudice resonating in people around us. It is of little consolation that Dobbs often ends up a lump of oozing, impotent emotion when he cannot articulate his prejudices with a veneer of reason. It is almost amusing to see him crazily ramble on, ostensibly phrasing a question to a guest only to abruptly end the interview without permitting any counter.

When the economy was doing well, Lou Dobbs was ‘Managing,’ now he is railing on outsourcing. The elite of America were all for trade and globalization when it was to their obvious advantage; now the advantages of trade are less obvious (but present nonetheless) and they have changed their tune. The racism stinks: the ‘regional design center’ in Germany or Israel is purportedly to harness the best talent of the world while the ‘outsourcing’ to India is a theft of a hard-working American’s job. Could you think of anything that screams “double-standard” any louder?

Work the numbers
There is a great survey on India in the February 21st, 2004 issue of The Economist. In the argument that outsourcing is harming the US economy, the numbers just don’t bear out. Nasscom forecasts that by 2008 IT and IT enabled services will account for $77B of India’s GDP. Even if all of this output is destined to the US, it is still only about 0.7% of US expected GDP in 2008. The doomsday seers are fussing over a 0.7% loss to US income over the course of 4 years - this is a laughably trivial effect.

The other way to look at it is in terms of jobs. Forrester Research projects that 3.3 millions service jobs will be lost to outsourcing by 2015. To put this in context, the US economy churns 2 million jobs a month; this roughly means that aside from cyclic effects of booms and busts, the economy creates and destroys 2 million jobs a month. The total job loss due to outsourcing is worth only 1 ½ months of churn and then over 11 years. This effect is almost imperceptible.

A thought experiment
J. Bradford DeLong, a UC Berkeley economist, has on his website an analysis on what outsourcing means to an economy. He lays of a couple of scenarios, but the one that is relevant to the current outsourcing issue is the one in which a minority of white collar workers find their jobs threatened with overseas competition. In this scenario, US IT workers find their wages are competed down which does have the effect of reducing national income. But everyone in the population benefits from cheaper IT services – they can use their savings to consume more of some combination of IT services and other goods; this counteracting effect more than compensates for the loss of US IT workers and the net result is a boost to the national output.

American Competitiveness
Consider the parallel to Bush’s steel tariffs. In the words of Palkhivala, a celebrated Indian jurist, in economics there are no miracles, only consequences. When Bush imposed tariffs on steel imports in blatant contempt of international trade agreements, he hurt not only foreign steel producers, but also hurt domestic consumers of steel – the appliance industry for instance found itself in distress when foreign appliance makers using steel from non-US sources had a cost advantage. Tariffs are not a panacea, as many a nation has discovered over and over.

In the context of outsourcing many a US electronics maker could find itself uncompetitive if it is forced to hire US firmware engineers, when the German competitor is using cheaper Indian ones. How does it help the US economy when the US firm goes bust or completely moves out of the US because it cannot be profitable using 100% US labor? When the whole world is using Indian IT services because they are the best value for money, America can be the exception only at its own peril.

Spread liberty through trade
Many an American is filled with hubris about the superiority of the American way of life, the centrality of liberty to the American way (the Patriot act notwithstanding), the fruits of capitalism and so on. The Iraq quagmire is now sensitizing many a thinking American to the contradiction in spreading liberty through oppression. This provides a timely basis to the argument that a more effective way to evangelize the world to the benefits of the market system is through trade. When nations are interconnected through commerce, there is an entrenched business interest which will counteract the nature of politicians to engage in jingoistic escapades.

There has to be some way to pay for this sort of world-improvement, better so in the form of a few lost jobs due to trade rather than the futile bloodshed of Americans in ‘ungrateful’ Islamic lands.
Protectionism is contagious and hence devastating
When a small, marginally consequential economy erects barriers to trade, it imperils itself. It cannot avail of the benefits of trade such as the comparative advantage in production, the discipline of the international market etc. But it hurts itself the most. It has more to lose than gain, because it risks provoking other, more powerful economies to retaliate against it specifically. Hence, small economies (with notable exceptions like North Korea) normally see the sense in keeping borders as free as possible.

But if the pre-eminent economy raises protectionist barriers, the smaller economies see no downside in also raising barriers. When there is no customer left who will retaliate, what prevents them from protecting their domestic market? Protectionism by the economic leader is contagious and leads to worldwide contraction – in a world dangerously afflicted with AIDS and radical Islam, trade and economic well-being is one of the few stabilizing counters left.

Shareholder capitalism
In America, that bastion of shareholder centric capitalism, of all places people should understand that companies do not exist for the philanthropic purpose of bringing purpose and income to individuals - that is but a by-product of the firm’s pursuit of delivering returns to shareholders. If costs can be lowered by employing cheaper resources, the firm MUST do so – anything else would be a violation of the management’s fiduciary duty to shareholders. Keeping jobs in America is the firm’s discretion – it is not within the government’s charter. Valid as this is, there are really two America’s (if not more): the small elite finance class that truly has internalized this notion, and the vast majority that pats itself on the back for its practice of capitalism, but at the first hint of layoffs castigates greedy corporations and ‘Benedict-Arnold CEOs.’

The cheapest resources are invariably brought into the production of any good. Outsourcing is inevitable. In the case of agriculture, America has a whole parallel labor economy – in this case other assets of production are not alienable from America (land/proximity to markets). In the case of technology there are no inalienable assets; Americans have to choose whether they want to liberalize the labor market (a truer globalization) and let all the Indians come in who want in – something America has rejected with its draconian immigration system which has kept the inflow of hitech workers on a tightly controlled spigot and has made the very subsistence of poor Mexican farm laborers a crime – or watch as the jobs leave to India. But America can’t have it both ways.

[As an aside, the consensus view of globalization is farcical. There are broadly three markets, the market for goods and services, the market for capital and the market for labor. While there is plenty of popular support for the goods market, and the jury appears to be still out on the market for capital (generally a good idea, but there are some valid concerns with regard to speculative capital that causes a good deal of near term distress to developing economies), there is little popular support for a free market in labor. Immigration restrictions in particular and nationalism in general are severe inhibitors of the labor market and do a great disservice to the welfare of humankind. Nationalism is a counter-productive and out-dated concept – it creates wars and artificial conflicts, but now I really digress.]

In summary, outsourcing helps developing nations tremendously, makes America better off too (due to the benefits of trade), and is a better way to spread cherished American values of liberty around the world than imposing ‘democracy’ at the end of a gun barrel.

Sunday, September 26, 2004

The 'Liberal' Epithet

Orwell wrote an illuminating essay in 1946 “Politics and the English Language” about how the meaning of words can be changed and in so doing can corrupt thought. The assault on the term ‘liberal’ occurs to me to be a glaring instance in our own times.

Conservatives speak with outrage and indignation at anything that appears ‘liberal’ to them and the context and tone with which they use the term liberal itself speak volumes. The word ‘liberty’ which to me evokes thoughts of rights from the state and freedom to seek opportunity appears to conservatives to be the very bane of humankind. So why are conservative commentators so venomously attacking the word liberal? It appears Machiavellian to me that conservatives attack the very strength of their adversary: the universal legitimacy of freedoms that liberty enshrines, since liberty assaults their own narrowly defined ‘values,’ which should be identified for what they are, an assault on free will. The same liberty that stands for understanding, tolerance and compassion is an assault to the conservative orthodoxy that is judgmental and meddlesome.

Conservatives used to vulgarize the term using epithets to modify it, for instance ‘knee-jerk liberal,’ or ‘bleeding-heart liberal’ and more recently ‘Massachusetts liberal.’ Quite outrageously, ‘liberal’ itself has become the epithet in recent times with usages like ‘the most liberal senator,’ or ‘the liberal hospital in Berkeley.’ Pray how can a hospital be characterized as liberal?

The words liberal and liberty are so routinely abused that I frequently have to look it up in a dictionary to remind myself of its true meaning and I hope you will spend a few minutes reviewing it for yourself:
http://www.m-w.com/cgi-bin/dictionary?book=Dictionary&va=liberty

When I attempt to infer the meaning that conservatives attribute to liberal, I find that they either mean ‘gravy train’ or a catchall term for anything that violates their particular flavor of orthodoxy. (In the hospital instance, the speaker intended he usage in the sense that the hospital in question violated his sense of orthodoxy with its birthing techniques).

When you control the language, you control thought. By hijacking the meaning of words, conservatives are manipulating the terms in which we can have discourse and this must be aggressively resisted and rejected. There are perfectly good words in the English language which people may use to characterize what offends their values or orthodoxy (blasphemy and abomination come to mind), but the meaning of words such as ‘liberal’ cannot be permitted to change when the motive is to control thought.