Metadata-Version: 2.0
Name: finter
Version: 0.0.28
Summary: FINTER API
Home-page: UNKNOWN
Author: Quantit <finter_support@quantit.io>
Author-email: 
License: UNKNOWN
Keywords: Swagger,FINTER API
Platform: UNKNOWN
Requires-Dist: urllib3 (>=1.15)
Requires-Dist: six (>=1.10)
Requires-Dist: certifi
Requires-Dist: python-dateutil

Finter API client Package
=========================

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 <https://github.com/swagger-api/swagger-codegen>`__ project.
-  Please contact with
   `finter\_support@quantit.io <finter_support@quantit.io>`__ if you
   have any problems, troubles, ... etc.

Requirements.
-------------

Python 2.7 and 3.4+

Installation & Usage
--------------------

.. code:: sh

    pip install finter

Then import the package:

.. code:: python

    import finter 

Set environment variable ``FINTER_API_KEY`` to use API key: later, you
can change settgins.configuration.api\_key['Authorization']

.. code:: bash

    # sh
    export FINTER_API_KEY=YOUR_API_KEY

.. code:: python

    # 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
~~~~~~~~~~~~~~

.. code:: python

    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
~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    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
~~~~~~~~~~~~~~~~~

.. code:: python

    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
~~~~~~~~~~~~~~~~~~~~

.. code:: python

    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
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    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
~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    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

    sim_data = {
        'position': '',  # postion json using df.to_json(orient="split", date_format="iso", date_unit="s", force_ascii=False)
        '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': 'arithmetic',
        '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 Example
~~~~~~~~~~~~~~~~~~~~~~

.. code:: python

    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)

Sample Alpha
~~~~~~~~~~~~

.. code:: python

    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 = self.get_cm("# 가격 CM").get_df(
                self.alpha_start, self.alpha_end)  # 가격
            self.market_equity = self.get_cm("# 시가총액 CM").get_df(
                self.alpha_start, self.alpha_end)  # 시가총액
            self.kospi_200 = self.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)

**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


