IBKR Quant Blog


1 2 3 4 5 2 15


Quant

SGX - Update on India: Accessing the World's Fastest Growing Large Economy via Offshore Futures in 2018


Join us for a free webinar with Tariq Dennison, QuantOfAsia, on May 23, 2018 4:30pm HK
 

Register


By some measures, India has surpassed China as the world’s fastest growing large economy, but it is still one of the most difficult stock and currency markets for foreign investors to access. This webinar discusses how to use offshore SGX-listed futures to trade India following this year’s updates and explains how the new SGX India Futures work.

Presented by Tariq Dennison, GFM Asset Management, QuantOfAsia,

Sponsored by Singapore Exchange

SGX-GFM


Information posted on IBKR Quant that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Quant are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.


17922




Quant

Quantra by QuantInsti presents Automated Trading using Interactive Brokers TWS and IBridgePy, an open-source Python software*


By Milind Paradkar

For those Python enthusiasts interested in using open-source software IBridgePy*, Quantra by QuantInsti® presents a free course "Automated Trading with IBridgePy using Interactive Brokers Platform".

The focus of this course would be on the applicability of IBridgePy, which is an open-sourced software used to connect to Interactive Brokers C++ API for execution of Python codes. It is free and available on Quantra, and it includes detailed lessons on using the IBridgePy API.

The topics covered are on:

  • How to install and configure Python environment and IBridgePy
  • Learn the syntax and functions for conducting various operations like fetching and handling data
  • Learn various steps involved to correctly fetch historical and real-time data from Interactive Brokers servers into your setup
  • Learn about different types of orders and how to place them using IBridgePy*
  • Learn to code, test and implement a trading strategy on Interactive Brokers platform using IBridgePy*

Quantra-Python

 

Visit Quantra by QuantInsti® to enroll for this free course*.

 

*Disclaimer: This software does not directly use IB's Python API, but instead uses the third party module IBridgePy. IBridgePy is an open-source Python software and is in no way affiliated, endorsed, or approved by Interactive Brokers or any of its affiliates. It comes with absolutely no warranty and should not be used in actual trading unless the user can read and understand the source.


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).


This article is from QuantInsti and is being posted with QuantInsti’s permission. The views expressed in this article are solely those of the author and/or QuantInsti and IB is not endorsing or recommending any investment or trading discussed in the article. This material is 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 IB 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.


17968




Quant

Actuaries Versus Quants


By David J. Merkel, CFA, FSA, Aleph Blog

I’m an Actuary and a Quant.  I’m not an Actuary, and I’m not a Quant.

I suppose I could do the other two permutations.  I won’t, but I will explain.

I passed all of the exams from the Society of Actuaries to become a Fellow in the Society of Actuaries.  I maintained that credential for around 18 years by paying my dues.  Oddly, once I stopped paying my dues, and thus ceased to be a Fellow, I got more requests to be on committees, and give talks to the Society of Actuaries.  Things that I recommended to the Society 20 years ago are finally getting a serious hearing now.  My main suggestion that actuaries should have to pass a writing test is at least floating among some thinkers at the Society.

Why a writing test?  The ability to express ideas verbally to those who may not have a strong math background is important, and correlates with other social skills that aid in leadership.  The Society of Actuaries at one time (not sure when) did have an English test, and in that era, actuaries were not merely math nerds, and many of them were leaders in insurance and pensions.

So, I am no longer a Fellow in the Society of Actuaries.  I am still an actuary.  The way I reason and use math to solve investing and other problems stems from the skills that I learned when practicing as an actuary.  As actuaries went, I was a generalist, and would enjoy tackling unusual and multi-disciplinary problems.  The problems I liked best were the toughest ones — the ones where there is no easy answer, some degree of qualitative reasoning must be employed, and new techniques created.

Unlike most actuaries, I know the investment math relatively well, which makes me a Quant [quantitative analyst].  But I am not a Quant, or maybe, I’m a skeptical Quant.  Why?  I don’t believe that Modern Portfolio Theory is right.  In general, higher returns are achieved by taking moderate risk, not low or high risk.  More risk does not mean more return after some point.

Also, markets are more complex than the Quants will generally accept.  Disturbances are not normally distributed.  Variances of stock returns are infinite, but normality is used in order to get tractable results.  Markets sometimes fail to trade in a continuous manner.  There are jumps/falls in prices far greater than a normal distribution would expect.  And that gets borne out by the greater volatility of markets close to open, than open to close.

So I am a skeptical Quant at best, but if someone asks me whether I am an Actuary or a Quant, I will say I am an Actuary.  Why?

The main thing is differences in method.  Actuaries believe in table stability; Quants believe in bicycle stability.  Actuaries look at the cash flows, and make minimal assumptions about markets continuing to operate.  Quants usually assume that market continue to operate.  Actuaries look long-term, and do stress-testing.  Quants look short-term, and do hedging.

This is one reason why few pure insurance companies failed during the crisis, while many banks did.  If assets and liabilities are matched, it is hard to have a run on the company, aside from credit events.

Actuaries think long-term, while Quants think short-term.  In the short-run, listening to the Quants will yield greater profits.  In the long-run, listening to the actuaries will yield greater profits.

There’s one more issue.  Actuaries have an ethics code.  Quants don’t.  (Quants that are CFAs have an ethics code, but most aren’t CFAs.)  Actuaries are supposed to act in the best interests of clients.

In my opinion, Wall Street would be far better of replacing their Quants in risk control positions with Actuaries.  Actuaries have a public policy interest, and would not merely bend to the needs of the company.  They would cut back risk positions far more than the Quants do.

I know this only makes sense to Wall Street if they are willing to adopt a stable model.  Actuaries would help to stabilize things, and a focus on long-term stability would aid Wall Street.

But if forced to choose: I am an actuary, I am not a quant!

-------------------------

About David Merkel

Learn more about Aleph Blog here:  http://alephblog.com/

David J. Merkel, CFA, is a Registered Investment Adviser through his firm, Aleph Investments, LLC.  He shares most of his views through his blog Alephblog.com.  He writes on equity and bond portfolio management, macroeconomics, derivatives, quantitative strategies, insurance issues, corporate governance, and more. His specialty is looking at the interlinkages in the markets in order to understand individual markets better. Formerly he worked as Director of Research for Finacorp Securities. He was a leading commentator for the investment website RealMoney.com. David was a senior investment analyst at Hovde Capital, responsible for analysis and valuation of investment opportunities for the FIP funds, particularly of companies in the insurance industry. He also manages the internal profit sharing and charitable endowment monies of the firm. Prior to joining Hovde in 2003, Merkel managed corporate bonds for Dwight Asset Management. In 1998, he joined the Mount Washington Investment Group as the Mortgage Bond and Asset Liability manager after working with Provident Mutual, AIG and Pacific Standard Life. His background as a life actuary has given David a different perspective on investing. Merkel holds bachelor’s and master’s degrees from Johns Hopkins University.

This article is from David J. Merkel, CFA, and is being posted with Mr. Merkel’s permission. The views expressed in this article are solely those of the author and/or Mr. Merkel’s and IB is not endorsing or recommending any investment or trading discussed in the article. This material is 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 IB 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.


17925




Quant

The Continuous Evolution of Bitcoin and Blockchain


By Dan Gramza

When most people think of cryptocurrencies, they think of bitcoin.  Although it is one of the most popular cryptocurrencies, there are over 1,600 cryptocurrencies. The applications of bitcoin and the other cryptocurrencies are constantly evolving. 

Bitcoin is being recognized as legal tender by some governments.  For example, Japan recognized bitcoin as legal tender in April 2017.  Bitcoin is illegal as a payment tool in some countries, such as Iceland.  Indonesia, India and Bangladesh.   

Cryptocurrencies continue to develop as a lifeline for undeveloped countries plagued with hyperinflation and failed government monetary policy. There are number of countries or organizations that are using cryptocurrencies as a tool to try to solve economic issues.  Examples of countries that are currently using a cryptocurrency or are contemplating using cryptocurrencies are Ecuador, Argentina, Palestine, Marshall Islands, Dubai, Zimbabwe, Senegal and Venezuela.

These special use cryptocurrencies are typically identified as that country’s currency. On the surface, the use of cryptocurrencies in this fashion may seem to alleviate some of the challenges that country may be facing on the local and global market. Some countries are considering cryptocurrency based crude oil transactions to eliminate potential control by the US government of US dollars used in crude oil transactions.  However, new challenges can arise. Just because a country has created a cryptocurrency it does not mean the global marketplace will accept it.  For example: Venezuelan President Nicolás Maduro announced the creation of a virtual currency in an effort to ease the country's economic crisis and the Trump administration prohibits US purchases of the Venezuelan Petro Cryptocurrency.

Another evolutionary trend is the backing of a cryptocurrencies with hard assets, such as diamonds and gold, as a way to create a feeling that there is something supporting the cryptocurrency other than the hope that someone else will be willing to pay a higher price for the cryptocurrency. The Israel Diamond Exchange is launching diamond-backed cryptocurrency. 

A potentially hazardous evolution is when the price of a bitcoin is used as a basis to determine the price of another cryptocurrency.  An example of this is the use of bitcoin prices in the valuation of Tether which is supposed to be back by US dollars.  The movement of Tether could have the potential to artificially inflate bitcoin’s price and any other cryptocurrency that is basing its price on the bitcoin’s price.

Bitcoin is a worldwide payment system which verifies bitcoin transactions by recording a transaction in a record system (distributed ledger) called a blockchain. Blockchain is a network of peer-to-peer connected computers. The bitcoin network of peer to peer computers use software to connect them to each other over the internet to the other computers running the same software.  This software creates a network of computers that can communicates with each other, relaying information about and recording new transactions to the bitcoin blockchain.  Once a new a block of valid transactions is confirmed it is distributed to all of the computers on the network.  Bitcoin ownership is followed in the Bitcoin Blockchain through Bitcoin addresses.  

Blockchain architecture is being used to explore non-cryptocurrency applications.   Here are a few examples of blockchain applications that are currently being used or being considered: fighting art forgers, tracking ownership and royalty payments in the music industry, DeBeers tracking diamonds production cycle, land and marine shipping industries tracking shipments, restaurant loyalty programs, Coca Cola certifying suppliers, clearing of stock trades on the Australian Stock Exchange, Dubi recording local real estate contracts, Hong Kong tracking trade financing and  Kodak looking to protect  registered images or photographs.

Blockchain is also going through an evolution.  Hashgraph, like blockchain, is a distributed ledger, with the expectation that hashgraph could be a faster and cheaper alternative to the blockchain.

Hashgraph, and the similar IOTA and ByteBall, rely on Directed Acyclic Graphs (DAG) to follow transactional information flow. Hashgraph’s DAG records information in a timed series. This means that the record of each transaction is dependent upon the order of all the previous transactions in the series.

This also means this new network can efficiently operate with massive amounts of data such as stock trades. It is the users of the DAG that confirm transactions for one another instead of relying on blockchains outside “miners.” Bitcoin blockchain requires transactions to be assembled in 1 megabyte blocks which can throttle back its capability of handling large amounts of data quickly. Hashgraph’s ledger does not bundle transactions which increases its efficiency and speed. Since every hashgraph user participates in confirming transactions, transactions are processed as they come in, meaning large amounts of data can be processed in a second compared to the Bitcoin blockchain which is much slower.

With the learning curve and technology enhancements for cryptocurrencies and distributed ledgers increasing at an exponential rate with no sign of slowing down means that it is important for investors and traders to stay up-to-date by monitoring the evolution of these markets.

 

----------------------------

Dan at Gramza is President of Gramza Capital Management Inc. and DMG Advisors, LLC. He provides daily market updates from around the globe on subjects ranging from the Nasdaq and currencies to crude oil and grains dangramza.com.

 

Click here to learn more about Gramza Capital Management, Inc.

 

This article is from Dan Gramza and is being posted with Dan Gramza’s permission. The views expressed in this article are solely those of the author and/or Dan Gramza and IB is not endorsing or recommending any investment or trading discussed in the video. This material is 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 IB 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.

 

These financial products are not suitable for all investors and customers should read the relevant risk warnings before investing. You should be aware that your losses may exceed the value of your original investment.
TRADING IN BITCOIN FUTURES IS ESPECIALLY RISKY AND IS ONLY FOR CLIENTS WITH A HIGH RISK TOLERANCE AND THE FINANCIAL ABILITY TO SUSTAIN LOSSES.
More information about the risk of trading Bitcoin products can be found on the IB website.


17912




Quant

Time Series Analysis: An Introduction In Python


Time Series Analysis

In this blog, we will see basic time series operations on historical stock data. Our main focus will be on generating a static forecasting model. We will also check the validity of the forecasting model by computing the mean error. However, before moving on to building the model, we will briefly touch upon some other basic parameters of time series like moving average, trends, seasonality, etc.

Fetching Data

For the purpose of this blog, we will take past five years of 'adjusted price' of MRF. We will fetch this data from yahoo finance using pandas_datareader. Let us start by importing relevant libraries.

import pandas as pd
import pandas_datareader as web
import matplotlib.pyplot as plt
import numpy as np

Now, let us fetch the data using DataReader. We will fetch historical data of the stock starting 1st Jan 2012 till 31st Dec 2017. You can also fetch only the adjusted closing price as this is the most relevant price, adjusted for all corporate actions and used in all financial analysis.

stock = web.DataReader('MRF.BO','yahoo', start = "01-01-2012", end="31-12-2017")
stock = stock.dropna(how='any')

We can check the data using the head() function.

stock.head()

Data Table

We can plot the adjusted price against time using the matplotlib library which we have already imported.

stock['Adj Close'].plot(grid = True)

Plot adjusted price against time

Calculating and plotting daily returns

Using time series, we can compute daily returns and plot returns against time. We will compute the daily returns from the adjusted closing price of the stock and store in the same dataframe 'stock' under the column name 'ret'. We will also plot the daily returns against time.

stock['ret'] = stock['Adj Close'].pct_change()
stock['ret'].plot(grid=True)

Plot daily returns against time

Moving Average

Similar to returns, we can calculate and plot the moving average of the adjusted close price. Moving average is a very important metric used widely in technical analysis. For illustration purpose, we will compute 20 days moving average.

stock['20d'] = stock['Adj Close'].rolling(window=20, center=False).mean()
stock['20d'].plot(grid=True)

Before moving on to forecasting, let us quickly have a look on trend and seasonality in time series.
Trend and seasonality in time series

Trend and Seasonality

In simple words, trend signifies the general direction in which the time series is developing. Trends and trend analysis are extensively used in technical analysis. If some patterns are visible in the time series at regular intervals, the data is said to have seasonality. Seasonality in a time series can impact results of the forecasting model and hence should be dealt with care.

You can refer to our blog "Starting Out with Time Series" for more details on trend and seasonality and how a time series can be decomposed into its components.

We will also discuss simple linear forecasting model assuming the time series is stationary and doesn't have seasonality. The basic assumption here is that the time series follows a linear trend. The model can be represented as:

Forecast (t) = a + b X t

Here 'a' is the intercept that time series makes on Y-axis and 'b' is the slope. Let us now look at the computations of a and b. Consider a time series with values D(t) for time period 't'.

In this equation, 'n' is the sample size. We can validate our model by calculating the forecasted values of D(t) using the above model and comparing the values against actual observed values. We can compute mean error which is the mean value of the difference between the forecasted D(t) and the actual D(t).

In our stock data, D(t) is the adjusted closing price of MRF. We will now compute the values of a, b, forecasted values and their errors using python.

#Populates the time period number in stock under head t
stock['t'] = range (1,len(stock)+1)

#Computes t squared, tXD(t) and n
stock['sqr t']=stock['t']**2
stock['tXD']=stock['t']*stock['Adj Close']
n=len(stock)

#Computes slope and intercept
slope = (n*stock['tXD'].sum() - stock['t'].sum()*stock['Adj Close'].sum())/(n*stock['sqr t'].sum() - (stock['t'].sum())**2)
intercept = (stock['Adj Close'].sum()*stock['sqr t'].sum() - stock['t'].sum()*stock['tXD'].sum())/(n*stock['sqr t'].sum() - (stock['t'].sum())**2)
print ('The slope of the linear trend (b) is: ', slope)
print ('The intercept (a) is: ', intercept)

The above code gives the output as shown.

The slope of the linear trend (b) is: 41.2816591061
The intercept (a) is: 1272.6557803

We can now check the validity of our model by computing the forecasted values and computing the mean error.

#Computes the forecasted values
stock['forecast'] = intercept + slope*stock['t']

#Computes the error
stock['error'] = stock['Adj Close'] - stock['forecast']
mean_error=stock['error'].mean()
print ('The mean error is: ', mean_error)

The mean error is given by the output as:

The mean error is: 1.0813935108094419e-10

As can be seen from the above value of the mean error, our model gave results very close to the actual values. Hence, the data is free from any seasonality.

Summary

In this blog, we have seen various properties of time series and how to compute these properties in python. We have also seen a simple model to forecast our time series based on trend assuming that the time series is free from seasonality.

If you want to learn more about quantitative trading strategies using Python, visit QuantInsti website and the educational offerings at their Executive Programme in Algorithmic Trading (EPAT™).

This article is from QuantInsti and is being posted with QuantInsti's permission. The views expressed in this article are solely those of the author and/or QuantInsti and IB is not endorsing or recommending any investment or trading discussed in the article. This material is 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 IB 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.


17826




1 2 3 4 5 2 15

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.