IBKR Quant Blog


1 2 3 4 5 2 50


Quant

R Best Practices: R you writing the R way! Part II


By Milind Paradkar

In Part I the author walked us through installing R packages and organizing R libraries. In this installment he will show us vectorization.


5) Use a consistent style for data structure types – R programming language permits different data structures like vectors, factors, data frames, matrices, and lists. Use a similar naming for a particular type of data structure. This will make it easy to recognize the similar data structures used in the code and to spot the problems easily.

Example:
You can name all different data frames used in your code by adding .df as the suffix.

aapl.df   = as.data.frame(read.csv(file = "AAPL.csv", header = TRUE))
amzn.df = as.data.frame(read.csv(file = "AMZN.csv", header = TRUE))
csco.df  = as.data.frame(read.csv(file = "CSCO.csv", header = TRUE))

6) Indent your code – Indentation makes your code easier to read, especially if there are multiple nested statements like For-loop and If.

Example:

# Computing the Profit & Loss (PL) and the Equity
dt$PL = numeric(nrow(dt))

for (i in 1:nrow(dt)){
   if (dt$Signal[i] == 1) {dt$PL[i+1] = dt$Close[i+1] - dt$Close[i]}
   if (dt$Signal[i] == -1){dt$PL[i+1] = dt$Close[i] - dt$Close[i+1]}

}

7) Remove temporary objects – For long codes, running in thousands of lines, it is a good practice to remove temporary objects after they have served their purpose in the code. This can ensure that R does not run into memory issues.

8) Time the code – You can time your code using the system.time function. You can also use the same function to find out the time taken by different blocks of code. The function returns the amount of time taken in seconds to evaluate the expression or a block of code. Timing codes will help to figure out any bottlenecks and help speed up your codes by making the necessary changes in the script.

To find the time taken for different blocks, we wrapped them in curly braces within the call to the system.time function.

The two important metrics returned by the function include:
i) User time – time charged to the CPU(s) for the code
ii) Elapsed time – the amount of time elapsed to execute the code in entirety

 Example:

# Generating random numbers
system.time({

mean_1 = rnorm(1e+06, mean = 0, sd = 0.8)
})

user    system    elapsed
0.40      0.00       0.45

9) Use vectorization – Vectorization results in faster execution of codes, especially when we are dealing with large data sets. One can use statements like the ifelse statement or the with function for vectorization.

Example:
Consider the NIFTY 1-year price series. Let us find the gap opening for each day using both the methods (using for-loop and with function) and time them using the system.time function. Note the time taken to execute the for-loop versus the time to execute the with function in combination with the lagpad function.

library(quantmod)
# Using FOR Loop
system.time({

df = read.csv("NIFTY.csv")
df = df[,c(1,3:6)]

df$GapOpen = double(nrow(df))
for ( i in 2:nrow(df)) {

df$GapOpen[i] = round(Delt(df$CLOSE[i-1],df$OPEN[i])*100,2)
}

print(head(df))
})

Quant-R

 

# Using with function + lagpad, instead of FOR Loop

system.time({

df = read.csv("NIFTY.csv")

df = dt[,c(1,3:6)]

lagpad = function(x, k) {

c(rep(NA, k), x)[1 : length(x)]

}

df$PrevClose = lagpad(df$CLOSE, 1)

df$GapOpen_ = with(df, round(Delt(df$PrevClose,df$OPEN)*100,2))

print(head(df))

})

Quant-R

 

In the next installment the author will demonstrate how R programmers can fold a code of line or code sections.

Milind Paradkar holds an MBA in Finance from the University of Mumbai and a Bachelor’s degree in Physics from St. Xavier’s College, Mumbai. At QuantInsti®, Milind is involved in creating technical content on Algorithmic & Quantitative trading. Prior to QuantInsti®, Milind had worked at Deutsche Bank as a Senior Analyst where he was involved in the cash flow modeling of structured finance deals covering Asset-backed Securities (ABS) and Collateralized Debt Obligations (CDOs).

Learn more QuantInsti here 
https://www.quantinsti.com

This material is from QuantInsti and is being posted with QuantInsti’s permission. The views expressed in this material are solely those of the author and/or QuantInsti and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

 

 

 

 

 

 


22477




Quant

IBKR Live Event


Career Fair at Loyola University Chicago

Save the Date!


IBKR invites Engineering and Quant students from Loyola University Chicago to stop by our booth during the upcoming Career Fair.

Loyola University Chicago
Date: Wednesday, February 20
Time: 1:30-5:00 p.m. CST

Visit IBKR Careers page for a listing of Java, C++ or Python developer jobs.

 

The analysis in this material is provided for information only and is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad-based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation by IBKR to buy, sell or hold such investments. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.


22670




Quant

IBKR Traders' Academy Python Course - Chapter in Review


Python Traders' Academy

 

Learn Python with this IBKR Traders’ Academy course! Get started with the first chapter, What is the TWS API? and explore our Trader Workstation (TWS), as well as the TWS Application Programming Interface (API).

Next, watch the instructor demonstrate the hardware and software requirements for this course. Finish the chapter by testing your knowledge with a short, fun quiz!

Python

 

 

The analysis in this material is provided for information only and is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad-based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation by IBKR to buy, sell or hold such investments. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.


22710




Quant

Kavout - ESG Investing with AI


Environmental, social, and governance (ESG) investing is becoming more popular nowadays and making an impact on mainstream investing. One may find various definitions of ESG, as it is a relatively new concept in investing. Nevertheless, in essence, ESG investing is supposed to adhere to certain socially responsible principles with a focus on environmental, social, and governance criteria.

As these principles continue to shape corporate strategies and government policies, they are also bringing investor awareness, which in turns spurs the need for advisors to be well-versed in ESG investing.

Many financial institutions, including ETF providers, rating agencies, and asset managers, are rushing to provide clients with investment products claiming to provide ESG exposure. Among them are new indexes, thematic ETFs, and ESG portfolios. But as there exist more vehicles for ESG investing, investors must be aware that not all ESG products are created equal and be wary of the potential paradox of choices.

By its definition, ESG investing involves selecting a relatively small number of assets, as opposed to broad market diversification. Therefore, to take a simple passive investment in an ESG ETF (or passive ESG portfolio in general) would be merely concentrating assets while ignoring risk.

That is why active investment strategies are particularly suitable for thematic investing – not only to seek excess returns but also navigate through risky paths in the evolving market.

With advancements in big data analytics and cloud computing, a quantitative approach offers a great potential to gain competitive advantage in active investing. On that front, financial Machine Learning (ML) sits in the intersection of mathematics, statistics, and computer science. It is a branch of Artificial Intelligence (AI) that can automate statistical models and data analyses to learn from data and identify patterns. Drawing data from various sources, AI/ML models can be designed to analyze numerous companies through their financial statements, performance history, factors exposure, and market sentiment. This is a very powerful tool for active investors.

Therefore, algorithms can be designed to select thematic stocks with the highest growth potential with minimal human intervention. In addition, this data-driven approach can automatically update fundamental and quantitative analytics and determine optimal strategies as live data are continuously incorporated. Specifically, it can dynamically allocate investments across assets and rebalance holdings to seek maximum risk-adjusted returns.

As an experiment, let us consider a portfolio, denoted by KESG. It is constructed in a series of steps:

  1. select a collection of ESG stocks based on fundamental and quantitative analytics,[1]
  2. keep track of momentum of each ESG stock within the collection and pick a subset of ESG stocks that pass a pre-specified momentum threshold,
  3. rebalance once a month to invest in a new set of ESG stocks.

The portfolio is compared against two benchmarks – the iShares MSCI USA ESG Select ETF (SUSA) and iShares ESG MSCI EAFE ETF (ESDG). SUSA seeks to track the investment results of the MSCI USA Extended ESG Select Index while ESGD is supposed to track the MSCI EAFE Extended ESG Focus Index. Both indices are composed of U.S. companies with environmental, social and governance characteristics as identified by the index provider. For more information, please visit our website.

The potential of machine learning models and quantitative methods is not limited to ESG investing. In fact, it can well be applied to other thematic and non-thematic portfolios, such as dynamic sector rotation strategies, multi-factor tactical asset allocation, and more. Traditional investing and machine learning are not mutually exclusive. In fact, some of these portfolios are grounded in tried-and-true principles and established trading strategies, but they can be supercharged with machine learning and augmented with AI algorithms.

 

 

 

About Kavout

Kavout is a global InvesTech company, with a mission to empower institutions and investors with augmented intelligence to generate alpha, manage wealth and do more with less. Kavout’s services span data analytics and alpha generation, Kai-as-a-Service (a machine learning and deep learning services platform) and consulting services for customized solutions.

Kavout brings together a world-class team of research-minded financial experts, and AI and machine learning engineers to develop investment services of the next generation, utilized by top investment firms worldwide servicing millions of investors.


[1] Kavout has a proprietary stock rating system that processes vast and diverse data sets, and runs predictive models encompassing many methods such as regression, classification, deep learning, and reinforcement learning to produce a rating to rank stocks.

 

 

This material is from Kavout and is being posted with Kavout’s permission. The views expressed in this material are solely those of the author and/or Kavout and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

 


22606




Quant

IBKR Live Event


Career Fair at the University of Notre Dame

Looking for career opportunities in Java, C++ or Python? Stop by IBKR's booth at this recruiting event to learn more.

University of Notre Dame
Winter Career Fair
Date: Wednesday, February 13, 2019
Time: 4:00 PM CST - 8:00 PM CST

Visit the IBKR Careers page for a listing of Java, C++ or Python developer jobs.

Apply Today

 

 

The analysis in this material is provided for information only and is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad-based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation by IBKR to buy, sell or hold such investments. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.


22589




1 2 3 4 5 2 50

Disclosures

We appreciate your feedback. If you have any questions or comments about IBKR Quant Blog please contact ibkrquant@ibkr.com.

The material (including articles and commentary) provided on IBKR Quant Blog is offered for informational purposes only. The posted material is NOT a recommendation by Interactive Brokers (IB) that you or your clients should contract for the services of or invest with any of the independent advisors or hedge funds or others who may post on IBKR Quant Blog or invest with any advisors or hedge funds. The advisors, hedge funds and other analysts who may post on IBKR Quant Blog are independent of IB and IB does not make any representations or warranties concerning the past or future performance of these advisors, hedge funds and others or the accuracy of the information they provide. Interactive Brokers does not conduct a "suitability review" to make sure the trading of any advisor or hedge fund or other party is suitable for you.

Securities or other financial instruments mentioned in the material posted are not suitable for all investors. The material posted does not take into account your particular investment objectives, financial situations or needs and is not intended as a recommendation to you of any particular securities, financial instruments or strategies. Before making any investment or trade, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice. Past performance is no guarantee of future results.

Any information provided by third parties has been obtained from sources believed to be reliable and accurate; however, IB does not warrant its accuracy and assumes no responsibility for any errors or omissions.

Any information posted by employees of IB or an affiliated company is based upon information that is believed to be reliable. However, neither IB nor its affiliates warrant its completeness, accuracy or adequacy. IB does not make any representations or warranties concerning the past or future performance of any financial instrument. By posting material on IB Quant Blog, IB is not representing that any particular financial instrument or trading strategy is appropriate for you.