Site icon R-bloggers

Analyze Gold Demand and Investments using R

[This article was first published on R-Chart, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.


After the recent foray into stock analysis using quantmod, I thought it worthwhile to mention that the library can be used to analyze a wide variety of investments, including precious metals.  It is also worthwhile to mention that there are other possibilities for using R related to investment research that do not fit as neatly into the paradigm for which quantmod was designed.  You might be interested in knowing – as indicated by the chart above – that the demand for gold for dentistry has remained steady throughout the past year.

This is straightforward when dealing with ETFs and indexes that essentially function like stocks.  For example the XAU PHLX Gold/Silver Sector tracks the performance of a set of companies engaged in gold or silver mining.


library(quantmod)
loadSymbols(c(‘^XAU’, ‘GLD’, ‘IAU’))


chartSeries(GLD)


This index consists of stocks and so the chart can be handled like any other quantmod stock chart.

Exchange Traded Funds like GLD and IAU invest in gold and seek to track the price of gold.  One question I had was whether the IAU and GLD ETFs performed the same.  However, this does illustrate how easy this sort of comparison is to make using R.


chartSeries(GLD – IAU)


Other than occasional outliers – they do seem to track the same.  You can also directly query the price of gold using the getMetals function.  There is a limit on how much data can be obtained using this method – so you will need to specify a date range or an error will occur.



getMetals(‘gold’, from=’2010-01-01′)





However, there is a wealth of information that does not fit simply into the stock analysis model.  For instance, supply and demand – although reflected in the price of equities and volume of trading – is not directly being tracked and reported on in the example above.  It is also not apparent who might be interested in gold and why they might be interested in it. 


The World Gold Council and GFMS Ltd provide data on identifiable gold demand.  The original data and notes are available and provide definitions, terms of use and other relevant information. 



2009-Q1< o:p>
2009-Q2< o:p>
2009-Q3< o:p>
2009-Q4< o:p>
2010-Q1< o:p>
Electronics< o:p>
49.9< o:p>
60.2< o:p>
66.3< o:p>
70.1< o:p>
69.9< o:p>
Other Industrial< o:p>
16.0< o:p>
20.2< o:p>
17.8< o:p>
19.9< o:p>
20.3< o:p>
Dentistry< o:p>
13.1< o:p>
13.3< o:p>
13.3< o:p>
13.3< o:p>
13.0< o:p>
Bar Hoarding< o:p>
-28.1< o:p>
70.8< o:p>
85.6< o:p>
58.6< o:p>
89.7< o:p>
Official Coin< o:p>
69.4< o:p>
56.0< o:p>
48.9< o:p>
54.2< o:p>
50.0< o:p>
Medals/Imitation Coin< o:p>
3.9< o:p>
13.8< o:p>
17.7< o:p>
21.2< o:p>
17.2< o:p>
Other identified retail invest< o:p>
99.2< o:p>
48.2< o:p>
36.2< o:p>
50.5< o:p>
25.6< o:p>






The records above constitute the detail information without summarization or aggregation.  One unusual number I noticed was the negative number related to bar hoarding.  The best I can tell, this was a bit of an anomaly that occurred when individuals in certain countries sold off gold due to fluctuations in currency value.  In any case, this negative number is a point of interest as the various charts are rendered.  However, keep in mind, my purpose is not to provide financial interpretation of the data (and certainly nothing like investment advice of any sort).

The original data was – of all things – an image.  Therefore, the data is entered in as a matrix rather than scraping the web.  Row names and column names are assigned, and a chart can be created using base R functionality.  Rather than using a default R color palette, specific colors are assigned.


gold.demand=matrix(c(
49.9,60.2,66.3,70.1,69.9,
16.0,20.2,17.8,19.9,20.3,
13.1,13.3,13.3,13.3,13.0,
-28.1,70.8,85.6,58.6,89.7,
69.4,56.0,48.9,54.2,50.0,
3.9,13.8,17.7,21.2,17.2,
99.2,48.2,36.2,50.5,25.6), nrow=7,ncol=5, byrow=TRUE)

rownames(gold.demand)=c(‘Electronics’,’Other Industrial’,’Dentistry’,’Bar Hoarding’,’Official Coin’,’Medals/Imitation Coin’,’Other identified retail invest’)
colnames(gold.demand)=c(‘2009-Q1′,’2009-Q2′,’2009-Q3′,’2009-Q4′,’2010-Q1’)

barplot(gold.demand, legend=rownames(gold.demand),col = c(“lightblue”,”mistyrose”,”lightcyan”,”lavender”,”cornsilk”,”lightgreen”,”tan”),args.legend = list(x = “topleft”))
The chart indicates a general increase in demand (at least as far as can be seen due to the legend obscuring the top of the bars).  Instead, lets look at what is possible with ggplot2.

Bar charts in ggplot 2 require data in a different format – first transpose and reshape the data.  The t function is like magic when compared with this type of operation in other languages (like SQL).  All of three characters to pivot the data.


data=t(gold.demand)

The “melt” function in the reshape library breaks out the cross tab organization into individual records.
library(reshape)

melted_gold=melt(gold.demand)
colnames(melted_gold)=c(‘Name’,’Quarter’,’Value’)


Again, an exceedingly simple operation that illustrates the strength of R for manipulating data.


head(melted_gold)
                   Name Quarter Value
1           Electronics 2009-Q1  49.9
2      Other Industrial 2009-Q1  16.0
3             Dentistry 2009-Q1  13.1
4          Bar Hoarding 2009-Q1 -28.1
5         Official Coin 2009-Q1  69.4
6 Medals/Imitation Coin 2009-Q1   3.9


Now that the data is properly structured, the chart can be rendered.  

library(ggplot2)
qplot(Quarter, Value, data=melted_gold, fill=Name, geom=”bar” ) +
opts(title=’2009-2010 Gold Demand’)


The negative value stands out clearly here – and in the subsequent charts.

ggplot(melted_gold, aes(Quarter, Value)) 
    + geom_bar() 
    + facet_wrap(~Name, ncol = 2)

Industrial and electronic uses appear to be on the rise – but investment demand has dropped over the past year.  The same data with some color coding to differentiate uses and the bars flipped horizontally is a bit easier to read – particularly the x axis.

ggplot(melted_gold, aes(Quarter, Value, fill=Name)) + 
    geom_bar(stat=”identity”) + 
    facet_wrap(~Name, nrow=4) + 
    coord_flip()

R’s ability as a functional language to manipulate data objects is really amazing.  It is a bit of a paradigm shift for me.  I tend to think in terms of how the data structure might be created (make some loops, iterate through data reassemble a multidimensional array etc).  R’s functional capabilities (and well designed solutions by others) allow focus on what is being done rather than how.     The ggplot2 library really does have some marvelous capabilities as well.  There is a pretty clear separation of functionality between various function calls when assembling a graph.  The challenge remains making adjustments to “think in R” and quickly articulate the constraints of a problem and map this to a concise solutions that uses the language in the way it was intended.

To leave a comment for the author, please follow the link and comment on their blog: R-Chart.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.