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 26719.6 0.95 -6.56 -11.30 2.17 -3.69
nikkei Japan Nikkei 225 22492.7 2.03 4.03 2.84 -0.54 2.09
dow US Dow Jones Industrial Average 26770.2 -0.67 -1.55 0.65 5.74 1.04
nasdaq NASDAQ Composite 8089.54 -0.28 -2.89 -0.15 8.31 1.25
ftse UK FTSE 100 7150.57 -2.40 -5.28 -4.30 1.53 -2.61
dax Germany DAX 30 12633.6 1.33 1.72 2.60 9.63 3.82
cac France CAC 40 5636.25 0.10 0.63 1.20 11.54 3.37
spx US S&P 500 2986.2 -0.19 -1.31 2.01 8.36 2.22
ibex Spain IBEX 35 9329.8 2.60 1.24 -1.85 5.94 1.98
mib Italy MIB 40 22321.8 1.93 2.22 2.77 17.69 6.15
asx Australia ASX 200 6649.7 -1.48 -2.58 4.14 12.61 3.17
kospi Korea KOSPI 2060.69 -0.94 -1.56 -8.25 -4.67 -3.86
omx OMX Stockholm 30 1697.91 3.68 5.18 1.54 11.26 5.41
stoxx Europe Stoxx 50 3579.41 1.20 1.58 2.21 12.20 4.30
sse China Shanghai Composite 2938.14 -3.06 0.48 -7.54 10.67 0.14
szse China SZSE Component 9533.51 -3.88 3.30 -5.17 23.03 4.32
aex Netherlands AEX 25 572.72 -0.34 -1.18 0.98 10.33 2.45
omxc OMX Copenhagen 20 1020.78 -2.36 0.78 1.47 12.06 2.99
obx Norway Oslo OBX 821.35 -0.67 3.02 -0.15 0.05 0.56
ibov Brazil IBOVESPA 104729.0 0.09 1.20 10.19 22.35 8.46
sensex India Sensex 39298.4 8.88 2.51 1.37 15.13 6.97
rtsi Russia RTSI 1355.27 -1.33 0.12 7.22 21.38 6.85
smi Switzerland SMI 20 9965.49 -0.32 -0.03 3.43 12.41 3.87
bux Hungary BUX 40826.3 0.06 -1.28 -5.59 12.00 1.30
athex Greece ATHEX 2146.38 0.60 -2.67 7.28 28.66 8.47

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