fetch_historical_data – ShinyBroker

# fetch_historical_data

`fetch_historical_data(contract, endDateTime='', durationStr='1 D', barSizeSetting='1 hour', whatToShow='Trades', useRTH=True, host='127.0.0.1', port=7497, client_id=9999, timeout=3)`

Fetch historical data for a tradable asset

Creates a temporary IBKR client socket at the specified `host`, `port`, and `client_id`, then makes a query for the historical data specified by the input parameters, receives the response, closes the socket, formats the response, and returns the result.

If `timeout` number of seconds elapse before receiving historical data, then `fetch_historical_data` returns `None`.

## Parameters

Name | Type | Description | Default
--- | --- | --- | ---
`contract` | Contract | The Contract object for which you want data | required
`endDateTime` |  | Ending datetime string formatted as “YYYYMMDD HH:mm:ss TMZ” specifying the end of the time period for which you want historical data. Leave it as the default “” to get historical data up to the current present moment. | `''`
`durationStr` |  | A Duration String that specifies how far back in time you want to fetch data. | `'1 D'`
`barSizeSetting` |  | A Bar Size that specifies how fine-grained you want your historical data to be (daily, weekly, every 30 seconds, etc). | `'1 hour'`
`whatToShow` |  | You may select from any of the Historical Data Types but for most cases you’ll probably be happy with one of “BID_ASK”, “MIDPOINT”, or “TRADES”. | `'Trades'`
`useRTH` |  | “Use Regular Trading Hours”. Set to `False` if you want the historical data to include after-hours/pre-market trading | `True`
`host` |  | Address of a running IBKR client (such as TWS or IBG) that has been configured to accept API connections | `'127.0.0.1'`
`port` |  | Port of a running IBKR client | `7497`
`client_id` |  | Client ID you want to use for the request. If you are connecting to a system that is used by multiple users, then you may wish to set aside an ID for this purpose; if you’re the only one using the account then you probably don’t have to worry about it – just use the default. | `9999`
`timeout` |  | Time in seconds to wait for a response. | `3`

## Examples

    import shinybroker as sb

    historical_data = sb.fetch_historical_data(
        contract=sb.Contract({
            'symbol': "AAPL",
            'secType': "STK",
            'exchange': "SMART",
            'currency': "USD"
        })
    )
    print(historical_data)

    # historical Bid/Ask for a Google Call
    # the behavior of this one can be spotty if you're running it outside of
    #   normal trading hours
    historical_data_google_bid_ask = sb.fetch_historical_data(
        contract=sb.Contract({
            'symbol': 'GOOG',
            'secType': 'OPT',
            'exchange': 'SMART',
            'currency': 'USD',
            'lastTradeDateOrContractMonth': '20261218',
            'strike': 160,
            'right': 'C',
            'multiplier': '100'
        }),
        durationStr='1 D',
        barSizeSetting='1 hour',
        whatToShow='BID_ASK'
    )
    print(historical_data_google_bid_ask)

    #### Try an example with a bad barSizeSetting
    #### fetch_historical_data prints an informative error message and returns None
    historical_data_bad_barsize = sb.fetch_historical_data(
        contract=sb.Contract({
            'symbol': "AAPL",
            'secType': "STK",
            'exchange': "SMART",
            'currency': "USD"
        }),
        barSizeSetting="1 hrs"
    )
    print(historical_data_bad_barsize)

    #### Try an example with a bad security definition
    #### IBKR doesn't give historical data for SPX on SMART exchange; you must pass
    ####   "ARCA" as the exchange to get it to work. If you try the below code,
    ####   which does not return historical data, you'll get an informative error
    ####   message suggesting that you check the contract definition.
    historical_data_bad_secdef = sb.fetch_historical_data(
        contract=sb.Contract({
            'symbol': "SPX",
            'secType': "STK",
            'exchange': "SMART",
            'currency': "USD"
        }),
        barSizeSetting="1 day",

    )
    print(historical_data_bad_secdef)