code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def write(self, rootdir):
"""
Write the metadata to a JSON file in the rootdir.
Values contained in the metadata are:
version : int
The value of FORMAT_VERSION of this class.
ohlc_ratio : int
The default ratio by which to multiply the pricing data to
... |
Write the metadata to a JSON file in the rootdir.
Values contained in the metadata are:
version : int
The value of FORMAT_VERSION of this class.
ohlc_ratio : int
The default ratio by which to multiply the pricing data to
convert the floats from floa... | write | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def open(cls, rootdir, end_session=None):
"""
Open an existing ``rootdir`` for writing.
Parameters
----------
end_session : Timestamp (optional)
When appending, the intended new ``end_session``.
"""
metadata = BcolzMinuteBarMetadata.read(rootdir)
... |
Open an existing ``rootdir`` for writing.
Parameters
----------
end_session : Timestamp (optional)
When appending, the intended new ``end_session``.
| open | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def sidpath(self, sid):
"""
Parameters
----------
sid : int
Asset identifier.
Returns
-------
out : string
Full path to the bcolz rootdir for the given sid.
"""
sid_subdir = _sid_subdir_path(sid)
return join(self._r... |
Parameters
----------
sid : int
Asset identifier.
Returns
-------
out : string
Full path to the bcolz rootdir for the given sid.
| sidpath | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def last_date_in_output_for_sid(self, sid):
"""
Parameters
----------
sid : int
Asset identifier.
Returns
-------
out : pd.Timestamp
The midnight of the last date written in to the output for the
given sid.
"""
... |
Parameters
----------
sid : int
Asset identifier.
Returns
-------
out : pd.Timestamp
The midnight of the last date written in to the output for the
given sid.
| last_date_in_output_for_sid | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def _init_ctable(self, path):
"""
Create empty ctable for given path.
Parameters
----------
path : string
The path to rootdir of the new ctable.
"""
# Only create the containing subdir on creation.
# This is not to be confused with the `.bcolz... |
Create empty ctable for given path.
Parameters
----------
path : string
The path to rootdir of the new ctable.
| _init_ctable | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def _ensure_ctable(self, sid):
"""Ensure that a ctable exists for ``sid``, then return it."""
sidpath = self.sidpath(sid)
if not os.path.exists(sidpath):
return self._init_ctable(sidpath)
return bcolz.ctable(rootdir=sidpath, mode='a') | Ensure that a ctable exists for ``sid``, then return it. | _ensure_ctable | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def pad(self, sid, date):
"""
Fill sid container with empty data through the specified date.
If the last recorded trade is not at the close, then that day will be
padded with zeros until its close. Any day after that (up to and
including the specified date) will be padded with `... |
Fill sid container with empty data through the specified date.
If the last recorded trade is not at the close, then that day will be
padded with zeros until its close. Any day after that (up to and
including the specified date) will be padded with `minute_per_day`
worth of zero... | pad | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def set_sid_attrs(self, sid, **kwargs):
"""Write all the supplied kwargs as attributes of the sid's file.
"""
table = self._ensure_ctable(sid)
for k, v in kwargs.items():
table.attrs[k] = v | Write all the supplied kwargs as attributes of the sid's file.
| set_sid_attrs | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def write(self, data, show_progress=False, invalid_data_behavior='warn'):
"""Write a stream of minute data.
Parameters
----------
data : iterable[(int, pd.DataFrame)]
The data to write. Each element should be a tuple of sid, data
where data has the following form... | Write a stream of minute data.
Parameters
----------
data : iterable[(int, pd.DataFrame)]
The data to write. Each element should be a tuple of sid, data
where data has the following format:
columns : ('open', 'high', 'low', 'close', 'volume')
... | write | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def write_sid(self, sid, df, invalid_data_behavior='warn'):
"""
Write the OHLCV data for the given sid.
If there is no bcolz ctable yet created for the sid, create it.
If the length of the bcolz ctable is not exactly to the date before
the first day provided, fill the ctable with... |
Write the OHLCV data for the given sid.
If there is no bcolz ctable yet created for the sid, create it.
If the length of the bcolz ctable is not exactly to the date before
the first day provided, fill the ctable with 0s up to that date.
Parameters
----------
sid... | write_sid | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def write_cols(self, sid, dts, cols, invalid_data_behavior='warn'):
"""
Write the OHLCV data for the given sid.
If there is no bcolz ctable yet created for the sid, create it.
If the length of the bcolz ctable is not exactly to the date before
the first day provided, fill the cta... |
Write the OHLCV data for the given sid.
If there is no bcolz ctable yet created for the sid, create it.
If the length of the bcolz ctable is not exactly to the date before
the first day provided, fill the ctable with 0s up to that date.
Parameters
----------
sid... | write_cols | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def _write_cols(self, sid, dts, cols, invalid_data_behavior):
"""
Internal method for `write_cols` and `write`.
Parameters
----------
sid : int
The asset identifier for the data being written.
dts : datetime64 array
The dts corresponding to values... |
Internal method for `write_cols` and `write`.
Parameters
----------
sid : int
The asset identifier for the data being written.
dts : datetime64 array
The dts corresponding to values in cols.
cols : dict of str -> np.array
dict of mark... | _write_cols | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def data_len_for_day(self, day):
"""
Return the number of data points up to and including the
provided day.
"""
day_ix = self._session_labels.get_loc(day)
# Add one to the 0-indexed day_ix to get the number of days.
num_days = day_ix + 1
return num_days * ... |
Return the number of data points up to and including the
provided day.
| data_len_for_day | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def truncate(self, date):
"""Truncate data beyond this date in all ctables."""
truncate_slice_end = self.data_len_for_day(date)
glob_path = os.path.join(self._rootdir, "*", "*", "*.bcolz")
sid_paths = sorted(glob(glob_path))
for sid_path in sid_paths:
file_name = os... | Truncate data beyond this date in all ctables. | truncate | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def _minutes_to_exclude(self):
"""
Calculate the minutes which should be excluded when a window
occurs on days which had an early close, i.e. days where the close
based on the regular period of minutes per day and the market close
do not match.
Returns
-------
... |
Calculate the minutes which should be excluded when a window
occurs on days which had an early close, i.e. days where the close
based on the regular period of minutes per day and the market close
do not match.
Returns
-------
List of DatetimeIndex representing t... | _minutes_to_exclude | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def _minute_exclusion_tree(self):
"""
Build an interval tree keyed by the start and end of each range
of positions should be dropped from windows. (These are the minutes
between an early close and the minute which would be the close based
on the regular period if there were no ea... |
Build an interval tree keyed by the start and end of each range
of positions should be dropped from windows. (These are the minutes
between an early close and the minute which would be the close based
on the regular period if there were no early close.)
The value of each node is... | _minute_exclusion_tree | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def _exclusion_indices_for_range(self, start_idx, end_idx):
"""
Returns
-------
List of tuples of (start, stop) which represent the ranges of minutes
which should be excluded when a market minute window is requested.
"""
itree = self._minute_exclusion_tree
... |
Returns
-------
List of tuples of (start, stop) which represent the ranges of minutes
which should be excluded when a market minute window is requested.
| _exclusion_indices_for_range | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def get_value(self, sid, dt, field):
"""
Retrieve the pricing info for the given sid, dt, and field.
Parameters
----------
sid : int
Asset identifier.
dt : datetime-like
The datetime at which the trade occurred.
field : string
... |
Retrieve the pricing info for the given sid, dt, and field.
Parameters
----------
sid : int
Asset identifier.
dt : datetime-like
The datetime at which the trade occurred.
field : string
The type of pricing data to retrieve.
... | get_value | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def _find_position_of_minute(self, minute_dt):
"""
Internal method that returns the position of the given minute in the
list of every trading minute since market open of the first trading
day. Adjusts non market minutes to the last close.
ex. this method would return 1 for 2002-... |
Internal method that returns the position of the given minute in the
list of every trading minute since market open of the first trading
day. Adjusts non market minutes to the last close.
ex. this method would return 1 for 2002-01-02 9:32 AM Eastern, if
2002-01-02 is the first ... | _find_position_of_minute | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def write(self, frames):
"""
Write the frames to the target HDF5 file, using the format used by
``pd.Panel.to_hdf``
Parameters
----------
frames : iter[(int, DataFrame)] or dict[int -> DataFrame]
An iterable or other mapping of sid to the corresponding OHLCV
... |
Write the frames to the target HDF5 file, using the format used by
``pd.Panel.to_hdf``
Parameters
----------
frames : iter[(int, DataFrame)] or dict[int -> DataFrame]
An iterable or other mapping of sid to the corresponding OHLCV
pricing data.
| write | python | quantopian/zipline | zipline/data/minute_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/minute_bars.py | Apache-2.0 |
def minute_frame_to_session_frame(minute_frame, calendar):
"""
Resample a DataFrame with minute data into the frame expected by a
BcolzDailyBarWriter.
Parameters
----------
minute_frame : pd.DataFrame
A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`,
and `d... |
Resample a DataFrame with minute data into the frame expected by a
BcolzDailyBarWriter.
Parameters
----------
minute_frame : pd.DataFrame
A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`,
and `dt` (minute dts)
calendar : trading_calendars.trading_calendar.T... | minute_frame_to_session_frame | python | quantopian/zipline | zipline/data/resample.py | https://github.com/quantopian/zipline/blob/master/zipline/data/resample.py | Apache-2.0 |
def minute_to_session(column, close_locs, data, out):
"""
Resample an array with minute data into an array with session data.
This function assumes that the minute data is the exact length of all
minutes in the sessions in the output.
Parameters
----------
column : str
The `open`, ... |
Resample an array with minute data into an array with session data.
This function assumes that the minute data is the exact length of all
minutes in the sessions in the output.
Parameters
----------
column : str
The `open`, `high`, `low`, `close`, or `volume` column.
close_locs : ... | minute_to_session | python | quantopian/zipline | zipline/data/resample.py | https://github.com/quantopian/zipline/blob/master/zipline/data/resample.py | Apache-2.0 |
def opens(self, assets, dt):
"""
The open field's aggregation returns the first value that occurs
for the day, if there has been no data on or before the `dt` the open
is `nan`.
Once the first non-nan open is seen, that value remains constant per
asset for the remainder ... |
The open field's aggregation returns the first value that occurs
for the day, if there has been no data on or before the `dt` the open
is `nan`.
Once the first non-nan open is seen, that value remains constant per
asset for the remainder of the day.
Returns
---... | opens | python | quantopian/zipline | zipline/data/resample.py | https://github.com/quantopian/zipline/blob/master/zipline/data/resample.py | Apache-2.0 |
def highs(self, assets, dt):
"""
The high field's aggregation returns the largest high seen between
the market open and the current dt.
If there has been no data on or before the `dt` the high is `nan`.
Returns
-------
np.array with dtype=float64, in order of ass... |
The high field's aggregation returns the largest high seen between
the market open and the current dt.
If there has been no data on or before the `dt` the high is `nan`.
Returns
-------
np.array with dtype=float64, in order of assets parameter.
| highs | python | quantopian/zipline | zipline/data/resample.py | https://github.com/quantopian/zipline/blob/master/zipline/data/resample.py | Apache-2.0 |
def lows(self, assets, dt):
"""
The low field's aggregation returns the smallest low seen between
the market open and the current dt.
If there has been no data on or before the `dt` the low is `nan`.
Returns
-------
np.array with dtype=float64, in order of assets... |
The low field's aggregation returns the smallest low seen between
the market open and the current dt.
If there has been no data on or before the `dt` the low is `nan`.
Returns
-------
np.array with dtype=float64, in order of assets parameter.
| lows | python | quantopian/zipline | zipline/data/resample.py | https://github.com/quantopian/zipline/blob/master/zipline/data/resample.py | Apache-2.0 |
def closes(self, assets, dt):
"""
The close field's aggregation returns the latest close at the given
dt.
If the close for the given dt is `nan`, the most recent non-nan
`close` is used.
If there has been no data on or before the `dt` the close is `nan`.
Returns
... |
The close field's aggregation returns the latest close at the given
dt.
If the close for the given dt is `nan`, the most recent non-nan
`close` is used.
If there has been no data on or before the `dt` the close is `nan`.
Returns
-------
np.array with dty... | closes | python | quantopian/zipline | zipline/data/resample.py | https://github.com/quantopian/zipline/blob/master/zipline/data/resample.py | Apache-2.0 |
def _get_filled_close(asset):
"""
Returns the most recent non-nan close for the asset in this
session. If there has been no data in this session on or before the
`dt`, returns `nan`
"""
window = self._minute_reader.load_raw_arrays(
... |
Returns the most recent non-nan close for the asset in this
session. If there has been no data in this session on or before the
`dt`, returns `nan`
| _get_filled_close | python | quantopian/zipline | zipline/data/resample.py | https://github.com/quantopian/zipline/blob/master/zipline/data/resample.py | Apache-2.0 |
def volumes(self, assets, dt):
"""
The volume field's aggregation returns the sum of all volumes
between the market open and the `dt`
If there has been no data on or before the `dt` the volume is 0.
Returns
-------
np.array with dtype=int64, in order of assets pa... |
The volume field's aggregation returns the sum of all volumes
between the market open and the `dt`
If there has been no data on or before the `dt` the volume is 0.
Returns
-------
np.array with dtype=int64, in order of assets parameter.
| volumes | python | quantopian/zipline | zipline/data/resample.py | https://github.com/quantopian/zipline/blob/master/zipline/data/resample.py | Apache-2.0 |
def currency_codes(self, sids):
"""
Get currencies in which prices are quoted for the requested sids.
Assumes that a sid's prices are always quoted in a single currency.
Parameters
----------
sids : np.array[int64]
Array of sids for which currencies are need... |
Get currencies in which prices are quoted for the requested sids.
Assumes that a sid's prices are always quoted in a single currency.
Parameters
----------
sids : np.array[int64]
Array of sids for which currencies are needed.
Returns
-------
... | currency_codes | python | quantopian/zipline | zipline/data/session_bars.py | https://github.com/quantopian/zipline/blob/master/zipline/data/session_bars.py | Apache-2.0 |
def _make_bundle_core():
"""Create a family of data bundle functions that read from the same
bundle mapping.
Returns
-------
bundles : mappingproxy
The mapping of bundles to bundle payloads.
register : callable
The function which registers new bundles in the ``bundles`` mapping.... | Create a family of data bundle functions that read from the same
bundle mapping.
Returns
-------
bundles : mappingproxy
The mapping of bundles to bundle payloads.
register : callable
The function which registers new bundles in the ``bundles`` mapping.
unregister : callable
... | _make_bundle_core | python | quantopian/zipline | zipline/data/bundles/core.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/core.py | Apache-2.0 |
def register(name,
f,
calendar_name='NYSE',
start_session=None,
end_session=None,
minutes_per_day=390,
create_writers=True):
"""Register a data bundle ingest function.
Parameters
----------
... | Register a data bundle ingest function.
Parameters
----------
name : str
The name of the bundle.
f : callable
The ingest function. This function will be passed:
environ : mapping
The environment this is being run with.
... | register | python | quantopian/zipline | zipline/data/bundles/core.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/core.py | Apache-2.0 |
def unregister(name):
"""Unregister a bundle.
Parameters
----------
name : str
The name of the bundle to unregister.
Raises
------
UnknownBundle
Raised when no bundle has been registered with the given name.
See Also
----... | Unregister a bundle.
Parameters
----------
name : str
The name of the bundle to unregister.
Raises
------
UnknownBundle
Raised when no bundle has been registered with the given name.
See Also
--------
zipline.data.bundles... | unregister | python | quantopian/zipline | zipline/data/bundles/core.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/core.py | Apache-2.0 |
def ingest(name,
environ=os.environ,
timestamp=None,
assets_versions=(),
show_progress=False):
"""Ingest data for a given bundle.
Parameters
----------
name : str
The name of the bundle.
environ : mapping, o... | Ingest data for a given bundle.
Parameters
----------
name : str
The name of the bundle.
environ : mapping, optional
The environment variables. By default this is os.environ.
timestamp : datetime, optional
The timestamp to use for the load.
... | ingest | python | quantopian/zipline | zipline/data/bundles/core.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/core.py | Apache-2.0 |
def most_recent_data(bundle_name, timestamp, environ=None):
"""Get the path to the most recent data after ``date``for the
given bundle.
Parameters
----------
bundle_name : str
The name of the bundle to lookup.
timestamp : datetime
The timestamp to... | Get the path to the most recent data after ``date``for the
given bundle.
Parameters
----------
bundle_name : str
The name of the bundle to lookup.
timestamp : datetime
The timestamp to begin searching on or before.
environ : dict, optional
... | most_recent_data | python | quantopian/zipline | zipline/data/bundles/core.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/core.py | Apache-2.0 |
def load(name, environ=os.environ, timestamp=None):
"""Loads a previously ingested bundle.
Parameters
----------
name : str
The name of the bundle.
environ : mapping, optional
The environment variables. Defaults of os.environ.
timestamp : datetime... | Loads a previously ingested bundle.
Parameters
----------
name : str
The name of the bundle.
environ : mapping, optional
The environment variables. Defaults of os.environ.
timestamp : datetime, optional
The timestamp of the data to lookup.
... | load | python | quantopian/zipline | zipline/data/bundles/core.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/core.py | Apache-2.0 |
def clean(name,
before=None,
after=None,
keep_last=None,
environ=os.environ):
"""Clean up data that was created with ``ingest`` or
``$ python -m zipline ingest``
Parameters
----------
name : str
The name of the ... | Clean up data that was created with ``ingest`` or
``$ python -m zipline ingest``
Parameters
----------
name : str
The name of the bundle to remove data for.
before : datetime, optional
Remove data ingested before this date.
This argument is mu... | clean | python | quantopian/zipline | zipline/data/bundles/core.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/core.py | Apache-2.0 |
def csvdir_bundle(environ,
asset_db_writer,
minute_bar_writer,
daily_bar_writer,
adjustment_writer,
calendar,
start_session,
end_session,
cache,
show_progress... |
Build a zipline data bundle from the directory with csv files.
| csvdir_bundle | python | quantopian/zipline | zipline/data/bundles/csvdir.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/csvdir.py | Apache-2.0 |
def format_metadata_url(api_key):
""" Build the query URL for Quandl WIKI Prices metadata.
"""
query_params = [('api_key', api_key), ('qopts.export', 'true')]
return (
QUANDL_DATA_URL + urlencode(query_params)
) | Build the query URL for Quandl WIKI Prices metadata.
| format_metadata_url | python | quantopian/zipline | zipline/data/bundles/quandl.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/quandl.py | Apache-2.0 |
def load_data_table(file,
index_col,
show_progress=False):
""" Load data table from zip file provided by Quandl.
"""
with ZipFile(file) as zip_file:
file_names = zip_file.namelist()
assert len(file_names) == 1, "Expected a single file from Quandl."
... | Load data table from zip file provided by Quandl.
| load_data_table | python | quantopian/zipline | zipline/data/bundles/quandl.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/quandl.py | Apache-2.0 |
def fetch_data_table(api_key,
show_progress,
retries):
""" Fetch WIKI Prices data table from Quandl
"""
for _ in range(retries):
try:
if show_progress:
log.info('Downloading WIKI metadata.')
metadata = pd.read_csv(
... | Fetch WIKI Prices data table from Quandl
| fetch_data_table | python | quantopian/zipline | zipline/data/bundles/quandl.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/quandl.py | Apache-2.0 |
def quandl_bundle(environ,
asset_db_writer,
minute_bar_writer,
daily_bar_writer,
adjustment_writer,
calendar,
start_session,
end_session,
cache,
show_progress... |
quandl_bundle builds a daily dataset using Quandl's WIKI Prices dataset.
For more information on Quandl's API and how to obtain an API key,
please visit https://docs.quandl.com/docs#section-authentication
| quandl_bundle | python | quantopian/zipline | zipline/data/bundles/quandl.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/quandl.py | Apache-2.0 |
def download_with_progress(url, chunk_size, **progress_kwargs):
"""
Download streaming data from a URL, printing progress information to the
terminal.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
chunk_size : int
Number of bytes to read a... |
Download streaming data from a URL, printing progress information to the
terminal.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
chunk_size : int
Number of bytes to read at a time from requests.
**progress_kwargs
Forwarded to clic... | download_with_progress | python | quantopian/zipline | zipline/data/bundles/quandl.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/quandl.py | Apache-2.0 |
def download_without_progress(url):
"""
Download data from a URL, returning a BytesIO containing the loaded data.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
Returns
-------
data : BytesIO
A BytesIO containing the downloaded data.
... |
Download data from a URL, returning a BytesIO containing the loaded data.
Parameters
----------
url : str
A URL that can be understood by ``requests.get``.
Returns
-------
data : BytesIO
A BytesIO containing the downloaded data.
| download_without_progress | python | quantopian/zipline | zipline/data/bundles/quandl.py | https://github.com/quantopian/zipline/blob/master/zipline/data/bundles/quandl.py | Apache-2.0 |
def get_rates(self, rate, quote, bases, dts):
"""
Load a 2D array of fx rates.
Parameters
----------
rate : str
Name of the rate to load.
quote : str
Currency code of the currency to convert into.
bases : np.array[object]
Array... |
Load a 2D array of fx rates.
Parameters
----------
rate : str
Name of the rate to load.
quote : str
Currency code of the currency to convert into.
bases : np.array[object]
Array of codes of the currencies to convert from. The same cur... | get_rates | python | quantopian/zipline | zipline/data/fx/base.py | https://github.com/quantopian/zipline/blob/master/zipline/data/fx/base.py | Apache-2.0 |
def get_rate_scalar(self, rate, quote, base, dt):
"""
Load a scalar FX rate value.
Parameters
----------
rate : str
Name of the rate to load.
quote : str
Currency code of the currency to convert into.
base : str
Currency code o... |
Load a scalar FX rate value.
Parameters
----------
rate : str
Name of the rate to load.
quote : str
Currency code of the currency to convert into.
base : str
Currency code of the currency to convert from.
dt : np.datetime64 or... | get_rate_scalar | python | quantopian/zipline | zipline/data/fx/base.py | https://github.com/quantopian/zipline/blob/master/zipline/data/fx/base.py | Apache-2.0 |
def get_rates_columnar(self, rate, quote, bases, dts):
"""
Load a 1D array of FX rates.
Parameters
----------
rate : str
Name of the rate to load.
quote : str
Currency code of the currency to convert into.
bases : np.array[object]
... |
Load a 1D array of FX rates.
Parameters
----------
rate : str
Name of the rate to load.
quote : str
Currency code of the currency to convert into.
bases : np.array[object]
Array of codes of the currencies to convert from. The same cur... | get_rates_columnar | python | quantopian/zipline | zipline/data/fx/base.py | https://github.com/quantopian/zipline/blob/master/zipline/data/fx/base.py | Apache-2.0 |
def get_rates(self, rate, quote, bases, dts):
"""Get rates to convert ``bases`` into ``quote``.
See :class:`zipline.data.fx.base.FXRateReader` for details.
"""
if rate == DEFAULT_FX_RATE:
rate = self._default_rate
check_dts(dts)
col_ixs = self.dts.searchsor... | Get rates to convert ``bases`` into ``quote``.
See :class:`zipline.data.fx.base.FXRateReader` for details.
| get_rates | python | quantopian/zipline | zipline/data/fx/hdf5.py | https://github.com/quantopian/zipline/blob/master/zipline/data/fx/hdf5.py | Apache-2.0 |
def write(self, dts, currencies, data):
"""Write data to the file.
Parameters
----------
dts : pd.DatetimeIndex
Index of row labels for rates to be written.
currencies : np.array[object]
Array of column labels for rates to be written.
data : itera... | Write data to the file.
Parameters
----------
dts : pd.DatetimeIndex
Index of row labels for rates to be written.
currencies : np.array[object]
Array of column labels for rates to be written.
data : iterator[(str, str, np.array[float64])]
Iter... | write | python | quantopian/zipline | zipline/data/fx/hdf5.py | https://github.com/quantopian/zipline/blob/master/zipline/data/fx/hdf5.py | Apache-2.0 |
def check_dts(requested_dts):
"""Validate that ``requested_dts`` are valid for querying from an FX reader.
"""
if not is_sorted_ascending(requested_dts):
raise ValueError("Requested fx rates with non-ascending dts.") | Validate that ``requested_dts`` are valid for querying from an FX reader.
| check_dts | python | quantopian/zipline | zipline/data/fx/utils.py | https://github.com/quantopian/zipline/blob/master/zipline/data/fx/utils.py | Apache-2.0 |
def _test_args():
"""Extra arguments to use when zipline's automated tests run this example.
"""
import pandas as pd
return {
'start': pd.Timestamp('2014-01-01', tz='utc'),
'end': pd.Timestamp('2014-11-01', tz='utc'),
} | Extra arguments to use when zipline's automated tests run this example.
| _test_args | python | quantopian/zipline | zipline/examples/buyapple.py | https://github.com/quantopian/zipline/blob/master/zipline/examples/buyapple.py | Apache-2.0 |
def _test_args():
"""
Extra arguments to use when zipline's automated tests run this example.
Notes for testers:
Gross leverage should be roughly 2.0 on every day except the first.
Net leverage should be roughly 2.0 on every day except the first.
Longs Count should always be 3 after the first... |
Extra arguments to use when zipline's automated tests run this example.
Notes for testers:
Gross leverage should be roughly 2.0 on every day except the first.
Net leverage should be roughly 2.0 on every day except the first.
Longs Count should always be 3 after the first day.
Shorts Count sh... | _test_args | python | quantopian/zipline | zipline/examples/momentum_pipeline.py | https://github.com/quantopian/zipline/blob/master/zipline/examples/momentum_pipeline.py | Apache-2.0 |
def run_example(example_modules, example_name, environ,
benchmark_returns=None):
"""
Run an example module from zipline.examples.
"""
mod = example_modules[example_name]
register_calendar("YAHOO", get_calendar("NYSE"), force=True)
return run_algorithm(
initialize=getatt... |
Run an example module from zipline.examples.
| run_example | python | quantopian/zipline | zipline/examples/__init__.py | https://github.com/quantopian/zipline/blob/master/zipline/examples/__init__.py | Apache-2.0 |
def __or__(self, other_restriction):
"""Base implementation for combining two restrictions.
"""
# If the right side is a _UnionRestrictions, defers to the
# _UnionRestrictions implementation of `|`, which intelligently
# flattens restricted lists
if isinstance(other_restr... | Base implementation for combining two restrictions.
| __or__ | python | quantopian/zipline | zipline/finance/asset_restrictions.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/asset_restrictions.py | Apache-2.0 |
def __or__(self, other_restriction):
"""
Overrides the base implementation for combining two restrictions, of
which the left side is a _UnionRestrictions.
"""
# Flatten the underlying sub restrictions of _UnionRestrictions
if isinstance(other_restriction, _UnionRestrictio... |
Overrides the base implementation for combining two restrictions, of
which the left side is a _UnionRestrictions.
| __or__ | python | quantopian/zipline | zipline/finance/asset_restrictions.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/asset_restrictions.py | Apache-2.0 |
def is_restricted(self, assets, dt):
"""
An asset is restricted for all dts if it is in the static list.
"""
if isinstance(assets, Asset):
return assets in self._restricted_set
return pd.Series(
index=pd.Index(assets),
data=vectorized_is_elemen... |
An asset is restricted for all dts if it is in the static list.
| is_restricted | python | quantopian/zipline | zipline/finance/asset_restrictions.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/asset_restrictions.py | Apache-2.0 |
def is_restricted(self, assets, dt):
"""
Returns whether or not an asset or iterable of assets is restricted
on a dt.
"""
if isinstance(assets, Asset):
return self._is_restricted_for_asset(assets, dt)
is_restricted = partial(self._is_restricted_for_asset, dt=... |
Returns whether or not an asset or iterable of assets is restricted
on a dt.
| is_restricted | python | quantopian/zipline | zipline/finance/asset_restrictions.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/asset_restrictions.py | Apache-2.0 |
def calculate_per_unit_commission(order,
transaction,
cost_per_unit,
initial_commission,
min_trade_cost):
"""
If there is a minimum commission:
If the order hasn't had ... |
If there is a minimum commission:
If the order hasn't had a commission paid yet, pay the minimum
commission.
If the order has paid a commission, start paying additional
commission once the minimum commission has been reached.
If there is no minimum commission:
Pay comm... | calculate_per_unit_commission | python | quantopian/zipline | zipline/finance/commission.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/commission.py | Apache-2.0 |
def __init__(self, cost=DEFAULT_MINIMUM_COST_PER_EQUITY_TRADE):
"""
Cost parameter is the cost of a trade, regardless of share count.
$5.00 per trade is fairly typical of discount brokers.
"""
# Cost needs to be floating point so that calculation using division
# logic do... |
Cost parameter is the cost of a trade, regardless of share count.
$5.00 per trade is fairly typical of discount brokers.
| __init__ | python | quantopian/zipline | zipline/finance/commission.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/commission.py | Apache-2.0 |
def calculate(self, order, transaction):
"""
If the order hasn't had a commission paid yet, pay the fixed
commission.
"""
if order.commission == 0:
# if the order hasn't had a commission attributed to it yet,
# that's what we need to pay.
retur... |
If the order hasn't had a commission paid yet, pay the fixed
commission.
| calculate | python | quantopian/zipline | zipline/finance/commission.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/commission.py | Apache-2.0 |
def calculate(self, order, transaction):
"""
Pay commission based on dollar value of shares.
"""
cost_per_share = transaction.price * self.cost_per_dollar
return abs(transaction.amount) * cost_per_share |
Pay commission based on dollar value of shares.
| calculate | python | quantopian/zipline | zipline/finance/commission.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/commission.py | Apache-2.0 |
def __init__(self, on_error, **kwargs):
"""
Track any arguments that should be printed in the error message
generated by self.fail.
"""
self.on_error = on_error
self.__fail_args = kwargs |
Track any arguments that should be printed in the error message
generated by self.fail.
| __init__ | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
"""
Before any order is executed by TradingAlgorithm, this method should be
called *exactly once* on each registered TradingControl... |
Before any order is executed by TradingAlgorithm, this method should be
called *exactly once* on each registered TradingControl object.
If the specified asset and amount do not violate this TradingControl's
restraint given the information in `portfolio`, this method should
retu... | validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def handle_violation(self, asset, amount, datetime, metadata=None):
"""
Handle a TradingControlViolation, either by raising or logging and
error with information about the failure.
If dynamic information should be displayed as well, pass it in via
`metadata`.
"""
... |
Handle a TradingControlViolation, either by raising or logging and
error with information about the failure.
If dynamic information should be displayed as well, pass it in via
`metadata`.
| handle_violation | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
"""
Fail if we've already placed self.max_count orders today.
"""
algo_date = algo_datetime.date()
# Reset order c... |
Fail if we've already placed self.max_count orders today.
| validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
"""
Fail if the asset is in the restricted_list.
"""
if self.restrictions.is_restricted(asset, algo_datetime):
... |
Fail if the asset is in the restricted_list.
| validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
"""
Fail if the magnitude of the given order exceeds either self.max_shares
or self.max_notional.
"""
if self.asse... |
Fail if the magnitude of the given order exceeds either self.max_shares
or self.max_notional.
| validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
"""
Fail if the given order would cause the magnitude of our position to be
greater in shares than self.max_shares or greater in do... |
Fail if the given order would cause the magnitude of our position to be
greater in shares than self.max_shares or greater in dollar value than
self.max_notional.
| validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
"""
Fail if we would hold negative shares of asset after completing this
order.
"""
if portfolio.positions[asset].a... |
Fail if we would hold negative shares of asset after completing this
order.
| validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
"""
Fail if the algo has passed this Asset's end_date, or before the
Asset's start date.
"""
# If the order is for ... |
Fail if the algo has passed this Asset's end_date, or before the
Asset's start date.
| validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
_portfolio,
_account,
_algo_datetime,
_algo_current_data):
"""
On each call to handle data by TradingAlgorithm, this method should be
called *exactly once* on each registered AccountControl object.
If... |
On each call to handle data by TradingAlgorithm, this method should be
called *exactly once* on each registered AccountControl object.
If the check does not violate this AccountControl's restraint given
the information in `portfolio` and `account`, this method should
return Non... | validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
_portfolio,
_account,
_algo_datetime,
_algo_current_data):
"""
Fail if the leverage is greater than the allowed leverage.
"""
if _account.leverage > self.max_leverage:
self.fail() |
Fail if the leverage is greater than the allowed leverage.
| validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def validate(self,
_portfolio,
account,
algo_datetime,
_algo_current_data):
"""
Make validation checks if we are after the deadline.
Fail if the leverage is less than the min leverage.
"""
if (algo_datetime > sel... |
Make validation checks if we are after the deadline.
Fail if the leverage is less than the min leverage.
| validate | python | quantopian/zipline | zipline/finance/controls.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/controls.py | Apache-2.0 |
def handle_splits(self, splits):
"""Processes a list of splits by modifying any positions as needed.
Parameters
----------
splits: list
A list of splits. Each split is a tuple of (asset, ratio).
Returns
-------
int: The leftover cash from fractional... | Processes a list of splits by modifying any positions as needed.
Parameters
----------
splits: list
A list of splits. Each split is a tuple of (asset, ratio).
Returns
-------
int: The leftover cash from fractional shares after modifying each
pos... | handle_splits | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def earn_dividends(self, cash_dividends, stock_dividends):
"""Given a list of dividends whose ex_dates are all the next trading
day, calculate and store the cash and/or stock payments to be paid on
each dividend's pay date.
Parameters
----------
cash_dividends : iterable... | Given a list of dividends whose ex_dates are all the next trading
day, calculate and store the cash and/or stock payments to be paid on
each dividend's pay date.
Parameters
----------
cash_dividends : iterable of (asset, amount, pay_date) namedtuples
stock_dividends: it... | earn_dividends | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def pay_dividends(self, next_trading_day):
"""
Returns a cash payment based on the dividends that should be paid out
according to the accumulated bookkeeping of earned, unpaid, and stock
dividends.
"""
net_cash_payment = 0.0
try:
payments = self._unpa... |
Returns a cash payment based on the dividends that should be paid out
according to the accumulated bookkeeping of earned, unpaid, and stock
dividends.
| pay_dividends | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def stats(self):
"""The current status of the positions.
Returns
-------
stats : PositionStats
The current stats position stats.
Notes
-----
This is cached, repeated access will not recompute the stats until
the stats may have changed.
... | The current status of the positions.
Returns
-------
stats : PositionStats
The current stats position stats.
Notes
-----
This is cached, repeated access will not recompute the stats until
the stats may have changed.
| stats | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def process_transaction(self, transaction):
"""Add a transaction to ledger, updating the current state as needed.
Parameters
----------
transaction : zp.Transaction
The transaction to execute.
"""
asset = transaction.asset
if isinstance(asset, Future)... | Add a transaction to ledger, updating the current state as needed.
Parameters
----------
transaction : zp.Transaction
The transaction to execute.
| process_transaction | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def process_splits(self, splits):
"""Processes a list of splits by modifying any positions as needed.
Parameters
----------
splits: list[(Asset, float)]
A list of splits. Each split is a tuple of (asset, ratio).
"""
leftover_cash = self.position_tracker.handl... | Processes a list of splits by modifying any positions as needed.
Parameters
----------
splits: list[(Asset, float)]
A list of splits. Each split is a tuple of (asset, ratio).
| process_splits | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def process_order(self, order):
"""Keep track of an order that was placed.
Parameters
----------
order : zp.Order
The order to record.
"""
try:
dt_orders = self._orders_by_modified[order.dt]
except KeyError:
self._orders_by_mod... | Keep track of an order that was placed.
Parameters
----------
order : zp.Order
The order to record.
| process_order | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def process_commission(self, commission):
"""Process the commission.
Parameters
----------
commission : zp.Event
The commission being paid.
"""
asset = commission['asset']
cost = commission['cost']
self.position_tracker.handle_commission(asse... | Process the commission.
Parameters
----------
commission : zp.Event
The commission being paid.
| process_commission | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def process_dividends(self, next_session, asset_finder, adjustment_reader):
"""Process dividends for the next session.
This will earn us any dividends whose ex-date is the next session as
well as paying out any dividends whose pay-date is the next session
"""
position_tracker = ... | Process dividends for the next session.
This will earn us any dividends whose ex-date is the next session as
well as paying out any dividends whose pay-date is the next session
| process_dividends | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def transactions(self, dt=None):
"""Retrieve the dict-form of all of the transactions in a given bar or
for the whole simulation.
Parameters
----------
dt : pd.Timestamp or None, optional
The particular datetime to look up transactions for. If not passed,
... | Retrieve the dict-form of all of the transactions in a given bar or
for the whole simulation.
Parameters
----------
dt : pd.Timestamp or None, optional
The particular datetime to look up transactions for. If not passed,
or None is explicitly passed, all of the tr... | transactions | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def orders(self, dt=None):
"""Retrieve the dict-form of all of the orders in a given bar or for
the whole simulation.
Parameters
----------
dt : pd.Timestamp or None, optional
The particular datetime to look up order for. If not passed, or
None is explici... | Retrieve the dict-form of all of the orders in a given bar or for
the whole simulation.
Parameters
----------
dt : pd.Timestamp or None, optional
The particular datetime to look up order for. If not passed, or
None is explicitly passed, all of the orders will be ... | orders | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def update_portfolio(self):
"""Force a computation of the current portfolio state.
"""
if not self._dirty_portfolio:
return
portfolio = self._portfolio
pt = self.position_tracker
portfolio.positions = pt.get_positions()
position_stats = pt.stats
... | Force a computation of the current portfolio state.
| update_portfolio | python | quantopian/zipline | zipline/finance/ledger.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/ledger.py | Apache-2.0 |
def __init__(self, dt, asset, amount, stop=None, limit=None, filled=0,
commission=0, id=None):
"""
@dt - datetime.datetime that the order was placed
@asset - asset for the order.
@amount - the number of shares to buy/sell
a positive sign indicates a buy... |
@dt - datetime.datetime that the order was placed
@asset - asset for the order.
@amount - the number of shares to buy/sell
a positive sign indicates a buy
a negative sign indicates a sell
@filled - how many shares of the order have been filled so far
... | __init__ | python | quantopian/zipline | zipline/finance/order.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/order.py | Apache-2.0 |
def check_triggers(self, price, dt):
"""
Update internal state based on price triggers and the
trade event's price.
"""
stop_reached, limit_reached, sl_stop_reached = \
self.check_order_triggers(price)
if (stop_reached, limit_reached) \
!= (sel... |
Update internal state based on price triggers and the
trade event's price.
| check_triggers | python | quantopian/zipline | zipline/finance/order.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/order.py | Apache-2.0 |
def earn_dividend(self, dividend):
"""
Register the number of shares we held at this dividend's ex date so
that we can pay out the correct amount on the dividend's pay date.
"""
return {
'amount': self.amount * dividend.amount
} |
Register the number of shares we held at this dividend's ex date so
that we can pay out the correct amount on the dividend's pay date.
| earn_dividend | python | quantopian/zipline | zipline/finance/position.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/position.py | Apache-2.0 |
def handle_split(self, asset, ratio):
"""
Update the position by the split ratio, and return the resulting
fractional share that will be converted into cash.
Returns the unused cash.
"""
if self.asset != asset:
raise Exception("updating split with the wrong a... |
Update the position by the split ratio, and return the resulting
fractional share that will be converted into cash.
Returns the unused cash.
| handle_split | python | quantopian/zipline | zipline/finance/position.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/position.py | Apache-2.0 |
def to_dict(self):
"""
Creates a dictionary representing the state of this position.
Returns a dict object of the form:
"""
return {
'sid': self.asset,
'amount': self.amount,
'cost_basis': self.cost_basis,
'last_sale_price': self.la... |
Creates a dictionary representing the state of this position.
Returns a dict object of the form:
| to_dict | python | quantopian/zipline | zipline/finance/position.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/position.py | Apache-2.0 |
def get_simulated_impact(self,
order,
current_price,
current_volume,
txn_volume,
mean_volume,
volatility):
"""
Calculate simulated... |
Calculate simulated price impact.
Parameters
----------
order : The order being processed.
current_price : Current price of the asset being ordered.
current_volume : Volume of the asset being ordered for the current bar.
txn_volume : Number of shares/contracts b... | get_simulated_impact | python | quantopian/zipline | zipline/finance/slippage.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/slippage.py | Apache-2.0 |
def _get_window_data(self, data, asset, window_length):
"""
Internal utility method to return the trailing mean volume over the
past 'window_length' days, and volatility of close prices for a
specific asset.
Parameters
----------
data : The BarData from which to ... |
Internal utility method to return the trailing mean volume over the
past 'window_length' days, and volatility of close prices for a
specific asset.
Parameters
----------
data : The BarData from which to fetch the daily windows.
asset : The Asset whose data we ar... | _get_window_data | python | quantopian/zipline | zipline/finance/slippage.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/slippage.py | Apache-2.0 |
def cancel_all_orders_for_asset(self, asset, warn=False,
relay_status=True):
"""
Cancel all open orders for a given asset.
"""
raise NotImplementedError('cancel_all_orders_for_asset') |
Cancel all open orders for a given asset.
| cancel_all_orders_for_asset | python | quantopian/zipline | zipline/finance/blotter/blotter.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/blotter/blotter.py | Apache-2.0 |
def reject(self, order_id, reason=''):
"""
Mark the given order as 'rejected', which is functionally similar to
cancelled. The distinction is that rejections are involuntary (and
usually include a message from a broker indicating why the order was
rejected) while cancels are typi... |
Mark the given order as 'rejected', which is functionally similar to
cancelled. The distinction is that rejections are involuntary (and
usually include a message from a broker indicating why the order was
rejected) while cancels are typically user-driven.
| reject | python | quantopian/zipline | zipline/finance/blotter/simulation_blotter.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/blotter/simulation_blotter.py | Apache-2.0 |
def hold(self, order_id, reason=''):
"""
Mark the order with order_id as 'held'. Held is functionally similar
to 'open'. When a fill (full or partial) arrives, the status
will automatically change back to open/filled as necessary.
"""
if order_id not in self.orders:
... |
Mark the order with order_id as 'held'. Held is functionally similar
to 'open'. When a fill (full or partial) arrives, the status
will automatically change back to open/filled as necessary.
| hold | python | quantopian/zipline | zipline/finance/blotter/simulation_blotter.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/blotter/simulation_blotter.py | Apache-2.0 |
def process_splits(self, splits):
"""
Processes a list of splits by modifying any open orders as needed.
Parameters
----------
splits: list
A list of splits. Each split is a tuple of (asset, ratio).
Returns
-------
None
"""
f... |
Processes a list of splits by modifying any open orders as needed.
Parameters
----------
splits: list
A list of splits. Each split is a tuple of (asset, ratio).
Returns
-------
None
| process_splits | python | quantopian/zipline | zipline/finance/blotter/simulation_blotter.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/blotter/simulation_blotter.py | Apache-2.0 |
def get_transactions(self, bar_data):
"""
Creates a list of transactions based on the current open orders,
slippage model, and commission model.
Parameters
----------
bar_data: zipline._protocol.BarData
Notes
-----
This method book-keeps the blot... |
Creates a list of transactions based on the current open orders,
slippage model, and commission model.
Parameters
----------
bar_data: zipline._protocol.BarData
Notes
-----
This method book-keeps the blotter's open_orders dictionary, so that
it... | get_transactions | python | quantopian/zipline | zipline/finance/blotter/simulation_blotter.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/blotter/simulation_blotter.py | Apache-2.0 |
def prune_orders(self, closed_orders):
"""
Removes all given orders from the blotter's open_orders list.
Parameters
----------
closed_orders: iterable of orders that are closed.
Returns
-------
None
"""
# remove all closed orders from our... |
Removes all given orders from the blotter's open_orders list.
Parameters
----------
closed_orders: iterable of orders that are closed.
Returns
-------
None
| prune_orders | python | quantopian/zipline | zipline/finance/blotter/simulation_blotter.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/blotter/simulation_blotter.py | Apache-2.0 |
def _make_metrics_set_core():
"""Create a family of metrics sets functions that read from the same
metrics set mapping.
Returns
-------
metrics_sets : mappingproxy
The mapping of metrics sets to load functions.
register : callable
The function which registers new metrics sets in... | Create a family of metrics sets functions that read from the same
metrics set mapping.
Returns
-------
metrics_sets : mappingproxy
The mapping of metrics sets to load functions.
register : callable
The function which registers new metrics sets in the ``metrics_sets``
mapping... | _make_metrics_set_core | python | quantopian/zipline | zipline/finance/metrics/core.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/core.py | Apache-2.0 |
def register(name, function=None):
"""Register a new metrics set.
Parameters
----------
name : str
The name of the metrics set
function : callable
The callable which produces the metrics set.
Notes
-----
This may be used as a deco... | Register a new metrics set.
Parameters
----------
name : str
The name of the metrics set
function : callable
The callable which produces the metrics set.
Notes
-----
This may be used as a decorator if only ``name`` is passed.
See... | register | python | quantopian/zipline | zipline/finance/metrics/core.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/core.py | Apache-2.0 |
def unregister(name):
"""Unregister an existing metrics set.
Parameters
----------
name : str
The name of the metrics set
See Also
--------
zipline.finance.metrics.register_metrics_set
"""
try:
del _metrics_sets[name]
... | Unregister an existing metrics set.
Parameters
----------
name : str
The name of the metrics set
See Also
--------
zipline.finance.metrics.register_metrics_set
| unregister | python | quantopian/zipline | zipline/finance/metrics/core.py | https://github.com/quantopian/zipline/blob/master/zipline/finance/metrics/core.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.