Friday, April 26, 2013

Currency: Basket vs. USD




Here's Brazil, Japan and China. Some notes:
  1. A 75% devaluation in the real vs. the dollar from 2001 to 2003. Wikipedia tells me a potential presidential candidate with hopes of defaulting on Brazilian debt caused an economic slowdown and a flight from the real. The real-dollar FX rate decreased as the US trade deficit sweeled from '02-'08.
  2. The yen is confusing. It was least valuable in 2002, peaking during the asset price bubble in Japan. A good look at why the yen strengthened from '08-'11 is here. It was written in 2011, so since we're in 2013, it's worth a chuckle to read this excerpt from the article:

    "In summary, the yen is a highly suitable candidate for the risk averse investor, and there is little chance of yen holders being sandbagged by a dramatic policy change along the lines of what the Swiss did.  The safety of yen holdings will only be endangered when Japanese officials at the Finance Ministry and Bank of Japan agree that there is no more urgent priority than a much weaker yen."

    Of course, this is exactly what happened as the BoJ is doubling-down on Fed inflationary policies. The yen seems to do its own thing, so I'm not going to worry too much about it.
  3. The yuan is not a floating currency. It was pegged to the dollar until around 2005, as can be seen by the constant line in yuan-dollar FX chart. After that, China devalued the RMB to help industry (by encouraging exports). The common story is that China wants the RMB as an international reserve currency, which requires the RMB to float. Capital controls (that is, Chinese government controls on where/when/how much on of the RMB can be used internationally?) aim to manage market valuation. Rather than having everyone decide what the yuan is worth, China gets to decide. For now, the yuan is relatively strong against the dollar.

Failing Upwards in R: Plotting Multivariate Time Series and '02-'08 Dollar Devaluation

My confusion with plotting in R originates from how many plotting methods exist. plot(), plot.xts(), plot.zoo(), ggplot(), and so on. Some problems:
  1. They take different formatting arguments in the plot() call. For example, plot.xts takes plot.xts(major.format="", minor.ticks="", ...) to format ticks on an axis. plot.zoo doesn't do it this way, and I still don't know how plot.zoo does it.
  2. plot.zoo plots multivariate time series on the same plot easily where plot.xts can't by using the plot.type="single". Here's what I can do so far,
    using plot.zoo:

    Labeling is a problem. Blue is pound, red is euro. Using plot.xts:


    Minor ticks in xts are easy to clean up, needless to say.
The series go from about 2000-'13. The '09 recession causes about an 18% drop in USD's to Euro. Before the crash, one euro bought about 1.6 dollars. After the crash, one euro bought about 1.3 dollars. The euro was made official currency of the Euro-zone in 1999 and it dropped to under $1 after inception. Since 2003, it's risen and stayed above $1. First glance, I'm having trouble understanding the rise from 2002-'08 in the exchange rate. The dollar depreciated and/or the euro+pound appreciated, even in a boom time in the US. This helps, but this is even better. The dynamic described in the latter goes like this:
Large US trade deficits -> excess dollars overseas -> can't/don't spend all USD in the US -> selling pressure on over-abundance of dollars


From that, devaluation. Set the start date in these charts from tradingeconomics to 2000 to see why you might not want to be in dollars (or more specifically, why you might have too many).

Source: tradingeconomics.com


Source: tradingeconomics.com









Wednesday, April 24, 2013

Currency: Building Up the Trade Weighted USD Index

I know nothing about relative currency strengths historically or present day. I won't need the Vietnamese "dong" (missing accents), the Malaysian "ringgit" or the Moldovan "leu" so I'm going to stick with the US for now.
In everything I've seen, currencies are measured relative to other currencies. The dynamic goes something like this. Stipulating two countries, Country A and Country B. Country A uses the "Adollar" and Country B uses the "Bruple" as their currencies. In year 1, you can exchange 1 Adollar for 1 Bruple. Year 2, Country A raises interest rates and Country B floods into Adollars and out of Bruples to grab the excess yield. Increasing demand for Adollars (and less for Bruples) means the value of an Adollar has increased (and Bruple has decreased), which means more Bruples are needed to exchange for 1 Adollar, and the Adollar is "strong" relative to the "weak" Bruple.
Some 101 causes for strength and weakness in currencies:

  1. Relatively high interest rates => relatively strong currency, relatively low interest rates => relatively weak currency.
  2. Volatility in government. Leading the Failed State Index according to Wikipedia is Somalia, and the USD to Somalian Shilling exchange rate reflects the volatility involved. The graph, courtesy of FRED, says that in 2000, 20K Shillings bought $1 and in 2010, that number jumped to 32K Shillings buying $1. Note that this is a ratio of x/y. Increasing x can produce the same ratio as decreasing y. In the case of shillings/dollar, we know that the dollar is relatively stable in comparison to the shilling, because, you know, Somalia isn't a vacation home. In other cases, this could be a bit more convoluted when dealing with more stable governments (such as British pounds/dollars).

  3. Relevant today is inflationary policy from the central banks. Buzzword of 2013 "Abenomics" and the BoJ has devalued the yen significantly with more aggressive inflationary policies than the Fed. Even if both are inflating their currency, more aggressive inflation will make it a relatively weaker currency.
The recurring word is relative. Currencies are measured against a benchmark. That can be another countries currency or the same currency at a specific point in time (how many 2000 dollars would buy a 1980 dollar).

The question then becomes choosing a relevant benchmark for comparison. One of those benchmarks is the Trade Weighted USD Index (also known as the "broad index". The idea is to aggregate values of many different currencies to get a broad (index) view of how the buck is doing in comparison to a basket of other currencies. The basket is weighted according to trade data, which I take to mean that currencies are weighted based on how relevant they are to US trading globally, so the euro, yuan, pound and yen take up most of the index weight compared to the Swiss franc or Vietnamese dong (if even included). This means that movements in the euro, yuan, pound and yen will more heavily affect the index calculation than the dong and franc.
Here's the broad index in action, again, from FRED:

The USD was relatively strong compared to the currency basket of the Broad Index from '97 to '08 (being above 100). The recessionary period from '08-~10 is an example of the relative nature of currency measurement (at least, in the Broad Index form). Although the US was in recession, so was everyone else. In global uncertainty, being in USD makes more sense than being in less stable currencies because there's a pretty strong expectation of the dollar being around tomorrow and that it won't be allowed to be destructively volatile. Another interesting implication comes from the deductive nature of economics (this leads to that which leads to something else which affects blank). Currency devalues. When a currency devalues against a second currency, that second currency can buy more of the first currency. Demand rises which strengthens the devalued currency, and the circle completes. 
As far as the calculation goes, the Broad Index is a geometric mean that multiplies together weighted period-to-period changes in single currencies. The result is then multiplied by the index value at the last calculation (ie, t-1 for period t) to get a new index value. A variation on the TWEXB adjusts for real exchange rates. Whenever "real" is involved, inflation is factored in. The TWEXB based on real exchange rate includes a ratio of the basket currency CPI to the US CPI at the periods t and t-1, which affects the period-to-period changes in single currencies. Blah.

Next time, I'll look at USD against a bunch of currencies individually.




Saturday, April 13, 2013

Failing Upwards in R: Time Series

My plan was to learn R through individual projects. I wanted to look at a bag of various commodity producers and see how/if correlate. I've spent 7 of the last 24 hours trying to figure out time series and how to plot them in R. Here's what I have:

The index in xts is the date. You can call the dates using index(ofinterest). The output from that seems to be a list, at least, that's the interpretation a Python experience gives you because you can choose a (subindexed?) element by foo=index(ofinterest) and foo[i] calls the ith element in foo. That's a list in Python.

The problem is that given two time series that start at different times, such as Series 1 with range 1980-2000 and Series 2 with range 1990-200, I can't overlay them on the same graph. I've hit it two ways:

1. Merged the date series (the intervals were diffferent) into a single series so that all y points had an x coordinate, and then tried to plot S1 and S2 with respect to that single date series. Obvious problem results in that x-y isn't one-to-one and the plotter doesn't like that. Possible solution is to insert nulls to equate x and y lengths. I don't know how to go about that yet. Start simpler, maybe.

2. Merged the xts series for each ticker and pray it plots. Merge doesn't work like I thought it did. I thought merge would create a single series of closing prices, but it seems to have created a matrix of submatrices. Likely incorrect on that.

I think I'm starting a bit ambitious for someone with limited experience, but I don't know a simpler project of interest. Date formatting in all languages still confuses me, so that's not a great sign. 

Friday, April 12, 2013

Corporate Swag

Rio Tinto is a $90B cap mining company. It would rank 63rd in a list of GDP by country (according to 2012 IMF data in Wikipedia), in front of Libya.

That's the Rio Tinto river in Spain, namesake of the corporation. The Rio Tinto plays host to significant mining in antiquity and present (ironically, Rio Tinto doesn't own these properties present day) and the red hue comes iron dilution into the river. The acidity of the river clocks in with a pH of 2, making it equivalent to lemon juice. Naming your mining company after the most significant downside of your industry and then rising to the top of that industry takes stones.

Wednesday, April 10, 2013

Failing Upwards: R

Two facts:
1. I started using R today.
2. I can do everything I was doing in Python in R already.

That probably means I should learn R. I'm going to jot down my difficulties and successes with R here.

Super convenient for financial data. I don't know if you need the quantmod to do this, but I'm working through R basics, specifically with plotting and data types. Data types, environments I just got done with OOP approach in figure plotting with Python. R plotting seems to be more about adding layers onto a base.


  • The default datatype in downloading from Yahoo Finance using the quantmod command GetSymbols() is xts (extensible time series). The interesting thing is that the dates (corresponding to the data columns) seem to serve as an index rather than an independent data column. More specifically, asking for the 0th column of a xts data matrix will print out ordered dates (R doesn't index 0 as the first entry, like Python).
    I don't know whether that means the inherent dates are inaccessible as an independent set of data (and the general rule of programming I know so far is that nothing is impossible, it just ranges in difficulty).
  • (daily, weekly, monthly)Returns is an AWESOME function.
  • The plot function weirds me out. After more time than I'd like to admit, I produced this:

GMO is in blue, TC is in black. Haven't cracked legends yet, or effective axis labeling. The divergent spread towards the end is interesting. I think that might be the Endako mine slough, which was a problem for TC (marginal when compared to the $14 to $3 long-term decline). The x-axis is labeled poorly enough that I can only say the relative steepness of decline from 2010 to 2012 is worth looking at. Does market pressure effect development stage companies consistently less intensely than production stage companies? If I want limited mol exposure, is it worth taking development stage downside risk to have a less volatile play at mol?The short answer is that if you don't want mol volatility, you probably shouldn't be interested in mol anyway.

Back to the plot function, it works by calling a "higher-level" function that creates the plot. "Low-level" functions are used to add onto it. In the figure above, the high-level plot calls on TC stock and limits the plot based on that data. The low-level addition using the lines() function calls GMO. If the high-level plot used GMO, I would have a plot ranging from $0-6 as y-limits and TC would largely wander off the chart as the low-level addition. I haven't figured out what edits the higher-level plot yet, although the "par" function seems a likely candidate.

  • The focal point on R seems to be in manipulating tabulated data. Specific entries are easily accessible along with parsing data for traits or eliminating outliers. It's simple and intuitive for that purpose.
  • It feels like there's some overlap in the utility of basic functions. I'm sure there's a reason, but from the rookie perspective, it's confusing.
My logic is that if I take the time to figure out visualizations before everything else, I can see the mistakes I'm making later on. Upwards!

Saturday, April 6, 2013

Adventures in SQL:

Adventures in SQL: Genesis



SQL=Structured Query Language

via thefreedictionary.com...


Structured=Having a well-defined structure or organization; highly organized; arranged in a definite pattern.

Query= A question; an inquiry; to mark an item with a notation in order to question its validity or accuracy.

(Programming) Language= An artificial language used to write instructions that can be translated into machine language and then executed by a computer

I'm going to walkthrough a posting on SQLcourse.com, which was chosen by being one of the first google results.

SQL is used to communicate with a database. 

A database is an organized collection of information where specific entries are accessible via programs. Webopedia calls it an "electronic filing system". SQL is one of those programs that can access a database. About.com claims that databases consist of tables analogous to Excel rows/columns. More importantly, databases allow for large-scale operations in a way that spreadsheets are not conducive towards.

According to ANSI (American National Standards Institute), it is the standard language for relational database management systems.

A useful definition from google for relational database management systems: a database management system designed to manage a relational database. Here's a more useful rundown. A relational database seems to eliminate problems similar to "magic numbers" in programming. If you have code that uses a factor of 5 multiple times, it is usually better to define a variable of 5 once and call the variable. Change the variable, and you've changed all the entries.
Here's a table from the dummies site that I liked.

DeptNoDeptName
10Marketing
20Purchasing
Table 3: A Sample Relational EMP Table
EmpNoENameDeptNo
101Abigail10
102Bob20
103Carolyn10
104Doug20
105Evelyn10

Eliminating employees in the Marketing department would not eliminate the marketing department. The first table is a reference for the second table and centralizes more of the relevant information.


 SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc.

Isn't a ton to this. SQL can do things to databases. A database stores things. Therefore, SQL is useful for modifying databases. There are many types of databases and SQL is often employed to manipulate them.


 Although most database systems use SQL, most of them also have their own additional proprietary extensions that are usually only used on their system. 

SQL is tweakable to specific problems.

However, the standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used to accomplish almost everything that one needs to do with a database.

Self-explanatory.


Have to start somewhere, huh?