[R-SIG-Finance] Using quantmod to calculate returns on multiple stocks and save in new variable
josh.m.ulrich at gmail.com
Sun Sep 12 15:41:36 CEST 2010
On Fri, Sep 10, 2010 at 2:38 PM, Keith Peter <kbpeter21 at gmail.com> wrote:
> Quick help question from a newbie.
> I have the script below where I am trying to collect the one day returns for
> many stocks into a new variable. You can see below where I have to hand
> enter the tickers into the column extraction function Cl() in quantmod. I'm
> looking for a line that recognizes the tickers already. I've tried a variety
> of things to create this code with no luck.
> 1) Is there a search feature on the R-SIG archive because I imagine this one
> has been addressed already? Going through the archive by hand is tedious.
I use www.rseek.org. Type your query, hit <Enter>, then click the
"Support Lists" tab on the results page.
> 2) What is the loop/function to recognize the length of the Tickers object
> and then feed the closing prices into the variable "closepx."
I'm not exactly sure what you mean by your question, but I think this
line does what you want.
closepx <- do.call(merge, lapply(Tickers, FUN=function(ticker) Cl(get(ticker))))
1) lapply() applies "FUN" to each element in "Tickers" and returns a list.
2) "FUN" takes one argument, "ticker" (the element from
"Tickers", which is the name (a string) of the object), and uses
get() to return the object with that name. You know what Cl() does.
3) do.call() constructs and executes a call to merge() for all the
objects whose names are listed in "Tickers"--based on the results of
the call to lapply().
> 3) If I plan to do this with hundreds of stocks, is this the most efficient
> way to do it?
I don't know if this is _the most_ efficient, but it should be close
enough. It takes ~0.3 seconds to merge 500 tickers on my 2.2Ghz
> Thanks in advance.
> #have an open excel sheet with QCOM,MSFT,ORCL,AAPL,IBM in column A#
> #I plan to pull the list from a *.csv file because it seems easier to hand
> enter the tickers in excel and save# Maybe there is a better way?
> *A function or loop (if best) that recognizes the length of Tickers and
> feeds each of them into the Cl(() to closepx.
> [[alternative HTML version deleted]]
> R-SIG-Finance at stat.math.ethz.ch mailing list
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions should go.
FOSS Trading: www.fosstrading.com
More information about the R-SIG-Finance