KeyError in Python Code
I've linked Refinitiv with Python and wanting to calculate a series of risk adjusted metrics (e.g. returns, std, beta, etc) for a bunch of shares. Relevant section of the codes after linking etc reads as follows:
def rapm(stocks, benchmark, start_date, end_date, RF, MAR):
data = pd.DataFrame()
bench = pd.DataFrame()
data = ek.get_timeseries(stocks, fields ='CLOSE',start_date='2017-01-01', end_date='2020-11-30')
bench = ek.get_timeseries('.FTSE', fields ='CLOSE',start_date='2017-01-01', end_date='2020-11-30')
table = BeautifulTable(maxwidth=120)
for i in stocks:
# Calculation of Daily Returns (Stocks and Benchmark)
data['daily_return_' + i] = data[i].pct_change()
bench['daily_return'] = bench.pct_change()
.......................
rapm(['AZN.L','GSK.L','HIK.L','SN.L'],['.FTSE'],'2017-01-01','2020-11-30', 2, 2)
When I run the code, I get the error message:
KeyError: 'daily_return_AZN.L'
Fairly new to using Python and Refinitiv.
Any ideas on how to fix this will be greatly appreciated.
Best Answer
-
@cafriyie, In your code:
# Calculation of Daily Returns (Stocks and Benchmark)
data['daily_return_' + i] = data[i].pct_change()
bench['daily_return'] = bench.pct_change()
# Calculation of Cumulative Return (Stocks and Benchmark)
st_return_i = np.prod(data['daily_return_' + i] + 1 ) - 1
bench_return = np.prod(bench['daily_return_' + i] + 1) - 1You are trying to access column daily_return_*** on dataframe bench, but you haven't defined it. In other words, bench['daily_return'] is a valid entity, whereas bench['daily_return_AZN.L'] is not.
For general help with Pandas, it is best to ask question on the Python/Pandas forums on the stackoverflow.
0
Answers
-
Hi @Gurpreet,
Please find below full details of my codes as per your request above:
"""
import pandas as pd
import numpy as np
import pandas_datareader as web
import eikon as ek
import configparser as cp
from beautifultable import BeautifulTable
from scipy import stats
cfg = cp.ConfigParser()
cfg.read('eikon.cfg.txt')
ek.set_app_key(cfg['eikon']['app_id'])
stocks = ['AZN.L','GSK.L','HIK.L','SN.L']
def rapm(stocks, benchmark, start_date, end_date, RF, MAR):
data = pd.DataFrame()
bench = pd.DataFrame()
data = ek.get_timeseries(stocks, fields ='CLOSE',start_date='2017-01-01', end_date='2020-11-30')
bench = ek.get_timeseries('.FTSE', fields ='CLOSE',start_date='2017-01-01', end_date='2020-11-30')
table = BeautifulTable(maxwidth=120)
table.columns.headers = ['Stock','Return','Benchmark Return','Standard Deviation','Downside Deviation','Beta',
'Tracking Error','Sharpe Ratio','Sortino Ratio','Treynor Ratio','Information Ratio']
table.set_style(BeautifulTable.STYLE_RST)
for i in data:
# Calculation of Daily Returns (Stocks and Benchmark)
data['daily_return_' + i] = data[i].pct_change()
bench['daily_return'] = bench.pct_change()
# Calculation of Cumulative Return (Stocks and Benchmark)
st_return_i = np.prod(data['daily_return_'+i]+ 1 ) - 1
bench_return = np.prod(bench['daily_return_'+i]+ 1) - 1
# Calculation of Standard Deviation and Downside Deviation
std_i = data['daily_return_' + i].std()*np.sqrt(252)
data['DD_' + i] = data[data['daily_return_' + i]<0]['daily_return_' + i]
dd_i = data['DD_' + i].std()*np.sqrt(252)
# Calculation of Beta
beta_i = stats.lineregress(data['daily_return_' + i].dropna(),bench['daily_return'].dropna())[0]
# Calculation of Tracking Error
te_i = (data['daily_return_' + i] - bench['daily_return']).std()*np.sqrt(252)
# Calculation of Sharpe Ratio
sharpe_i = (st_return_i - RF/100) / std_i
# Calculation of Sortino Ratio
sortino_i = (st_return_i - MAR/100) / dd_i
# Calculation of Treynor Ratio
treynor_i = (st_return_i - RF/100) / beta_i
# Calculation of Information Ratio
information_i = (st_return_i - bench_return)/ te_i
column = (i,str(round(st_return_i*100,2))+'%',str(round(bench_return*100,2))+'%',str(round(std_i*100,2))+'%',
str(round(dd_i*100,2))+'%',round(beta_i,2),str(round(te_i*100,2))+'%',round(sharpe_i,2),round(sortino_i,2),
round(treynor_i,2),round(information_i,2))
table.rows.append(column)
print(table)
rapm(['AZN.L','GSK.L','HIK.L','SN.L'],['.FTSE'],'2017-01-01','2020-11-30', 2, 2)
"""
Thank you very much.
0 -
Thank you very much.
0
Categories
- All Categories
- 6 AHS
- 39 Alpha
- 161 App Studio
- 4 Block Chain
- 4 Bot Platform
- 16 Connected Risk APIs
- 47 Data Fusion
- 30 Data Model Discovery
- 608 Datastream
- 1.3K DSS
- 577 Eikon COM
- 4.9K Eikon Data APIs
- 7 Electronic Trading
- Generic FIX
- 7 Local Bank Node API
- Trading API
- 2.7K Elektron
- 1.3K EMA
- 236 ETA
- 519 WebSocket API
- 33 FX Venues
- 10 FX Market Data
- 1 FX Post Trade
- 1 FX Trading - Matching
- 12 FX Trading – RFQ Maker
- 5 Intelligent Tagging
- 2 Legal One
- 20 Messenger Bot
- 2 Messenger Side by Side
- 9 ONESOURCE
- 7 Indirect Tax
- 59 Open Calais
- 264 Open PermID
- 39 Entity Search
- 2 Org ID
- PAM
- PAM - Logging
- 8.4K Private Comments
- 6 Product Insight
- Project Tracking
- ProView
- ProView Internal
- 20 RDMS
- 1.4K Refinitiv Data Platform
- 367 Refinitiv Data Platform Libraries
- 3 Refinitiv Due Diligence
- LSEG Due Diligence Portal API
- 3 Refinitiv Due Dilligence Centre
- Rose's Space
- 1.1K Screening
- 18 Qual-ID API
- 13 Screening Deployed
- 23 Screening Online
- 10 World-Check Customer Risk Screener
- 990 World-Check One
- 44 World-Check One Zero Footprint
- 45 Side by Side Integration API
- Test Space
- 3 Thomson One Smart
- 1.2K TR Internal
- Global Hackathon 2015
- 2 Specialists Who Code
- 10 TR Knowledge Graph
- 150 Transactions
- 142 REDI API
- 1.7K TREP APIs
- 4 CAT
- 21 DACS Station
- 117 Open DACS
- 1.1K RFA
- 103 UPA
- 172 TREP Infrastructure
- 224 TRKD
- 886 TRTH
- 5 Velocity Analytics
- 5 Wealth Management Web Services
- 60 Workspace SDK
- 9 Element Framework
- 5 Grid
- 13 World-Check Data File
- Yield Book Analytics
- 46 中文论坛