跳轉到

finlab.market_info

finlab.market_info.MarketInfo

市場類別 假如希望開發新的交易市場套用到回測系統,可以繼承 finlab.market_info.MarketInfo 來實做新類別。

get_asset_id_to_name staticmethod

get_asset_id_to_name()

設定對標報酬率的時間序列 Returns: (dict): 股號與股名對照表,ex:{'2330':'台積電'}

Source code in finlab/market_info.py
@staticmethod
def get_asset_id_to_name() -> Dict:
    """設定對標報酬率的時間序列
    Returns:
      (dict): 股號與股名對照表,ex:`{'2330':'台積電'}`
    """
    return {}

get_benchmark staticmethod

get_benchmark()

設定對標報酬率的時間序列

這個函數用於設定對標報酬率的時間序列。

RETURNS DESCRIPTION
Series

pd.Series: 時間序列的報酬率。

RAISES DESCRIPTION
ExceptionType

Description of conditions under which the exception is raised.

Examples:

date 0050
2007-04-23 100
2007-04-24 100.1
2007-04-25 99
2007-04-26 98.3
2007-04-27 99.55
Source code in finlab/market_info.py
@staticmethod
def get_benchmark() -> pd.Series:
    """設定對標報酬率的時間序列

    這個函數用於設定對標報酬率的時間序列。

    Returns:
        pd.Series: 時間序列的報酬率。

    Raises:
        ExceptionType: Description of conditions under which the exception is raised.

    Examples:
        | date       |   0050 |
        |:-----------|-------:|
        | 2007-04-23 |   100 |
        | 2007-04-24 |   100.1 |
        | 2007-04-25 |   99 |
        | 2007-04-26 |   98.3 |
        | 2007-04-27 |   99.55 |
    """
    return pd.Series([], index=pd.Index([], dtype='datetime64[ns]'), dtype='float64')

get_freq staticmethod

get_freq()

Returns the frequency of the data. Used to determine how to resample the data when the data is not daily. The freq will be saved in finlab.core.report.

Returns: str: The frequency of the data.

Source code in finlab/market_info.py
@staticmethod
def get_freq() -> str:
    """
    Returns the frequency of the data.
    Used to determine how to resample the data when the data is not daily.
    The freq will be saved in `finlab.core.report`.

    Returns:
    str: The frequency of the data.
    """
    return '1d'

get_market_value staticmethod

get_market_value()

取得回測用市值數據

RETURNS DESCRIPTION
DataFrame

市值數據,其中 index 為日期,而 columns 是股票代號。

Source code in finlab/market_info.py
@staticmethod
def get_market_value():
    """取得回測用市值數據

    Returns:
      (pd.DataFrame): 市值數據,其中 index 為日期,而 columns 是股票代號。

    """
    return pd.DataFrame()

get_name staticmethod

get_name()

Returns the name of the market data source.

This function is used to get the name of the market data source.

Source code in finlab/market_info.py
@staticmethod
def get_name() -> str:
    """
    Returns the name of the market data source.

    This function is used to get the name of the market data source.
    """
    return 'auto'

get_price staticmethod

get_price(trade_at_price, adj=True)

取得回測用價格數據

PARAMETER DESCRIPTION
trade_at_price

選擇回測之還原股價以收盤價或開盤價計算,預設為'close'。可選'close'或'open'。

TYPE: str

adj

是否使用還原股價計算。

TYPE: str DEFAULT: True

RETURNS DESCRIPTION
DataFrame

價格數據

Examples:

格式範例

date 0015 0050 0051 0052
2007-04-23 9.54 57.85 32.83 38.4
2007-04-24 9.54 58.1 32.99 38.65
2007-04-25 9.52 57.6 32.8 38.59
2007-04-26 9.59 57.7 32.8 38.6
2007-04-27 9.55 57.5 32.72 38.4
Source code in finlab/market_info.py
@staticmethod
def get_price(trade_at_price:str, adj:bool=True) -> pd.DataFrame:
    """取得回測用價格數據

    Args:
       trade_at_price (str): 選擇回測之還原股價以收盤價或開盤價計算,預設為'close'。可選'close'或'open'。
       adj (str): 是否使用還原股價計算。

    Returns:
      (pd.DataFrame): 價格數據

    Examples:
        格式範例

        | date       |   0015 |   0050 |   0051 |   0052 |
        |:-----------|-------:|-------:|-------:|-------:|
        | 2007-04-23 |   9.54 |  57.85 |  32.83 |  38.4  |
        | 2007-04-24 |   9.54 |  58.1  |  32.99 |  38.65 |
        | 2007-04-25 |   9.52 |  57.6  |  32.8  |  38.59 |
        | 2007-04-26 |   9.59 |  57.7  |  32.8  |  38.6  |
        | 2007-04-27 |   9.55 |  57.5  |  32.72 |  38.4  |
        """
    return pd.DataFrame()

get_reference_price

get_reference_price()

Returns the most recent reference price of the market.

RETURNS DESCRIPTION

pandas.Series: The most recent reference price of the market.

Source code in finlab/market_info.py
def get_reference_price(self):
    """Returns the most recent reference price of the market.

    Returns:
        pandas.Series: The most recent reference price of the market.
    """
    return self.get_price('close').iloc[-1]

get_trading_price

get_trading_price(name, adj=True)

取得回測用價格數據

PARAMETER DESCRIPTION
name

選擇回測之還原股價以收盤價或開盤價計算,預設為'close'。可選 'open'、'close'、'high'、'low'、'open_close_avg'、'high_low_avg'、或 'price_avg'。

TYPE: str

Returns: (pd.DataFrame): 價格數據

Source code in finlab/market_info.py
def get_trading_price(self, name: str, adj=True) -> pd.DataFrame:

    """取得回測用價格數據

    Args:
        name (str): 選擇回測之還原股價以收盤價或開盤價計算,預設為'close'。可選 'open'、'close'、'high'、'low'、'open_close_avg'、'high_low_avg'、或 'price_avg'。
    Returns:
        (pd.DataFrame): 價格數據

    """


    if name in ['open', 'close', 'high', 'low']:
        return self.get_price(name, adj=adj)
    elif name == 'close_open_avg' or 'open_close_avg':
        return (self.get_price('open', adj=adj) + self.get_price('close', adj=adj)) / 2
    elif name == 'high_low_avg' or 'low_high_avg':
        return (self.get_price('high', adj=adj) + self.get_price('low', adj=adj)) / 2
    elif name == 'price_avg':
        return (self.get_price('open', adj=adj) + self.get_price('close', adj=adj)\
                 + self.get_price('high', adj=adj) + self.get_price('low', adj=adj)) / 4

    raise ValueError(f"Unknown trade price name: {name}")

market_close_at_timestamp

market_close_at_timestamp(timestamp=None)

Returns the timestamp of the market close of the given timestamp.

PARAMETER DESCRIPTION
timestamp

The timestamp to find the market close to.

TYPE: datetime DEFAULT: None

RETURNS DESCRIPTION
datetime

The timestamp of the closest market close.

Source code in finlab/market_info.py
def market_close_at_timestamp(self, timestamp=None):
    """
    Returns the timestamp of the market close of the given timestamp.

    Args:
        timestamp (datetime): The timestamp to find the market close to.

    Returns:
        datetime: The timestamp of the closest market close.
    """

    indexes = self.get_price('close').index

    if timestamp is None:
        timestamp = indexes[-1]

    # find min delta between indexes
    delta = np.abs(indexes[1:] - indexes[:-1]).min()
    return timestamp + delta

tzinfo

tzinfo()

Returns the timezone of the market.

RETURNS DESCRIPTION

datetime.timezone: The timezone of the market.

Source code in finlab/market_info.py
def tzinfo(self):
    """Returns the timezone of the market.

    Returns:
        datetime.timezone: The timezone of the market.
    """
    return None