symbol | name | market_index | 1m change | 3m change | 6m change | 1y change | combo change |
---|---|---|---|---|---|---|---|
hsi | Hong Kong Hang Seng Index | 18860.9 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
nikkei | Japan Nikkei 225 | 31943.9 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
dow | US Dow Jones Industrial Average | 34349.3 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
nasdaq | NASDAQ Composite | 13919.0 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
ftse | UK FTSE 100 | 7416.11 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
dax | Germany DAX 30 | 16023.0 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
cac | France CAC 40 | 7333.01 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
spx | US S&P 500 | 4472.16 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
ibex | Spain IBEX 35 | 9453.7 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
mib | Italy MIB 40 | 28552.2 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
asx | Australia ASX 200 | 7135.7 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
kospi | Korea KOSPI | 2574.72 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
omx | OMX Stockholm 30 | 2264.21 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
stoxx | Europe Stoxx 50 | 4360.46 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
sse | China Shanghai Composite | 3196.13 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
szse | China SZSE Component | 10919.3 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
aex | Netherlands AEX 25 | 768.14 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
omxc | OMX Copenhagen 20 | 1970.02 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
obx | Norway Oslo OBX | 1116.42 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
ibov | Brazil IBOVESPA | 117666.0 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
sensex | India Sensex | 65393.9 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
rtsi | Russia RTSI | 1004.98 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
smi | Switzerland SMI 20 | 11019.0 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
bux | Hungary BUX | 50549.4 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
athex | Greece ATHEX | 3207.79 | -100.00 | -100.00 | -100.00 | -100.00 | -100.00 |
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.
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
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 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 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 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
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()
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() |