Skip to main content

FINTER API

Project description

Overview

Python client SDK for finter platform

  • You can get Authorization of finter API with authToken.

    • Type: API key

    • API key parameter name: Authorization

    • Location: HTTP header

  • This Python package is automatically generated by the Swagger Codegen project.

  • Please contact with finter_support@quantit.io if you have any problems, troubles, … etc.

Requirements.

Python 2.7 and 3.4+

Installation & Usage

pip install finter

Then import the package:

import finter

Set environment variable FINTER_API_KEY to use API key: later, you can change settgins.configuration.api_key[‘Authorization’]

# sh
export FINTER_API_KEY=YOUR_API_KEY
# python
import os
os.environ['FINTER_API_KEY'] = 'YOUR_API_KEY'

Getting Started

Please follow the installation procedure and then run the following:

Get CM Example

from __future__ import print_function
import time
import finter
from finter.rest import ApiException
from pprint import pprint
# Configure API key authorization: tokenAuth
configuration = finter.Configuration()
# Token-based authentication with required prefix "Token"
configuration.api_key['Authorization'] = 'Token YOUR_API_KEY' # prefix "Token" is required

# create an instance of the API class
api_instance = finter.ContentApi(finter.ApiClient(configuration))
code_format = 'code_format_example' # str | data column code format (optional)
end = 'end_example' # str | data end date (optional)
identity_name = 'identity_name_example' # str | content model identity name (required)
tail = 56 # int | data tail row number (optional)

try:
    api_response = api_instance.content_model_retrieve(code_format=code_format, end=end, identity_name=identity_name, tail=tail)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling ContentApi->content_model_retrieve: %s\n" % e)

Convert to Pandas DataFrame

import finter

json_response = api_response.to_dict()['cm']
column_types = api_response.to_dict()['column_types']
df = finter.to_dataframe(json_response, column_types)

BaseAlpha Example

from __future__ import print_function
import time
import finter
from finter.rest import ApiException
from pprint import pprint
# Configure HTTP basic authorization: basicAuth
configuration = finter.Configuration()
configuration.username = 'YOUR_USERNAME'
configuration.password = 'YOUR_PASSWORD'
# Configure API key authorization: tokenAuth
configuration = finter.Configuration()
configuration.api_key['Authorization'] = 'YOUR_API_KEY'
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['Authorization'] = 'Bearer'

# create an instance of the API class
api_instance = finter.AlphaApi(finter.ApiClient(configuration))
end = 'end_example' # str | data end date
identity_name = 'identity_name_example' # str | content model identity name
start = 'start_example' # str | data start date
code_format = 'code_format_example' # str | data column code format (optional)
tail = 56 # int | data tail row number (optional)

try:
    api_response = api_instance.alpha_base_alpha_cm_retrieve(end, identity_name, start, code_format=code_format, tail=tail)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling AlphaApi->alpha_base_alpha_cm_retrieve: %s\n" % e)
json_response = api_response.to_dict()['cm']
column_types = api_response.to_dict()['column_types']
df = finter.to_dataframe(json_response, column_types)

Get Calendar Example

from __future__ import print_function
import time
import finter
from finter.rest import ApiException
from pprint import pprint
# Configure API key authorization: tokenAuth
configuration = finter.Configuration()
configuration.api_key['Authorization'] = 'Token YOUR_API_KEY' # prefix "Token" is required

# create an instance of the API class
api_instance = finter.CalendarApi(finter.ApiClient(configuration))
date_type = 1 # int | 0:all day 1: trading day, 2: closed day, 3: weekends (optional, default: 0)
start_date = 'start_date_example' # str |  (required)
end_date = 'end_date_example' # str |  (required)
exchange = 'exchange_example' # str |  (optional)

try:
    api_response = api_instance.calendar_retrieve(date_type=date_type, end_date=end_date, exchange=exchange, start_date=start_date)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling CalendarApi->calendar_retrieve: %s\n" % e)

Get Metafund Model Example

from __future__ import print_function
import time
import finter
from finter.rest import ApiException
from pprint import pprint
# Configure API key authorization: tokenAuth
configuration = finter.Configuration()
configuration.api_key['Authorization'] = 'Token YOUR_API_KEY' # prefix "Token" is required

# create an instance of the API class
api_instance = finter.MetafundApi(finter.ApiClient(configuration))
code_format = 'code_format_example' # str | data column code format (optional)
forward_fill = True # bool |  (optional)
metafund_name = 'metafund_name_example' # str |  (required)

try:
    api_response = api_instance.metafund_model_retrieve(code_format=code_format, forward_fill=forward_fill, metafund_name=metafund_name)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling MetafundApi->metafund_model_retrieve: %s\n" % e)

Get simulation Example

from __future__ import print_function
import time
import finter
from finter.rest import ApiException
from pprint import pprint
from finter.utils.convert import get_json_with_columns_from_dataframe

# Configure API key authorization: tokenAuth
configuration = finter.Configuration()
configuration.api_key['Authorization'] = 'Token YOUR_API_KEY' # prefix "Token" is required

position, position_column_types = get_json_with_columns_from_dataframe(df)
sim_data = {
    'position': position,
    'position_column_types': position_column_types,
    'model_info': {'exchange': 'krx', 'universe': 'krx', 'instrument_type': 'stock', 'freq': '1d',
                   'position_type': 'target', 'type': 'alpha'},
    'start': 20100111,
    'end': 20230620,
    'fill_nan': True,
    'close': True,
    'adj_dividend': True,
    'adj_funding_fee': False,
    'currency': None,
    'return_calc_method': 'arithmetic',
    'turnover_calc_method': 'diff',
    'cost_list': ['fee_tax', 'high_low'],
    'volcap_pct': 0,
    'decay': 1,
    'slippage': 10,
}
# create an instance of the API class
api_instance = finter.SimulationApi(finter.ApiClient(configuration))
body = finter.SimulationRequest(**sim_data) # SimulationRequest |

try:
    api_response = api_instance.simulation_create(body)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling SimulationApi->simulation_create: %s\n" % e)

Get Submission alpha Example

from __future__ import print_function
import time
import finter
from finter.rest import ApiException
from pprint import pprint
# Configure API key authorization: tokenAuth
configuration = finter.Configuration()
configuration.api_key['Authorization'] = 'Token YOUR_API_KEY' # prefix "Token" is required

api_instance = finter.SubmissionApi(finter.ApiClient(configuration))
model_info = {
    "exchange": "krx",
    "universe": "krx",
    "instrument_type": "stock",
    "exposure": "long_only",
    "insample": "1day",
    "position_type": "target",
    "freq": "1d",
    "type": "alpha",
}
model_dir = 'sample_alpha'
try:
    api_response = api_instance.submission_create(model_info, model_dir)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling SubmissionApi->submission_create: %s\n" % e)

Get Submission portfolio Example

from __future__ import print_function
import time
import finter
from finter.rest import ApiException
from pprint import pprint
# Configure API key authorization: tokenAuth
configuration = finter.Configuration()
configuration.api_key['Authorization'] = 'Token YOUR_API_KEY' # prefix "Token" is required

api_instance = finter.SubmissionApi(finter.ApiClient(configuration))
model_info = {
    "exchange": "krx",
    "universe": "krx",
    "instrument_type": "stock",
    "insample": "1day",
    "position_type": "target",
    "freq": "1d",
    "type": "portfolio",
}
model_dir = 'sample_portfolio'
try:
    api_response = api_instance.submission_create(model_info, model_dir)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling SubmissionApi->submission_create: %s\n" % e)

Sample Alpha

from datetime import datetime

import numpy as np
from finter.framework_model import BaseAlpha
from finter.framework_model import iter_trading_days


def get_long_position(df, aum=1e+8):
    pos_df = (df > 0) * df
    pos_df = np.divide(
        aum*pos_df, abs(pos_df).sum(axis=1).replace(0, np.nan).values.reshape(-1, 1))
    df2 = pos_df.fillna(0.)
    return df2


def get_long_short_position(df, aum=1e+8):
    pos_df = (df > 0) * df
    neg_df = (df < 0) * df
    pos_df = np.divide(0.5*aum*pos_df, abs(pos_df).sum(axis=1).values.reshape(-1, 1))
    neg_df = np.divide(0.5*aum*neg_df, abs(neg_df).sum(axis=1).values.reshape(-1, 1))
    df2 = pos_df.fillna(0.) + neg_df.fillna(0.)
    return df2


def zscore(df):
    df2 = np.subtract(df, df.mean(axis=1).values.reshape(-1, 1))
    df2 = np.divide(df2, df.std(axis=1).values.reshape(-1, 1))
    return df2


class Alpha(BaseAlpha): # BaseAlpha Class를 상속받아옴 (필수)
    def initialize(self, start, end, preload): # 인자로 받은 start, end에서 start에서 preload-year을 빼고 로드함.
        self.alpha_start, self.alpha_end = start - preload*int(1e4), end
        self.position_size = 1e8  # 포지션 사이즈는 기본 1억(1e8)

        # 거래소, 유니버스, 종목타입, 포지션타입, 포지션 생성 주기, 전략 타입
        self.exchange, self.universe, self.instrument_type, self.position_type, self.freq, self.type = \
            'krx', 'krx', 'stock', 'target', '1d', 'alpha'
        self.model_info = {'exchange': self.exchange, 'universe': self.universe, 'instrument_type': self.instrument_type,
                           'freq': self.freq, 'position_type': self.position_type,  'type': self.type}
        self.close = BaseAlpha.get_cm("# 가격 CM").get_df(
            self.alpha_start, self.alpha_end)  # 가격
        self.market_equity = BaseAlpha.get_cm("# 시가총액 CM").get_df(
            self.alpha_start, self.alpha_end)  # 시가총액
        self.kospi_200 = BaseAlpha.get_cm("# 코스피200 필터링 CM").get_df(
            self.alpha_start, self.alpha_end).replace('Y', 1.0).replace('N', np.nan)  # 코스피200 필터링
        self.kospi_200_me = self.market_equity * self.kospi_200


    def get(self, start, end):  # start와 end를 입력받아서 start ~ end에 해당하는 포지션을 반환
        self.initialize(start, end, preload=2)  # 포지션 시작일보다 데이터는 2년을 앞서 로드함
        self.trading_start_dt, self.trading_end_dt = datetime.strptime(
            str(start), '%Y%m%d'), datetime.strptime(str(end), '%Y%m%d')  # 트레이딩 시작일, 종료일
        self.trading_dates = [datetime(day.year, day.month, day.day) for day in iter_trading_days(
            self.trading_start_dt, self.trading_end_dt)]  # 트레이딩 일자. 미국인 경우 us_iter_trading_days 사용

        self.signal1 = self.kospi_200_me  # 코스피200 시가총액 비율 (대형주 투자)
        self.signal2 = (1 / self.kospi_200_me)  # 코스피200 시가총액 역순 비율 (소형주 투자)
        self.signal3 = (self.kospi_200_me.rank(axis=1, pct=True) >= 0.75).astype(float)  # 코스피 200 중 시가총액 상위 25%에 동일 가중 투자
        self.signal4 = (self.kospi_200_me.rank(axis=1, pct=True) <= 0.25).astype(float)  # 코스피 200 중 시가총액 하위 25%에 동일 가중 투자

        # shift(1)을 하는 이유는 오늘의 장 마감후 데이터는 장 마감 전에 알 수 없기 때문
        self.position1 = get_long_position(self.signal1).shift(1).reindex(self.trading_dates)  # 코스피200 시가총액 비중 투자
        self.position2 = get_long_position(self.signal2).shift(1).reindex(self.trading_dates)  # 코스피200 시가총액 역수 비중 투자
        self.position3 = get_long_position(self.signal3).shift(1).reindex(self.trading_dates)  # 코스피 200 중 시가총액 상위 25%에 동일 가중 투자
        self.position4 = get_long_position(self.signal4).shift(1).reindex(self.trading_dates)  # 코스피 200 중 시가총액 하위 25%에 동일 가중 투자
        return self.position2

if __name__ == '__main__':
    start, end = (20050101, 20220706)
    self = Alpha()
    position = self.get(start, end)

Sample portfolio

from finter.framework_model.portfolio import BasePortfolio

class Portfolio(BasePortfolio):
    alpha_set = set(
        [
            "krx.krx.stock.ldh0127_qt.sample_univ_1",
        ]
    )  # type: ignore

    def __init__(self):
        return

    def alpha_loader(self, start, end):
        return self.get_alpha_position_loader(
            start, end, "krx", "krx", "stock", "1d", "target"
        )

    def get(self, start, end):
        alpha_loader = self.alpha_loader(start, end)

        alpha_dict = {}
        for i in self.alpha_set:
            alpha_dict[i] = alpha_loader.get_alpha("alpha." + i)

        pf = sum(map(lambda x: x.fillna(0), alpha_dict.values()))

        return pf


if __name__ == "__main__":
    start, end = (20200101, 20231101)
    self = Portfolio()
    pf = self.get(start, end)

Get Universe list

from finter.framework_model import get_universe_list
id_list = get_universe_list('korea', 'stock', 'fnguide')

Get Universe list with API

from __future__ import print_function
import time
import finter
from finter.rest import ApiException
from pprint import pprint
# Configure API key authorization: tokenAuth
configuration = finter.Configuration()
configuration.api_key['Authorization'] = 'Token YOUR_API_KEY' # prefix "Token" is required

api_instance = finter.UniverseApi(finter.ApiClient(configuration))
region = 'korea' # str |
type = 'stock' # str |
vendor = 'fnguide' # str |

try:
    api_response = api_instance.universe_list_retrieve(region, type, vendor)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling UniverseApi->universe_list_retrieve: %s\n" % e)

You can apply same code frame to use other endpoints.

api_instance

module name

Api url

ContentApi

content_identities_retrieve

content/identities

content_model_retrieve

content/model

ews_retrieve

ews/

AlphaApi

alpha_identities_retrieve

alpha/identities

alpha_model_retrieve

alpha/model

PortfolioApi

portfolio_identities_retrieve

portfolio/identities

portfolio_model_retrieve

portfolio/model

FundApi

fund_identities_retrieve

fund/identities

fund_model_retrieve

fund/model

FlexibleFundApi

flexiblefund_identities_retrieve

flexiblefund/identities

flexiblefund_model_retrieve

flexiblefund/model

MetafundApi

metafund_list_retrieve

metafund/list

metafund_model_retrieve

metafund/model

metafund_performance_retrieve

metafund/performance

Calendar

calendar_retrieve

calendar/

Finter Utils name | description —- | —- to_dataframe | convert json-formed data to dataframe

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

finter-0.0.51-py3-none-any.whl (177.4 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page