Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Quantitative Finance with R

You're reading from   Learning Quantitative Finance with R Implement machine learning, time-series analysis, algorithmic trading and more

Arrow left icon
Product type Paperback
Published in Mar 2017
Publisher Packt
ISBN-13 9781786462411
Length 284 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
PRASHANT VATS PRASHANT VATS
Author Profile Icon PRASHANT VATS
PRASHANT VATS
Dr. Param Jeet Dr. Param Jeet
Author Profile Icon Dr. Param Jeet
Dr. Param Jeet
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Introduction to R 2. Statistical Modeling FREE CHAPTER 3. Econometric and Wavelet Analysis 4. Time Series Modeling 5. Algorithmic Trading 6. Trading Using Machine Learning 7. Risk Management 8. Optimization 9. Derivative Pricing

Functions

In this section, we will provide some examples of built-in functions that already exist in R and also construct a user-defined function for a specific task.

A function is a collection of statements put together to do a specific task.

R has a lot of built-in functions and users can define their own functions.

According to their requirement, in R, the interpreter passes control to the function object along with the arguments required for the accomplishment of the task designated for the function. After completing the task, the function returns the control to the interpreter.

The syntax for defining a function is as follows:

>function_name<-function(arg1, arg2,...){ 
>+function body 
>+} 

Here:

  • Function name: This is the name of the defined function and is stored as an object with this name.
  • Arguments: Arguments are the required information needed for the function to accomplish its task. Arguments are optional.
  • Function body: This is a collection of statements that does the designated task for the function.
  • Return value: The return value is the last expression of a function which is returned as an output value of the task performed by the function.

Please find here an example of some of the inbuilt functions along with their results when executed:

>print(mean(25:82)) 
[1] 53.5 
>print(sum(41:68)) 
[1] 1526 

Now we will look at how to build the user-defined functions. Here we are trying to find the square of a given sequence.

The name of the function is findingSqrFunc and takes the argument value, which must be an integer:

>findingSqrFunc<-function(value){ 
>+for(j in 1:value){ 
>+sqr<-j^2 
>+print(sqr) 
>+} 
>+} 

Once the preceding code gets executed, we call the function:

>findingSqrFunc(4) 

We get the following output:

[1] 1 
[1] 4 
[1] 9 
[1] 16 

Calling a function without an argument

Construct a function without an argument:

>Function_test<-function(){ 
>+ for(i in 1:3){ 
>+ print(i*5) 
>+ } 
>+ } 
>Function_test() 

On executing the preceding function without arguments, the following output gets printed:

[1] 5 
[1] 10 
[1] 15 

Calling a function with an argument

The arguments to a function can be supplied in the same sequence as the way it has been defined. Otherwise the arguments have to be given in any order but assigned to their name. Given here are the steps for creating and calling the functions:

  1. First create a function:
            >Function_test<-function(a,b,c){ 
            >+ result<-a*b+c 
            >+ print(result) 
            >+ } 
    
  2. Call the function by providing the arguments in the same sequence. It gives the following output:
            >Function_test(2,3,4) 
            [1] 10 
    
  3. Call the function by names of arguments in any sequence:
            >Function_test(c=4,b=3,a=4) 
    

This gives the following output:

[1] 16 

How to execute R programs

In this section, we will discuss different ways of executing R programs.

How to run a saved file through R Window

For running a program in the R workspace, follow these steps:

  1. Open R (double-click on the desktop icon or open the program from Start).
  2. Click on File and open the script.
  3. Select the program you want to run; it will appear in an R Editor window.
  4. Right-click and Select All (or type Ctrl + A).
  5. Right-click and Run Line or Selection (or type Ctrl + R).
  6. The output will appear in the R console window.

How to source R script

Please perform the following steps for sourcing the R code:

  1. First check your working directory. It can be checked by the following code:
            >print(getwd()) 
    
  2. On running the preceding code, if it gives the path of the designated folder, it is fine. Otherwise, change the working directory by using the following code:
            >setwd("D:/Rcode")  
    
  3. Change the destination directory according to your need and then run the required code using the following code:
            >Source('firstprogram.r') 
    

For example, let's say the program firstprogram.r has the following code in it:

  a<-5 
print(a) 

Upon sourcing, it will generate the output 5 at the console.

When you want to tell R to execute a number of lines of code without waiting for instructions, you can use the source function to run the saved script. This is known as sourcing a script.

It's better to write the entire code in Studio Editor and then save it and source the entire script. If you want to print an output in source script then please use the print function to get the desired output. However, in the interactive editor, you do not need to write print. It will give it by default.

In other operating systems, the command for running the program remains the same.

Comments are parts of a program that are ignored by the interpreter while executing the actual program.

Comments are written using #; for example:

#this is comment in my program. 
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime