def establishConnectionWithReuters(app_id): """ Establish the connection wth EIKON Reuters """ ek.set_app_id(app_id) return ek
def wrapper_func(*args, **kwargs): log = logging.getLogger(__name__) # Check if Eikon is running (if not start it) ps = os.popen('tasklist').read() if 'EikonBox' not in ps: log.info('Start Eikon and wait 60 seconds for initialization') sub.Popen( r'C:\Program Files (x86)\Thomson Reuters\Eikon\Eikon.exe') time.sleep(120) # API Key for Eikon ek.set_app_id('a3613aeaa2a14b6ea8aaff7950114a2d19bdc03a') # Execute Function ret_val = func(*args, **kwargs) return ret_val
def index(request): app_id = str('CE9D75E3B5ECDE27DC3BDA') eikon.set_app_id(app_id) # import pdb; pdb.set_trace() codes = [ str(c) for c in str(urllib.unquote(request.GET.get("codes"))).split(',') ] start_date = str(request.GET.get("start_date")) end_date = str(request.GET.get("end_date")) interval = str(request.GET.get("interval")) prices = eikon.get_timeseries(codes, fields=[str('Close')], start_date=start_date, end_date=end_date, interval=interval) price_list = {p: prices[p].values.tolist() for p in prices} dates = [str(row[0]) for row in [t for t in prices.to_records()]] price_list['dates'] = dates return JsonResponse(price_list)
def wrapper_func(*args, **kwargs): log = logging.getLogger(__name__) p = None # Check if Proxy is running (if not start it) ps = os.popen('tasklist').read() if 'EikonAPIProxy' not in ps: log.info( 'Start Eikon Proxy and wait 60 seconds for initialization') p = sub.Popen( r'C:\Users\Laurent\AppData\Local\Eikon API Proxy\EikonAPIProxy.exe' ) time.sleep(60) # API Key for Eikon ek.set_app_id('a3613aeaa2a14b6ea8aaff7950114a2d19bdc03a') # Execute Function ret_val = func(*args, **kwargs) # Terminate process if p is not None: p.terminate() return ret_val
import sys import eikon as ek ek.set_app_id("your_eikon_id") ric = input("Enter RIC (e.g. IBM, TD.TO): ") def drawRange(num): tNum = (5 - num) * 6.25 print("\t\t ", end="") for i in range(int(tNum) - 1): print(" ", end="") print(u"▼", end="") print("") print("\t\t ", end="") print(u"┌────┬────┬────┬────┬────┐") print("\t\tSell ", end="") print(u"│ │░░░░│▒▒▒▒│▓▓▓▓│████│", end="") print(" Buy") print("\t\t ", end="") print(u"└────┴────┴────┴────┴────┘") try: # check if it is a valid equity stock print("Getting primary RIC") # get the primary RIC associated with this equity stock pRICDF, err = ek.get_data(ric, "TR.PrimaryQuote") pRIC = pRICDF.loc[0]["Primary Quote RIC"]
import xlwings as xw import os import numpy as np import pandas as pd import time import pandas as pd import eikon as ek ek.set_app_id('604ea22425e048d39af0ef760ec9c64ebbe1fe68') from sklearn import preprocessing import functions import pickle import statsmodels.api as sm import zipfile from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import RobustScaler from scipy import stats @xw.func @xw.ret(expand='table') def get_traindata(headers, tickers, FX, start_date='2015-01-01', month_dummies=0): tickers_train = dict(zip(headers, tickers)) dataset = functions.get_train_data(tickers_train, ek, start_date) for i in range(len(FX)): if FX[i] == "USD":
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import eikon as ek import pandas as pd import pickle ek.set_app_id('E9DE83B192F920DC8739C') df = ek.get_timeseries(["SPXo161828000.U"], start_date="2018-02-12", interval='daily') data = {} for i in range(1100, 3525, 25): try: df = ek.get_timeseries( ["SPXo1618{}0.U".format(i)], # start_date="2018-02-12", interval='daily') except: continue data[i] = df dataset = pd.DataFrame() for i in range(1100, 3525, 25): try: dataset = pd.concat([dataset, data[i]['CLOSE']], axis=1)
import eikon as ek # the Eikon Python wrapper package import numpy as np # NumPy import pandas as pd # pandas import cufflinks as cf # Cufflinks import configparser as cp from eikon import Profile as profile profile.get_scripting_proxy_port = 49152 ek.set_app_id('0a845119ab7548339124ed3f965d50480c0f4205')
#!eikonrest/bin/python from flask import Flask, request, jsonify from flask_restful import Resource, Api # from json import dumps import eikon as ek import yaml app = Flask(__name__) api = Api(app) conf = yaml.load(open('config.yml')) ek.set_app_id(conf['eikon']['apikey']) class Query(Resource): def get(self, syms, fs, params=''): # Check UUID in Bearer of API request. This is a simple wrapper. token = request.headers.get('Authorization', None) if token is None: return None method, tokenstr = token.split() if method.lower() == "bearer" and tokenstr == conf['pywrapper']['apikey']: df = ek.get_data(instruments=str(syms).split(','), fields=str(fs).split(','), parameters=params, raw_output=True) return jsonify(df) else: return None class ListHSIOptions(Resource): def get(self, fs, params=''): # Check UUID in Bearer of API request. This is a simple wrapper.
import re import pandas as pd import datetime import chinese_tagging_api import csv companies = chinese_tagging_api.load_company_names( 'Data/2000_Chinese_Companies.xlsx', 'Chinese Lexicon', 'Data/exclude_alias.txt') ric_list = ['财经'] for x in companies: ric_list.append(companies[x]['Name']) ek.set_app_id('F5FA9CCFBBD5247AE06A30D6') today = datetime.datetime.now() from_date = datetime.date.strftime(today - datetime.timedelta(days=1), '%Y-%m-%dT%H:%M:%S') today = datetime.date.strftime(today, '%Y-%m-%dT%H:%M:%S') def get_news(ric): headlines = ek.get_news_headlines(ric + ' IN CHINESE', date_from=from_date, date_to=today, count=100) return [{ 'time': datetime.date.strftime(a, '%Y-%m-%dT%H:%M:%S'), 'source': d, 'headline': b,
def years_ago(end_date, years): if type(end_date) == str: end_date = parse(end_date) if end_date.month == 2 and end_date.day == 29: end_date = end_date.replace(day=28) return end_date.replace(year=end_date.year - years).replace(month = end_date.month - 1) len_hist = 5 end_date = datetime.date.today() dates = pd.bdate_range(years_ago(end_date,len_hist),end_date) df_TS = pd.DataFrame(index=dates).sort_index(axis = 0,ascending = False) cpi = ['AAPL.O'] pwd = os.getcwd() #ek.set_app_id('8B2D38D084ECE14EBF190BC7') ek.set_app_id('B2AA4B3A4A8EE1BCEFA9B') df2,err = ek.get_data(cpi,['TR.PriceClose.date','TR.PriceClose','TR.PriceClose.currency','TR.EV', 'TR.PE','TR.CompanyMarketCap','TR.WACCBeta','TR.WACCCostofEquity', 'TR.TotalReturn1Wk','TR.Volume'], {'SDate': 0, 'EDate': -len_hist*252, 'FRQ': 'D'}) df1,err = ek.get_data(cpi,['TR.NormalizedEbitda.date','TR.NormalizedEbitda','TR.TotalEquity','TR.TotalCurrentAssets','TR.NetIncome'],{'SDate': 0, 'EDate': -len_hist*4, 'FRQ': 'FY'}) df_bm,err = ek.get_data('.SPLRCTHSP',['TR.PriceClose.date','TR.PriceClose'],{'SDate': 0, 'EDate': -len_hist*252, 'FRQ': 'D'}) df_spx,err = ek.get_data('.SPX',['TR.PriceClose.date','TR.PriceClose'],{'SDate': 0, 'EDate': -len_hist*252, 'FRQ': 'D'}) df2.set_index(['Date'],inplace = True) #df1.set_index(['Date'],inplace = True) df_spx.set_index(['Date'],inplace = True) df_bm.set_index(['Date'],inplace = True)
# Do some data prep on missing values df = oj.copy() ## NaN indicator column # for k in df: # s = 'NaN.' + k # df[s] = df[k].isnull() # forward fill NaN's with previous value df = df.fillna(method='pad') # fill with zeroes what doesn't have a past value df = df.fillna(0) return df if __name__ == "__main__": # import sys # parse_data(list(sys.argv[1])) from datetime import datetime import eikon as ek ek.set_app_id('D79B714919385CD9D749D1') import pandas as pd start_date = datetime(2009, 1, 1) end_date = datetime(2016, 5, 31) df2 = parse_data(start_date, end_date, ["Cc1", "Sc1", "Wc1"])
from datetime import date, timedelta import math from dateutil.relativedelta import relativedelta import error_log as log import re import helper import os import time import failed_log as fl import mail_helper as mailservice try: """Eikon App ID """ ek.set_app_id('93D5C93060C3ECEAD451638') except ek.EikonError as e: if (e.code == '401'): StartEikon() else: log.Error(e) """ Function to get ticker data for date. Here we get all tickers from Database and and the data is got for individual tickers from the end for which the last job stopped for the ticker till todays date """ def get_data_for_date(start_date, end_date): tickers = db.call_procedure("get_ticker_details", "")
import eikon as ek ek.set_app_id('your app key') dfFY0, err = ek.get_data("IBM", [ 'TR.RevenueActValue(Period=FY0, Scale=6, Curn=USD)', 'TR.EBITDAActValue(Period=FY0, Scale=6, Curn=USD)', 'TR.EPSActValue(Period=FY0, Curn=USD)' ]) dfFY1, err = ek.get_data("IBM", [ 'TR.RevenueMeanEstimate(Period=FY1, Scale=6, Curn=USD, Precision=0)', 'TR.RevenueHigh(Period=FY1, Scale=6, Curn=USD, Precision=0)', 'TR.RevenueLow(Period=FY1, Scale=6, Curn=USD, Precision=0)', 'TR.EBITDAMean(Period=FY1, Scale=6, Curn=USD, Precision=0)', 'TR.EBITDAHigh(Period=FY1, Scale=6, Curn=USD, Precision=0)', 'TR.EBITDALow(Period=FY1, Scale=6, Curn=USD, Precision=0)', 'TR.EPSMeanEstimate(Period=FY1, Curn=USD)', 'TR.EPSHigh(Period=FY1, Curn=USD)', 'TR.EPSLow(Period=FY1, Curn=USD)' ]) # there can be only one request to get the field in get_data call # for the same field but with different parameters, we use another call dfFY1Roll, err = ek.get_data("IBM", [ 'TR.RevenueMeanEstimate(Period=FY1, Scale=6, Curn=USD, RollPeriods=False, Precision=0)', 'TR.EBITDAMean(Period=FY1, Scale=6, Curn=USD, RollPeriods=False, Precision=0)', 'TR.EPSMeanEstimate(Period=FY1, Curn=USD, RollPeriods=False)' ]) dfFY2, err = ek.get_data("IBM", [ 'TR.RevenueMeanEstimate(Period=FY2, Scale=6, Curn=USD, Precision=0)',
import eikon as ek ek.set_app_id('F1968B7782740096D4E66') dfFY0, err = ek.get_data("IBM", [('TR.RevenueActValue', { 'Period': 'FY0', 'Scale': 6, 'Curn': 'USD' }), ('TR.EBITDAActValue', { 'Period': 'FY0', 'Scale': 6, 'Curn': 'USD' }), ('TR.EPSActValue', { 'Period': 'FY0', 'Curn': 'USD' })], sort_on=None, output='pandas', debug=True) dfFY1, err = ek.get_data("IBM", [('TR.RevenueMeanEstimate', { 'Period': 'FY1', 'Scale': 6, 'Curn': 'USD', 'Precision': 2 }), ('TR.RevenueHigh', { 'Period': 'FY1', 'Scale': 6, 'Curn': 'USD' }), ('TR.RevenueLow', { 'Period': 'FY1', 'Scale': 6,
import eikon as ek from datetime import date import re import lxml.html import pandas as pd import win32com.client outlook = win32com.client.Dispatch("Outlook.Application") mail = outlook.CreateItem(0) ek.set_app_id('<Eikon_token_id>') #start_date, end_date = date(2017, 10, 22), date.today() start_date, end_date = date(2017, 10, 1), date(2017, 12, 14) q = "Product:IFRC AND Topic:ISU AND (\"PRICED\" OR \"DEAL\")" headlines = ek.get_news_headlines(query=q, date_from=start_date, date_to=end_date, count=100) headlines = headlines[headlines['storyId'].str.contains('nIFR')] headlines.to_csv('test.csv') def termsheet_to_dict(storyId): x = ek.get_news_story(storyId) story = lxml.html.document_fromstring(x).text_content() matches = dict(re.findall(pattern=r"\[(.*?)\]:\s?([A-Z,a-z,0-9,\-,\(,\),\+,/,\n,\r,\.,%,\&,>, ]+)", string=story)) clean_matches = {key.strip(): item.strip() for key, item in matches.items()} return clean_matches result = [] index = pd.DataFrame(headlines, columns=['storyId']).values.tolist() for i, storyId in enumerate(index): x = termsheet_to_dict(storyId[0])
import eikon as ek import numpy as np import pandas as pd import cufflinks as cf import configparser as cp cf.set_config_file(offline=True) cfg = cp.ConfigParser() cfg.read('eikon.cfg') ek.set_app_id(cfg['eikon']['app_id']) ric = 'AAPL.O' data = ek.get_timeseries(ric, fields='CLOSE', start_date='2015-01-01', end_date='2018-08-15') data.normalize().iplot(kind='lines') SMA1 = 42 # days SMA2 = 252 # days data['SMA1'] = data['CLOSE'].rolling(SMA1).mean() data['SMA2'] = data['CLOSE'].rolling(SMA2).mean() data.iplot() data.dropna( inplace=True ) #dropping na to account for SMA periods with not enough data to smooth. data['position'] = np.where(data['SMA1'] > data['SMA2'], 1, -1) data.iplot(secondary_y='position')
import asyncio import datetime import random import websockets import eikon import requests import json ric_codes = [] data_url = 'http://52.87.248.54/ric_codes' app_id = 'CE9D75E3B5ECDE27DC3BDA' eikon.set_app_id(app_id) # async def consumer(ric_codes): # data = ric_codes.split(',') # async def producer(): # if not data: # return '' # rst, err = eikon.get_data(instruments=data, fields=['CF_LAST']) # return [str(d) for d in rst['CF_LAST']] # async def consumer_handler(websocket, path): # while True: # ric_codes = await websocket.recv() # await consumer(ric_codes) # async def producer_handler(websocket, path): # while True: