logo

Welcome to Quantapi!


How does the global market performs?

Create Date: 2018-03-06
Update Date: 2018-10-16
Author: Nick Wong

symbol name market_index 1m change 3m change 6m change 1y change combo change
hsi Hong Kong Hang Seng Index 29466.3 3.34 14.15 9.08 -6.60 4.99
nikkei Japan Nikkei 225 21566.8 0.63 0.28 -4.85 0.87 -0.77
dow US Dow Jones Industrial Average 25895.3 -0.24 13.30 -1.34 4.72 4.11
nasdaq NASDAQ Composite 7723.95 3.14 18.31 -2.92 4.88 5.85
ftse UK FTSE 100 7324.0 1.32 8.97 -2.22 3.72 2.95
dax Germany DAX 30 11788.4 3.39 9.49 -3.04 -4.22 1.41
cac France CAC 40 5425.9 4.43 15.58 -1.24 3.30 5.52
spx US S&P 500 2832.57 1.72 14.80 -2.47 4.26 4.58
ibex Spain IBEX 35 9492.3 3.39 10.93 -1.02 -1.96 2.84
mib Italy MIB 40 21430.3 5.55 13.14 0.70 -6.00 3.35
asx Australia ASX 200 6184.8 1.45 12.33 0.25 4.18 4.55
kospi Korea KOSPI 2177.62 -1.27 5.14 -4.85 -12.39 -3.34
omx OMX Stockholm 30 1615.14 1.67 11.38 -0.94 4.07 4.04
stoxx Europe Stoxx 50 3409.0 4.59 13.61 -0.64 -0.09 4.37
sse China Shanghai Composite 3090.97 11.94 18.98 14.38 -6.07 9.81
szse China SZSE Component 9839.74 16.12 29.60 18.23 -11.18 13.19
aex Netherlands AEX 25 552.65 2.34 13.99 0.52 3.19 5.01
omxc OMX Copenhagen 20 1024.01 4.65 12.44 5.21 3.71 6.50
obx Norway Oslo OBX 821.67 3.06 7.33 -2.78 12.06 4.92
ibov Brazil IBOVESPA 99588.4 3.19 15.26 33.40 18.33 17.54
sensex India Sensex 38363.5 8.52 8.16 2.07 16.26 8.75
rtsi Russia RTSI 1219.78 3.93 12.58 7.55 -2.88 5.30
smi Switzerland SMI 20 9525.92 2.26 11.70 6.84 7.67 7.12
bux Hungary BUX 42014.2 3.58 6.43 16.37 10.70 9.27
athex Greece ATHEX 1865.25 6.02 14.73 2.95 -9.51 3.55

Let's try to make some research with Quantapi. We will try to look into 25 different Global market index and see which market perform the best and the worst and plot a simple chart with it.
- file containing 25 market index symbol can be downloaded here market_index.csv.
- the whole python script can be copied here.
- to get a trial token Sign Up here.

Get Quantapi data

Below we would import some required packages for the script. Remember to run pip install if you haven't installed the packages yet. Then we define a function get_quantapi(symbol, token, duration, format) which takes in 4 parameters symbol, token, duration, format.

#import required packages
import time
import datetime as dt
import pandas as pd
from pandas import read_csv
import numpy as np
import matplotlib.pyplot as plt


#get data from quantapi json format
def get_quantapi(symbol, token, duration, format):
	query = 'https://quantapi.co/api/' + symbol + '/' + token + '/?d=' + duration + '&f=' + format
	df = pd.read_json(query)
	df = df[['date', 'open', 'high', 'low', 'close']]
	df = df.sort_values('date', ascending = True)
	print(df)
	return df

Market index file

Read in a file named market_index.csv which includes the market index symbols in Quantapi.

#get index list from file
def get_index():
    df = read_csv('market_index.csv', header=0, index_col=0)       
    return df

Calculate market index performance

Calculate market index performance by [current close / past close]. Here we used approximations where 20, 60, 125 transcation days before would be approximate to 1, 3, 6 months. The combo returns will be the mean of 1, 3, 6 and 12 months returns.

#calculate one, three, six month, one year and combo returns
def get_returns(df):
    n = len(df)
    combo = True
    combo_return = 0
    close_price = df['close'].iloc[-1]
    if(n>20):
        one_m_price = df['close'].iloc[-20]
        one_m_return = close_price / one_m_price
    else:
        combo = False
        one_m_return = 0
    if(n>60):
        three_m_price = df['close'].iloc[-60]
        three_m_return = close_price / three_m_price
    else:
        combo = False       
        three_m_return = 0
    if(n>125):
        six_m_price = df['close'].iloc[-125]
        six_m_return = close_price / six_m_price
    else:
        combo = False
        six_m_return = 0
    if(n>230):
        one_y_price = df['close'].iloc[0]
        one_y_return = close_price / one_y_price
    else:
        combo = False
        one_y_return = 0
    
    if(combo):    
        combo_return = (one_m_return + three_m_return + six_m_return + one_y_return)/4
    return one_m_return, three_m_return, six_m_return, one_y_return, combo_return

Calculate momentums of the market index

Calculate the momentums of the market index by putting before functions together and returns a dataframe which includes the following columns "symbol", "name", "category", "1_month", "3_month", "6_month", "12_month", "combo", "index", "1m_change", "3m_change", "6m_change", "1y_change", "combo_change".

#calculate momentums and put them into the index list
def calculate_momentum(df):
    token = 'your token here'
    duration = '1y'
    format = 'json'
    columns = ["symbol", "name", "category", "1_month", "3_month", "6_month", "12_month", "combo", "index", "1m_change", "3m_change", "6m_change", "1y_change", "combo_change"]
    i_list = []
    for i in range(len(df)):
        symbol = df['symbol'].iloc[i]
        name = df['name'].iloc[i]
        category = df['category'].iloc[i]
        prices = get_quantapi(symbol, token, duration, format)
        #delay 1-1.5s to prevent block of IP
        time.sleep(2)
        one_m_return, three_m_return, six_m_return, one_y_return, combo = get_returns(prices)
        price = prices['close'].iloc[-1]
        one_m_change = one_m_return - 1
        three_m_change = three_m_return - 1
        six_m_change = six_m_return - 1
        one_y_change = one_y_return - 1
        combo_change = combo - 1
        i_list.append(symbol)
        i_list.append(name)
        i_list.append(category)
        i_list.append(one_m_return)
        i_list.append(three_m_return)
        i_list.append(six_m_return)
        i_list.append(one_y_return)
        i_list.append(combo)
        i_list.append(price)
        i_list.append(one_m_change)
        i_list.append(three_m_change)
        i_list.append(six_m_change)
        i_list.append(one_y_change)
        i_list.append(combo_change)
        print(int(len(i_list)/len(columns)))
    index_list = pd.DataFrame.from_records(np.array(i_list).reshape(int(len(i_list)/len(columns)), len(columns)), columns = columns)
    return index_list 

Filter +ve returns and sort

Filter those market index with +ve returns and sort by descending order. 5 dataframes which ranked by different periods (1, 3, 6, 12 and combo) will be returned.

#filter and rank the momentum
def filter_rank(df):
    #need to convert np.string to np.float for comparision
    df1 = df.loc[df['1_month'].astype(np.float) > 1]
    ranked_1_m = df1.sort_values('1_month', ascending = False).head(10) 
    ranked_3_m = df1.sort_values('3_month', ascending = False).head(10)
    ranked_6_m = df1.sort_values('6_month', ascending = False).head(10)
    ranked_1_y = df1.sort_values('12_month', ascending = False).head(10)
    ranked_combo = df1.sort_values('combo', ascending = False).head(10)
    return ranked_1_m, ranked_3_m, ranked_6_m, ranked_1_y, ranked_combo

Run, output and plot

This part can be viewed as the main program which run the defined functions, output results and plot.

#get index list
index_list = get_index()
print(index_list)

#calculate index momentums
index_momentum = calculate_momentum(index_list)
#filter and rank index
ranked_1_m, ranked_3_m, ranked_6_m, ranked_1_y, ranked_combo = filter_rank(index_momentum)
print("Rank by 1 Month Return:")
print(ranked_1_m)
print("Rank by 3 Month Return:")
print(ranked_3_m)
print("Rank by 6 Month Return:")
print(ranked_6_m)
print("Rank by 1 Year Return:")
print(ranked_1_y)
print("Rank by Combo Return:")
print(ranked_combo)
#export to csv
today = dt.datetime.now().strftime("%Y%m%d")
index_momentum.to_csv("index_momentum" + today + ".txt", sep = ",", encoding="utf-8")
ranked_1_m.to_csv("index_1_month" + today + ".txt", sep = ",", encoding="utf-8")
ranked_3_m.to_csv("index_3_month" + today + ".txt", sep = ",", encoding="utf-8")
ranked_6_m.to_csv("index_6_month" + today + ".txt", sep = ",", encoding="utf-8")
ranked_1_y.to_csv("index_1_year" + today + ".txt", sep = ",", encoding="utf-8")
ranked_combo.to_csv("index_combo" + today + ".txt", sep = ",", encoding="utf-8")

#plot some graphs
symbol = index_momentum["symbol"]
up_performance = index_momentum.loc[index_momentum['1m_change'].astype(np.float) > 0]
up = up_performance["1m_change"]
down_performance = index_momentum.loc[index_momentum['1m_change'].astype(np.float) <= 0]
down = down_performance["1m_change"]
y_pos = np.arange(len(symbol))

plt.rcParams["figure.figsize"] = [20, 4]
plt.bar(up.index.values, up, align='center', alpha=0.5, color='green')
plt.bar(down.index.values, down, align='center', alpha=0.5, color='red')
plt.xticks(y_pos, symbol)
plt.ylabel('Performance')
plt.title('Global Market Index Performance (1 month)')
plt.savefig('global_index' + str(today) + '.png', bbox_inches='tight') 
plt.show()

Putting all pieces together

Full code can be copied below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
'''
This python script demostrate how to use the quantapi to calculate the global market
index and plot some graphs. 
'''

#import required packages
import time
import datetime as dt
import pandas as pd
from pandas import read_csv
import numpy as np
import matplotlib.pyplot as plt


#get data from quantapi json format
def get_quantapi(symbol, token, duration, format):
	query = 'https://quantapi.co/api/' + symbol + '/' + token + '/?d=' + duration + '&f=' + format
	df = pd.read_json(query)
	df = df[['date', 'open', 'high', 'low', 'close']]
	df = df.sort_values('date', ascending = True)
	print(df)
	return df


#calculate one, three, six month, one year and combo returns
def get_returns(df):
    n = len(df)
    combo = True
    combo_return = 0
    close_price = df['close'].iloc[-1]
    if(n>20):
        one_m_price = df['close'].iloc[-20]
        one_m_return = close_price / one_m_price
    else:
        combo = False
        one_m_return = 0
    if(n>60):
        three_m_price = df['close'].iloc[-60]
        three_m_return = close_price / three_m_price
    else:
        combo = False       
        three_m_return = 0
    if(n>125):
        six_m_price = df['close'].iloc[-125]
        six_m_return = close_price / six_m_price
    else:
        combo = False
        six_m_return = 0
    if(n>230):
        one_y_price = df['close'].iloc[0]
        one_y_return = close_price / one_y_price
    else:
        combo = False
        one_y_return = 0
    
    if(combo):    
        combo_return = (one_m_return + three_m_return + six_m_return + one_y_return)/4
    return one_m_return, three_m_return, six_m_return, one_y_return, combo_return


#get index list from file
def get_index():
    df = read_csv('market_index.csv', header=0, index_col=0)       
    return df


#calculate momentums and put them into the index list
def calculate_momentum(df):
    token = 'your token here'
    duration = '1y'
    format = 'json'
    columns = ["symbol", "name", "category", "1_month", "3_month", "6_month", "12_month", "combo", "index", "1m_change", "3m_change", "6m_change", "1y_change", "combo_change"]
    i_list = []
    for i in range(len(df)):
        symbol = df['symbol'].iloc[i]
        name = df['name'].iloc[i]
        category = df['category'].iloc[i]
        prices = get_quantapi(symbol, token, duration, format)
        #delay 1-1.5s to prevent block of IP
        time.sleep(2)
        one_m_return, three_m_return, six_m_return, one_y_return, combo = get_returns(prices)
        price = prices['close'].iloc[-1]
        one_m_change = one_m_return - 1
        three_m_change = three_m_return - 1
        six_m_change = six_m_return - 1
        one_y_change = one_y_return - 1
        combo_change = combo - 1
        i_list.append(symbol)
        i_list.append(name)
        i_list.append(category)
        i_list.append(one_m_return)
        i_list.append(three_m_return)
        i_list.append(six_m_return)
        i_list.append(one_y_return)
        i_list.append(combo)
        i_list.append(price)
        i_list.append(one_m_change)
        i_list.append(three_m_change)
        i_list.append(six_m_change)
        i_list.append(one_y_change)
        i_list.append(combo_change)
        print(int(len(i_list)/len(columns)))
    index_list = pd.DataFrame.from_records(np.array(i_list).reshape(int(len(i_list)/len(columns)), len(columns)), columns = columns)
    return index_list 


#filter and rank the momentum
def filter_rank(df):
    #need to convert np.string to np.float for comparision
    df1 = df.loc[df['1_month'].astype(np.float) > 1]
    ranked_1_m = df1.sort_values('1_month', ascending = False).head(10) 
    ranked_3_m = df1.sort_values('3_month', ascending = False).head(10)
    ranked_6_m = df1.sort_values('6_month', ascending = False).head(10)
    ranked_1_y = df1.sort_values('12_month', ascending = False).head(10)
    ranked_combo = df1.sort_values('combo', ascending = False).head(10)
    return ranked_1_m, ranked_3_m, ranked_6_m, ranked_1_y, ranked_combo


#get index list
index_list = get_index()
#index_list = index_list[0:6]
print(index_list)

#calculate index momentums
index_momentum = calculate_momentum(index_list)
#filter and rank index
ranked_1_m, ranked_3_m, ranked_6_m, ranked_1_y, ranked_combo = filter_rank(index_momentum)
print("Rank by 1 Month Return:")
print(ranked_1_m)
print("Rank by 3 Month Return:")
print(ranked_3_m)
print("Rank by 6 Month Return:")
print(ranked_6_m)
print("Rank by 1 Year Return:")
print(ranked_1_y)
print("Rank by Combo Return:")
print(ranked_combo)
#export to csv
today = dt.datetime.now().strftime("%Y%m%d")
index_momentum.to_csv("index_momentum" + today + ".txt", sep = ",", encoding="utf-8")
ranked_1_m.to_csv("index_1_month" + today + ".txt", sep = ",", encoding="utf-8")
ranked_3_m.to_csv("index_3_month" + today + ".txt", sep = ",", encoding="utf-8")
ranked_6_m.to_csv("index_6_month" + today + ".txt", sep = ",", encoding="utf-8")
ranked_1_y.to_csv("index_1_year" + today + ".txt", sep = ",", encoding="utf-8")
ranked_combo.to_csv("index_combo" + today + ".txt", sep = ",", encoding="utf-8")

#plot some graphs
symbol = index_momentum["symbol"]
up_performance = index_momentum.loc[index_momentum['1m_change'].astype(np.float) > 0]
up = up_performance["1m_change"]
down_performance = index_momentum.loc[index_momentum['1m_change'].astype(np.float) <= 0]
down = down_performance["1m_change"]
y_pos = np.arange(len(symbol))

plt.rcParams["figure.figsize"] = [20, 4]
plt.bar(up.index.values, up, align='center', alpha=0.5, color='green')
plt.bar(down.index.values, down, align='center', alpha=0.5, color='red')
plt.xticks(y_pos, symbol)
plt.ylabel('Performance')
plt.title('Global Market Index Performance (1 month)')
plt.savefig('global_index' + str(today) + '.png', bbox_inches='tight') 
plt.show()

Ref: https://www.investorschronicle.co.uk/2015/11/12/tips-and-ideas/trading-on-auto-pilot-3EyihEk7UiBOKwMIVnoXTL/article.html