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)