1

After getting some projects approved, I have monthly reports I’m starting to run in R. I want to be able to manually kick off several lines of code. I believe this is best done with a user defined function, but I’m unsure of where to begin. Here is an example of what I would like to accomplish:

getSymbols("AAPL", src = "yahoo")

candleChart(AAPL, up.col = "black", dn.col = "red", theme = "white", subset = "2018-01-01/")

addSMA(n = c(10, 30)); addBBands()

Instead of executing each line or copy-paste from my notes to RStudio, I would like to make a function and enter the stock symbol:

Stock.Price(AAPL) 

and run all 3 lines. Can anyone point me in the right direction or a comprehensive example on the web? I’m used to working with packages and such, but just now breaking into some of the automation aspects.

2
  • Is there anything in those three lines of code that changes? For example, the subset = "2018-1-1", does that possibly need to be "2018-02-02" for another set of data? Commented Jun 11, 2018 at 15:05
  • It would just be the stock symbol "AAPL". I want to leave everything else as is for now. This type of function I'm planning on using for multiple projects...such as running functions from dplyr() and then forecast() with quick user defined inputs. Commented Jun 11, 2018 at 15:09

2 Answers 2

0

Functions in R are useful for getting rid of repeating lines of code and being able to quickly change variables. If you simply want to do what is outlined in your question then see the code below.

AAPL<-function(){

getSymbols("AAPL", src = "yahoo")

candleChart(AAPL, up.col = "black", dn.col = "red", theme = "white", subset 
= "2018-01-01/")

addSMA(n = c(10, 30)); addBBands()

return(NA)

}

StockPrice<-AAPL()

The return argument outlines what calculations and variables you want back from the function since these are not saved in the global environment. You do not need to return plots, they will simply be plotted.

Below is a more complex example of a function, where we assign variables A & B, and return a calculation of the two, to the variable that called the function. I think this is what is useful about functions in R.

My_Function<-function(A,B){

Test=A+B+4

return(Test)

}

Answer<-My_Function(1,2)
Answer_two<-My_Function(8,10)

Notice that we can call the function an infinite amount of times and assign any number we want to A and B, and the function knows anywhere there is A and B to plug in the values that were input during the call.

I'm not sure how the user is inputting the stock symbol, so I will approach this with a shiny solution.

#simulated input from user
UserChoice<-"GOOG"

Stocks<-function(Symbol,Symbol2){

getSymbols(Symbol2, src = "yahoo")

candleChart(Symbol, up.col = "black", dn.col = "red", theme = "white", 
subset  = "2018-01-01/")

addSMA(n = c(10, 30)); addBBands()

return(NA)

}


# By using simulated user input we can apply the function to basically any 
# four letter stock code by changing the `Stocks()` arguments.

if(UserChoice=="APPL"){
APPL<-Stocks(APPL,"APPL")

} else if (UserChoice=="GOOG"){
GOOG<-Stocks(GOOG,"GOOG")

} else {}

Note that Symbol and Symbol2 are the arguments to be passed to the function, Symbol2 is a character

Now, GOOG and APPL are created varaibles with nothing assigned, to make these equal to something,a variable needs to be assigned then returned from the function. Lets say we want to return the first line, just set it equal to a variable and then return it....

....
a<-getSymbols("AAPL", src = "yahoo")
.....
return(a)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! reviewing your code seems to work for a static stock symbol, but what I would like to do is make the data set called "AAPL" if the stock symbol that was entered is "AAPL". If the user enters (goog), I want to produce a data set called GOOG with the chart showing Google data. the first is a function that pulls and creates a data set called "AAPL". The second then plots the new data set AAPL. The last line just adds a layer to the graph. Thank you for the example of the multiple variables function. This is the next step in what I want to accomplish!
@caszboy Then change StockPrice to APPL, what do you mean if the symbol that was entered? Entered into what, do you have an interface?
Sorry. I edited my last post. Does that make a little more sense on my end?
Np, I'm still not sure how you are getting the user input choice, but I have edited my post to show how using two arguments symbol and symbol2 we can change the function to work with any four letter stock symbol the user enters. @caszboy
This worked with the last edit! Thanks so much Chabo ! I'm going to break down the mechanics on my end to apply to other functions I want to create. I'm also going to review the document from @JonGrub . Thanks again!
0

If I get you right, you want to start writing your own functions. A good resource to start is, in my opinion, this (Hadley Wickham & Garrett Grolemund: R for Data Science). But the basic is very simply:

Stock_Price <- function(x) {
  getSymbols("AAPL", src = "yahoo")

  candleChart(AAPL, up.col = "black", dn.col = "red", theme = "white", subset = "2018-01-01/")

  addSMA(n = c(10, 30)); addBBands()

  return(out)
}

I did not check your lines of code so this probably won't work. But there are just four parts you really need to think about (for now).

  • The name of the function. You can name a function by assigning the function definition with <- like you would do with an object. Function names should not contain dots anymore since this is reserved for methods (don't worry about it for now just use _ instead)
  • What goes into the function. This is the part in the brackets of function(). Usually people use x but you can use anything you want. If you want to supply more than one value to go into the function, seperate with comma: function(x, y). You should use this to supply all values that are needed to execute the code within the function, as things will likely fail otherwise.
  • The code inside the function. This code can be a few lines of code or something more complicated. I used your three lines of code and simply wrapped {} around it. everything inside {} will be executed when you call the function.
  • return. The objects created inside the function will be destroyed when R is finished executing the code. But it will return excatly one object. The one you supply to return. Alternativly, you can just write an object in the last line of the function to return it, but I would recommend you make things more explicit for now. For demonstration I simply returned your input back to the global environment which means it will be printed to the console.

If you run the function definition, it is stored in you global environment like any other object. What you can do to get it back after restarting R is to save the function definition in an R script and source it after you open R: source("path/to/script.R").

That should get you started.

1 Comment

R for Data Science seems like a great resource and I will have to read through it. I'm feeling like I should have explored functions in the beginning stages of learning R versus now. Thanks for the resource!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.