desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns a filtered list with copies of each command entry
in the document
Arguments:
how -- how it should be filtered, possible types are:
string - only commands, which equals this string
list of string - only commands which are in this list
function of command->bool - should return true iff the command
should be in t... | def filter_commands(self, how, flags=DEFAULT_FLAGS):
| if isinstance(how, strbase):
def command_filter(c):
return (c.command == how)
elif (type(how) is list):
def command_filter(c):
return (c.command in how)
elif callable(how):
def command_filter(c):
return how(c)
else:
raise Exception(('Un... |
'Stops this thread pool. Note stopping is not immediate. If you
need to wait for the termination to complete, you should call join()
after this.'
| def terminate(self):
| self._should_stop.set()
|
'Arguments
file_name -- the name of the file of the entry
region -- the sublime.Region inside the file'
| def __init__(self, file_name, region, **kwargs):
| self.file_name = file_name
self.region = region
self.start = self.region.begin()
self.end = self.region.end()
|
'Adds an item to the list in the overlay before the entries.
Arguments:
position -- The position where to add the item. This must be before
the content. The use of AT_START and AT_END is recommended
name -- The caption of the item. Must be unique for all non-entries.
done_handler -- This handler will be executed, when ... | def add_item(self, position, name, done_handler=None, change_handler=None):
| index = {AT_START: 0, AT_END: self._offset}.get(position, position)
index = min(max(0, index), self._offset)
self.captions.insert(index, name)
self._offset += 1
if done_handler:
self.done_handler[name] = done_handler
if change_handler:
self.change_handler[name] = change_handler
|
'Opens a quickpanel based on the initialized data'
| def show_quickpanel(self, selected_index=0):
| if _ST3:
flags = {'selected_index': selected_index, 'on_highlight': self._on_changed}
else:
flags = {}
self.window.show_quick_panel(self.captions, self._on_done, **flags)
|
'Removes the highlight from the view.
If the view None, then the highlight of the active view will be
removed.'
| def _remove_highlight(self, view=None):
| if (not view):
view = self.window.active_view()
view.erase_regions('temp_highlight_command')
|
'Add the highlight to the region'
| def _add_highlight(self, view, region):
| flags = sublime.DRAW_NO_FILL
view.add_regions('temp_highlight_command', [region], 'comment', flags=flags)
|
'Opens the file of a command in transient mode, focuses and highlights
the region of the command'
| def _open_transient(self, command):
| file_name = command.file_name
v = self.window.open_file(file_name, sublime.TRANSIENT)
run_after_loading(v, (lambda : self._add_highlight(v, command.region)))
run_after_loading(v, (lambda : v.show(command.region)))
|
'Handles a item change in the quickpanel:
Calls the handler if the item is below the offset.
Otherwise it opens the file and highlights the command.'
| def _on_changed(self, index):
| if (index < self._offset):
key = self.captions[index]
handle = self.change_handler.get(key, (lambda : None))
handle()
return
self._remove_highlight()
self._open_transient(self.entries[(index - self._offset)])
|
'Restores the viewport (and file) from before the quickpanel'
| def _restore_viewport(self):
| self._remove_highlight()
self.window.focus_view(self.view)
self.view.set_viewport_position(self.viewport_position, False)
|
'Move the viewport to focus the region of a command.
If the file of the command is not opened, then it will also open the
file.'
| def _move_viewport(self, command):
| self._remove_highlight()
file_name = command.file_name
view = self.window.open_file(file_name)
def move():
view.sel().clear()
view.sel().add(command.region)
view.show(command.start)
self._remove_highlight(view)
run_after_loading(view, move)
|
'Handles a item select in the quickpanel:
Calls the handler if the item is below the offset.
Otherwise it opens the file and focus the command.'
| def _on_done(self, index):
| if (index == (-1)):
self._restore_viewport()
return
elif (index < self._offset):
self._remove_highlight()
key = self.captions[index]
handle = self.done_handler.get(key, (lambda : None))
handle()
return
self._move_viewport(self.entries[(index - self._of... |
'Gets the completions to display with Sublime\'s autocomplete
Should return a list of completions or a tuple consisting of a list of
completions and a single character to be inserted. This second option
is to allow completing, e.g., ef -> ef{}
:param view:
The view the completions are requested for
:param prefix:
The c... | def get_auto_completions(self, view, prefix, line):
| return []
|
'Gets the completions to display in the quick panel
Should return a list of completions formatted to be displayed in the
quick panel.
:param view:
The view the completions are requested for
:param prefix:
The current word the user has selected
Note that if completions are entered using { , etc. this will be
blank
:para... | def get_completions(self, view, prefix, line):
| return None
|
'Checks if this plugin matches the current line
:param line:
The current line to check'
| def matches_line(self, line):
| return False
|
'Returns the scope selector, in which the completion should be
enabled. Default value is outside comments (- comment).
Omit text.tex.latex, because it is always checked.'
| def get_supported_scope_selector(self):
| return '- comment'
|
'Checks whether this plugin should be used for triggered completions'
| def is_enabled(self):
| return False
|
'retrieve the cached value for the corresponding key
raises CacheMiss if value has not been cached
:param key:
the key that the value has been stored under'
| def get(self, key):
| if (key is None):
raise ValueError('key cannot be None')
try:
result = self._objects[key]
except KeyError:
result = self.load(key)
if (result is _invalid_object):
raise CacheMiss('{0} is invalid'.format(key))
try:
if (hasattr(result, '__dict__')... |
'check if cache has a value for the corresponding key
:param key:
the key that the value has been stored under'
| def has(self, key):
| if (key is None):
raise ValueError('key cannot be None')
return ((key in self._objects) and (self._objects[key] is not _invalid_object))
|
'set the cache value for the given key
:param key:
the key to store the value under
:param obj:
the value to store; note that obj *must* be picklable'
| def set(self, key, obj):
| if (key is None):
raise ValueError('key cannot be None')
try:
pickle.dumps(obj, protocol=(-1))
except pickle.PicklingError:
raise ValueError('obj must be picklable')
if isinstance(obj, list):
obj = tuple(obj)
elif isinstance(obj, dict):
obj =... |
'convenience method to attempt to get the value from the cache and
generate the value if it hasn\'t been cached yet or the entry has
otherwise been invalidated
:param key:
the key to retrieve or set
:param func:
a callable that takes no arguments and when invoked will return
the proper value'
| def cache(self, key, func):
| if (key is None):
raise ValueError('key cannot be None')
try:
return self.get(key)
except:
result = func()
self.set(key, result)
return result
|
'invalidates either this whole cache, a single entry or a list of
entries in this cache
:param key:
the key of the entry to invalidate; if None, the entire cache
will be invalidated'
| def invalidate(self, key=None):
| def _invalidate(key):
try:
self._objects[key] = _invalid_object
except:
print 'error occurred while invalidating {0}'.format(key)
traceback.print_exc()
with self._write_lock:
if (key is None):
for k in self._objects.keys():
... |
'loads the value specified from the disk and stores it in the in-memory
cache
:param key:
the key to load from disk; if None, all entries in the cache
will be read from disk'
| def load(self, key=None):
| with self._write_lock:
if (key is None):
for entry in os.listdir(self.cache_path):
if os.path.isfile(entry):
entry_name = os.path.basename[entry]
try:
self._objects[entry_name] = self._read(entry_name)
... |
'an async version of load; does the loading in a new thread'
| def load_async(self, key=None):
| self._pool.apply_async(self.load, key)
|
'saves the cache entry specified to disk
:param key:
the entry to flush to disk; if None, all entries in the cache will
be written to disk'
| def save(self, key=None):
| if (not self._dirty):
return
with self._disk_lock:
with self._write_lock:
_objs = copy.deepcopy(self._objects)
self._dirty = False
if (key is None):
delete_keys = [k for k in _objs if (_objs[k] is _invalid_object)]
for k in delete_keys:
... |
'an async version of save; does the save in a new thread'
| def save_async(self, key=None):
| self._pool.apply_async(self.save, key)
|
'subclasses MUST override this method to return a key which identifies
this instance; this key MUST be able to be used as a dictionary key
the key is intended to be shared by multiple instances of the cache,
but only those which represent the same underlying data; for example,
the LocalCache uses the tex_root value as ... | def _get_inst_key(self, *args, **kwargs):
| raise NotImplemented
|
'gets the length of time an item should remain in the local cache
before being evicted
note that previous values are calculated and stored since this method
is used on every cache read'
| @classmethod
def _get_cache_life_span(cls):
| def __parse_life_span_string():
try:
return long(life_span_string)
except ValueError:
try:
(d, h, m, s) = TIME_RE.match(life_span_string).groups()
times = [(s, 1), (m, 60), (h, 3600), (d, 86400)]
return sum(((long((t[0] or 0)) *... |
'Create a new token converter from a string.'
| def __init__(self, tex):
| self.tex = tuple(_tokenize(tex))
self.pos = 0
self.lastoutput = 'x'
|
'Turn self into an iterator. It already is one, nothing to do.'
| def __iter__(self):
| return self
|
'Return token at offset n from current pos.'
| def __getitem__(self, n):
| p = (self.pos + n)
t = self.tex
return (t[p] if (p < len(t)) else None)
|
'Find and return another piece of converted output.'
| def __next__(self):
| if (self.pos >= len(self.tex)):
raise StopIteration
nextoutput = self.chunk()
if ((self.lastoutput[0] == '\\') and self.lastoutput[(-1)].isalpha() and nextoutput[0].isalpha()):
nextoutput = (' ' + nextoutput)
self.lastoutput = nextoutput
return nextoutput
|
'Grab another set of input tokens and convert them to an output string.'
| def chunk(self):
| for (delta, c) in self.candidates(0):
if (c in _l2u):
self.pos += delta
try:
return unichr(_l2u[c])
except NameError:
return chr(_l2u[c])
elif ((len(c) == 2) and (c[1] == 'i') and ((c[0], '\\i') in _l2u)):
self.pos += de... |
'Generate pairs delta,c where c is a token or tuple of tokens from tex
(after deleting extraneous brackets starting at pos) and delta
is the length of the tokens prior to bracket deletion.'
| def candidates(self, offset):
| t = self[offset]
if (t in _blacklist):
return
elif (t == '{'):
for (delta, c) in self.candidates((offset + 1)):
if (self[((offset + delta) + 1)] == '}'):
(yield ((delta + 2), c))
elif (t == '\\mbox'):
for (delta, c) in self.candidates((offset + 1)):
... |
'Handles the toggle to hide the labels'
| def __hide_labels(self):
| self.captions = (self.captions[0:self._offset] + self.__caption_secs)
index = self.captions.index(self.__hide_string)
self.captions[index] = self.__show_string
self.entries = self.__secs
self.show_quickpanel(index)
|
'Handles the toggle to show the labels'
| def __show_labels(self):
| self.captions = (self.captions[0:self._offset] + self.__caption_labels)
index = self.captions.index(self.__show_string)
self.captions[index] = self.__hide_string
self.entries = self.__labels
self.show_quickpanel(index)
|
'command to jump to the file at a specified line and column
if this raises a NotImplementedError, we will fallback to
invoking view_file
:params:
pdf_file - full path to the generated pdf
tex_file - full path to the tex file of the active view
line - indicates the line number in the tex file (1-based)
col - incidates t... | def forward_sync(self, pdf_file, tex_file, line, col, **kwargs):
| raise NotImplementedError()
|
'command to open a file
:params:
pdf_file - full path to the generated pdf'
| def view_file(self, pdf_file, **kwargs):
| raise NotImplementedError()
|
'return True to indicate that this plugin supports the keep_focus
setting or False (the default) to use the default refocus
implementation'
| def supports_keep_focus(self):
| return False
|
'return True to indicate that this plugin supports the reported
platform or False to indicate that it is not supported in the
current platform / environment'
| def supports_platform(self, platform):
| return True
|
'returns evince-related settings as a tuple
(python, sync_wait)'
| def _get_settings(self):
| linux_settings = get_setting('linux', {})
python = linux_settings.get('python')
if ((python is None) or (python == '')):
python = linux_settings.get('python2')
if ((python is None) or (python == '')):
if (self.PYTHON is not None):
python = self.PYTHON
else:
... |
'Function to substitute various values into a user-provided string
Returns a tuple consisting of the string with any substitutions made
and a boolean indicating if any substitutions were made
Provided Values:
$pdf_file | full path of PDF file
$pdf_file_name | name of the PDF file
$pdf_file_ext | ex... | def _replace_vars(self, s, pdf_file, tex_file=None, line='', col=''):
| if (not self.CONTAINS_VARIABLE.search(s)):
return (s, False)
sublime_binary = (get_sublime_exe() or '')
pdf_file_path = os.path.split(pdf_file)[0]
pdf_file_name = os.path.basename(pdf_file)
(pdf_file_base_name, pdf_file_ext) = os.path.splitext(pdf_file_name)
if (tex_file is None):
... |
'Completes brackets if auto_match is enabled; also implements the
"smart_bracket_auto_trigger" logic, which tries to complete the nearest
open bracket intelligently.
:param view:
the current view
:param edit:
the current edit
:param insert_char:
the character to try to automatch'
| def complete_auto_match(self, view, edit, insert_char):
| if sublime.load_settings('Preferences.sublime-settings').get('auto_match_enabled', True):
if insert_char:
self.insert_at_end(view, edit, self.get_match_char(insert_char))
if (insert_char in self.MATCH_CHARS):
new_regions = []
for sel in view.sel():
... |
'Intended to be called from a TextCommand to insert a specified
insert_char, close the nearest bracket, and remove any regions
specified
:param view:
the current view
:param edit:
the current edit
:param insert_char:
the character to insert and possibly automatch
:param remove_regions:
any regions to be removed from th... | def complete_brackets(self, view, edit, insert_char='', remove_regions=[]):
| self.insert_at_end(view, edit, insert_char)
self.complete_auto_match(view, edit, insert_char)
self.remove_regions(view, edit, remove_regions)
self.clear_bracket_cache()
|
'Determines if the nearest bracket that occurs before the given
selection is closed. If the bracket should be closed, returns the
closing bracket to use.
Note that this will not work if the arguments to the command span
multiple lines, but we generally don\'t support that anyway.
:param view:
the current view
:param se... | def get_closing_bracket(self, view, sel):
| candidates = None
if ((not hasattr(self, 'last_view')) or (self.last_view != view.id())):
self.last_view = view.id()
self.use_full_scan = get_setting('smart_bracket_scan_full_document', False)
candidates = self.candidates = {}
if (not self.use_full_scan):
candidates = {}
... |
'Clears the cache of brackets stored by get_closing_bracket
If get_closing_bracket is used, this method must be called at the end
or else subsequent calls to get_closing_brackets will not be updated
with a fresh view of the current buffer'
| def clear_bracket_cache(self):
| try:
del self.candidates
except:
pass
try:
del self.last_view
except:
pass
try:
del self.use_full_scan
except:
pass
|
'gets the common prefix (if any) from a list of locations
:param view:
the current view
:param locations:
either a list of points or a list of sublime.Regions'
| def get_common_prefix(self, view, locations):
| if ((type(locations[0]) is int) or (type(locations[0]) is long)):
locations = [getRegion(l, l) for l in locations]
old_prefix = None
for location in locations:
if location.empty():
word_region = getRegion(self.get_current_word(view, location).begin(), location.b)
pref... |
'get the common fancy prefix (if any) from a list of locations
see get_fancy_prefix for the definition of a fancy prefix
:param view:
the current view
:param locations:
either a list of points or a list of sublime.Regions'
| def get_common_fancy_prefix(self, view, locations):
| remove_regions = []
old_prefix = None
new_prefix = ''
for location in locations:
prefix_region = self.get_fancy_prefix(view, location)
if prefix_region.empty():
continue
new_prefix = view.substr(getRegion((prefix_region.begin() + 1), prefix_region.end()))
remo... |
'Gets the region containing the current word which contains the caret
or the given selection.
The current word is defined between the nearest non-word characters to
the left and to the right of the current selected location.
Non-word characters are defined by the WORD_SEPARATOR_RX.
:param view:
the current view
:param ... | def get_current_word(self, view, location):
| if isinstance(location, sublime.Region):
(start, end) = (location.begin(), location.end())
else:
start = end = location
start_line = view.line(start)
end_line = view.line(end)
line_prefix = view.substr(getRegion(start_line.begin(), start))[::(-1)]
line_suffix = view.substr(getReg... |
'Gets the prefix for the command assuming it takes a form like:
\cite_prefix
ef_prefix
These are also supported:
\cite_prefix{
ef_prefix{
The prefix is defined by everything *after* the underscore
:param view:
the current view
:param location:
either a point or a sublime.Region that defines the caret position
or curren... | def get_fancy_prefix(self, view, location):
| if isinstance(location, sublime.Region):
start = location.begin()
else:
start = location
start_line = view.line(start)
line_prefix = view.substr(getRegion(start_line.begin(), start))[::(-1)]
m = self.FANCY_PREFIX_RX.match(line_prefix)
if (not m):
return getRegion(start, s... |
'Inserts a string at the end of every current selection
:param view:
the current view
:param edit:
the current edit
:param value:
the string to insert'
| def insert_at_end(self, view, edit, value):
| if value:
new_regions = []
for sel in view.sel():
view.insert(edit, sel.end(), value)
if sel.empty():
new_start = new_end = (sel.end() + len(value))
else:
new_start = sel.begin()
new_end = (sel.end() + len(value))
... |
'Replaces the current word with the provided string in each selection
For the definition of word, see get_current_word()
:param view:
the current view
:param edit:
the current edit
:param value:
the string to replace the current word with'
| def replace_word(self, view, edit, value):
| new_regions = []
for sel in view.sel():
if sel.empty():
word_region = self.get_current_word(view, sel.end())
start_point = word_region.begin()
end_point = word_region.end()
else:
word_region = self.get_current_word(view, sel)
start_poin... |
'Removes all current selections and adds the specified selections
NB When calling this method, it is important that all current
selections be either replaced or simply included as-is. Otherwise,
these selections will be lost
:param view:
the current view
:param new_regions:
a list of sublime.Regions that should be sele... | def update_selections(self, view, new_regions):
| sel = view.sel()
sel.clear()
for region in new_regions:
sel.add(region)
|
'Converts a list of regions to a list of two-element tuples containing
the corresponding points
This is necessary to properly serialize a set of regions as an argument
to a Sublime command, since arguments MUST be serializable as JSON
objects
:param regions:
an iterable of sublime.Regions to convert to tuples'
| def regions_to_tuples(self, regions):
| if (type(regions) == sublime.Region):
return [(regions.a, regions.b)]
return [[r.a, r.b] for r in regions]
|
'Converts a list of 2-tuples to a list of corresponding regions
This is the opposite of regions_to_tuples and is intended to
deserialize regions serialized using that method
:param tuples:
an iterable of two-element tuples to convert to sublime.Regions'
| def tuples_to_regions(self, tuples):
| if (type(tuples) == tuple):
return [getRegion(tuples[0], tuples[1])]
return [getRegion(start, end) for (start, end) in tuples]
|
'Scores a selector on a view, returns True if the selectors is
scored for each selection.
:param view:
the current view
:param selector:
the selector, which should be scored'
| def score_selector(self, view, selector):
| return all((view.score_selector(sel.b, selector) for sel in view.sel()))
|
'Loads the FillAllHelper plugins'
| def _load_plugins(self):
| self.COMPLETION_TYPES = {}
for plugin in get_plugins_by_type(FillAllHelper):
name = _classname_to_internal_name(plugin.__name__)
if name.endswith('_fill_all_helper'):
name = name[:(-16)]
self.COMPLETION_TYPES[name] = plugin()
self.COMPLETION_TYPE_NAMES = list(self.COM... |
'Gets the list of plugin names'
| def get_completion_types(self):
| if (self.COMPLETION_TYPES is None):
self._load_plugins()
return self.COMPLETION_TYPE_NAMES
|
'supports query_context for all completion types
key is "lt_fill_all_{name}" where name is the short name of the
completion type, e.g. "lt_fill_all_cite", etc.'
| def on_query_context(self, view, key, operator, operand, match_all):
| if (not key.startswith('lt_fill_all_')):
return None
for sel in view.sel():
point = sel.b
if (not view.score_selector(point, 'text.tex.latex')):
return None
if (self.SUPPORTED_KEYS is None):
self.SUPPORTED_KEYS = dict((('lt_fill_all_{0}'.format(name), name) for na... |
'Provides the mechanisms to calculate the list of signals.'
| @abstractmethod
def calculate_signals(self, event):
| raise NotImplementedError('Should implement calculate_signals()')
|
'On creation, the Portfolio object contains no
positions and all values are "reset" to the initial
cash, with no PnL - realised or unrealised.
Note that realised_pnl is the running tally pnl from closed
positions (closed_pnl), as well as realised_pnl
from currently open positions.'
| def __init__(self, price_handler, cash):
| self.price_handler = price_handler
self.init_cash = cash
self.equity = cash
self.cur_cash = cash
self.positions = {}
self.closed_positions = []
self.realised_pnl = 0
|
'Updates the value of all positions that are currently open.
Value of closed positions is tallied as self.realised_pnl.'
| def _update_portfolio(self):
| self.unrealised_pnl = 0
self.equity = self.realised_pnl
self.equity += self.init_cash
for ticker in self.positions:
pt = self.positions[ticker]
if self.price_handler.istick():
(bid, ask) = self.price_handler.get_best_bid_ask(ticker)
else:
close_price = sel... |
'Adds a new Position object to the Portfolio. This
requires getting the best bid/ask price from the
price handler in order to calculate a reasonable
"market value".
Once the Position is added, the Portfolio values
are updated.'
| def _add_position(self, action, ticker, quantity, price, commission):
| if (ticker not in self.positions):
if self.price_handler.istick():
(bid, ask) = self.price_handler.get_best_bid_ask(ticker)
else:
close_price = self.price_handler.get_last_close(ticker)
bid = close_price
ask = close_price
position = Position(ac... |
'Modifies a current Position object to the Portfolio.
This requires getting the best bid/ask price from the
price handler in order to calculate a reasonable
"market value".
Once the Position is modified, the Portfolio values
are updated.'
| def _modify_position(self, action, ticker, quantity, price, commission):
| if (ticker in self.positions):
self.positions[ticker].transact_shares(action, quantity, price, commission)
if self.price_handler.istick():
(bid, ask) = self.price_handler.get_best_bid_ask(ticker)
else:
close_price = self.price_handler.get_last_close(ticker)
... |
'Handles any new position or modification to
a current position, by calling the respective
_add_position and _modify_position methods.
Hence, this single method will be called by the
PortfolioHandler to update the Portfolio itself.'
| def transact_position(self, action, ticker, quantity, price, commission):
| if (action == 'BOT'):
self.cur_cash -= ((quantity * price) + commission)
elif (action == 'SLD'):
self.cur_cash += ((quantity * price) - commission)
if (ticker not in self.positions):
self._add_position(action, ticker, quantity, price, commission)
else:
self._modify_positi... |
'Takes an OrderEvent and executes it, producing
a FillEvent that gets placed onto the events queue.
Parameters:
event - Contains an Event object with order information.'
| @abstractmethod
def execute_order(self, event):
| raise NotImplementedError('Should implement execute_order()')
|
'Initialises the handler, setting the event queue
as well as access to local pricing.
Parameters:
events_queue - The Queue of Event objects.'
| def __init__(self, events_queue, price_handler, compliance=None):
| self.events_queue = events_queue
self.price_handler = price_handler
self.compliance = compliance
|
'Calculate the Interactive Brokers commission for
a transaction. This is based on the US Fixed pricing,
the details of which can be found here:
https://www.interactivebrokers.co.uk/en/index.php?f=1590&p=stocks1'
| def calculate_ib_commission(self, quantity, fill_price):
| commission = min(((0.5 * fill_price) * quantity), max(1.0, (0.005 * quantity)))
return PriceParser.parse(commission)
|
'Converts OrderEvents into FillEvents "naively",
i.e. without any latency, slippage or fill ratio problems.
Parameters:
event - An Event object with order information.'
| def execute_order(self, event):
| if (event.type == EventType.ORDER):
timestamp = self.price_handler.get_last_timestamp(event.ticker)
ticker = event.ticker
action = event.action
quantity = event.quantity
if self.price_handler.istick():
(bid, ask) = self.price_handler.get_best_bid_ask(ticker)
... |
'Interface method for streaming the next SentimentEvent
object to the events queue.'
| def stream_next(self, stream_date=None):
| raise NotImplementedError('stream_next is not implemented in the base class!')
|
'Opens the CSV file containing the sentiment analysis
information for all represented stocks and places
it into a pandas DataFrame.'
| def _open_sentiment_csv(self):
| sentiment_path = os.path.join(self.csv_dir, self.filename)
sent_df = pd.read_csv(sentiment_path, parse_dates=True, header=0, index_col=0, names=('Date', 'Ticker', 'Sentiment'))
if (self.start_date is not None):
sent_df = sent_df[self.start_date.strftime('%Y-%m-%d'):]
if (self.end_date is not Non... |
'Stream the next set of ticker sentiment values into
SentimentEvent objects.'
| def stream_next(self, stream_date=None):
| if (stream_date is not None):
stream_date_str = stream_date.strftime('%Y-%m-%d')
date_df = self.sent_df.ix[stream_date_str:stream_date_str]
for row in date_df.iterrows():
sev = SentimentEvent(stream_date, row[1]['Ticker'], row[1]['Sentiment'])
self.events_queue.put(se... |
'Initialises the SuggestedOrder. The quantity defaults
to zero as the PortfolioHandler creates these objects
prior to any position sizing.
The PositionSizer object will "fill in" the correct
value prior to sending the SuggestedOrder to the
RiskManager.
Parameters:
ticker - The ticker symbol, e.g. \'GOOG\'.
action - \'B... | def __init__(self, ticker, action, quantity=0):
| self.ticker = ticker
self.action = action
self.quantity = quantity
|
'Initialises the TickEvent.
Parameters:
ticker - The ticker symbol, e.g. \'GOOG\'.
time - The timestamp of the tick
bid - The best bid price at the time of the tick.
ask - The best ask price at the time of the tick.'
| def __init__(self, ticker, time, bid, ask):
| self.type = EventType.TICK
self.ticker = ticker
self.time = time
self.bid = bid
self.ask = ask
|
'Initialises the BarEvent.
Parameters:
ticker - The ticker symbol, e.g. \'GOOG\'.
time - The timestamp of the bar
period - The time period covered by the bar in seconds
open_price - The unadjusted opening price of the bar
high_price - The unadjusted high price of the bar
low_price - The unadjusted low price of the bar
... | def __init__(self, ticker, time, period, open_price, high_price, low_price, close_price, volume, adj_close_price=None):
| self.type = EventType.BAR
self.ticker = ticker
self.time = time
self.period = period
self.open_price = open_price
self.high_price = high_price
self.low_price = low_price
self.close_price = close_price
self.volume = volume
self.adj_close_price = adj_close_price
self.period_rea... |
'Creates a human-readable period from the number
of seconds specified for \'period\'.
For instance, converts:
* 1 -> \'1sec\'
* 5 -> \'5secs\'
* 60 -> \'1min\'
* 300 -> \'5min\'
If no period is found in the lookup table, the human
readable period is simply passed through from period,
in seconds.'
| def _readable_period(self):
| lut = {1: '1sec', 5: '5sec', 10: '10sec', 15: '15sec', 30: '30sec', 60: '1min', 300: '5min', 600: '10min', 900: '15min', 1800: '30min', 3600: '1hr', 86400: '1day', 604800: '1wk'}
if (self.period in lut):
return lut[self.period]
else:
return ('%ssec' % str(self.period))
|
'Initialises the SignalEvent.
Parameters:
ticker - The ticker symbol, e.g. \'GOOG\'.
action - \'BOT\' (for long) or \'SLD\' (for short).
suggested_quantity - Optional positively valued integer
representing a suggested absolute quantity of units
of an asset to transact in, which is used by the
PositionSizer and RiskMana... | def __init__(self, ticker, action, suggested_quantity=None):
| self.type = EventType.SIGNAL
self.ticker = ticker
self.action = action
self.suggested_quantity = suggested_quantity
|
'Initialises the OrderEvent.
Parameters:
ticker - The ticker symbol, e.g. \'GOOG\'.
action - \'BOT\' (for long) or \'SLD\' (for short).
quantity - The quantity of shares to transact.'
| def __init__(self, ticker, action, quantity):
| self.type = EventType.ORDER
self.ticker = ticker
self.action = action
self.quantity = quantity
|
'Outputs the values within the OrderEvent.'
| def print_order(self):
| print(('Order: Ticker=%s, Action=%s, Quantity=%s' % (self.ticker, self.action, self.quantity)))
|
'Initialises the FillEvent object.
timestamp - The timestamp when the order was filled.
ticker - The ticker symbol, e.g. \'GOOG\'.
action - \'BOT\' (for long) or \'SLD\' (for short).
quantity - The filled quantity.
exchange - The exchange where the order was filled.
price - The price at which the trade was filled
commi... | def __init__(self, timestamp, ticker, action, quantity, exchange, price, commission):
| self.type = EventType.FILL
self.timestamp = timestamp
self.ticker = ticker
self.action = action
self.quantity = quantity
self.exchange = exchange
self.price = price
self.commission = commission
|
'Initialises the SentimentEvent.
Parameters:
timestamp - The timestamp when the sentiment was generated.
ticker - The ticker symbol, e.g. \'GOOG\'.
sentiment - A string, float or integer value of "sentiment",
e.g. "bullish", -1, 5.4, etc.'
| def __init__(self, timestamp, ticker, sentiment):
| self.type = EventType.SENTIMENT
self.timestamp = timestamp
self.ticker = ticker
self.sentiment = sentiment
|
'Set up configuration.'
| def setUp(self):
| self.config = settings.TEST
|
'Test generate_simulated_prices'
| def test_generate_simulated_prices(self):
| qstrader.scripts.generate_simulated_prices.run('', 'GOOG', 700, 42, 1.5, 0.02, 400, 100, 2014, 1, 3, config=self.config)
|
'This ExampleRiskManager object simply lets the
sized order through, creates the corresponding
OrderEvent object and adds it to a list.'
| def refine_orders(self, portfolio, sized_order):
| order_event = OrderEvent(sized_order.ticker, sized_order.action, sized_order.quantity)
return [order_event]
|
'Takes a FillEvent from an ExecutionHandler
and logs each of these.
Parameters:
fill - A FillEvent with information about the
trade that has just been executed.'
| @abstractmethod
def record_trade(self, fill):
| raise NotImplementedError('Should implement record_trade()')
|
'Wipe the existing trade log for the day, leaving only
the headers in an empty CSV.
It allows for multiple backtests to be run
in a simple way, but quite likely makes it unsuitable for
a production environment that requires strict record-keeping.'
| def __init__(self, config):
| self.config = config
today = datetime.datetime.utcnow().date()
self.csv_filename = (('tradelog_' + today.strftime('%Y-%m-%d')) + '.csv')
try:
fname = os.path.expanduser(os.path.join(config.OUTPUT_DIR, self.csv_filename))
os.remove(fname)
except (IOError, OSError):
print 'No ... |
'Append all details about the FillEvent to the CSV trade log.'
| def record_trade(self, fill):
| fname = os.path.expanduser(os.path.join(self.config.OUTPUT_DIR, self.csv_filename))
with open(fname, 'a') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([fill.timestamp, fill.ticker, fill.action, fill.quantity, fill.exchange, PriceParser.display(fill.price, 4), PriceParser.display(fill... |
'Set up the initial "account" of the Position to be
zero for most items, with the exception of the initial
purchase/sale.
Then calculate the initial values and finally update the
market value of the transaction.'
| def __init__(self, action, ticker, init_quantity, init_price, init_commission, bid, ask):
| self.action = action
self.ticker = ticker
self.quantity = init_quantity
self.init_price = init_price
self.init_commission = init_commission
self.realised_pnl = 0
self.unrealised_pnl = 0
self.buys = 0
self.sells = 0
self.avg_bot = 0
self.avg_sld = 0
self.total_bot = 0
... |
'Depending upon whether the action was a buy or sell ("BOT"
or "SLD") calculate the average bought cost, the total bought
cost, the average price and the cost basis.
Finally, calculate the net total with and without commission.'
| def _calculate_initial_value(self):
| if (self.action == 'BOT'):
self.buys = self.quantity
self.avg_bot = self.init_price
self.total_bot = (self.buys * self.avg_bot)
self.avg_price = (((self.init_price * self.quantity) + self.init_commission) // self.quantity)
self.cost_basis = (self.quantity * self.avg_price)
... |
'The market value is tricky to calculate as we only have
access to the top of the order book through Interactive
Brokers, which means that the true redemption price is
unknown until executed.
However, it can be estimated via the mid-price of the
bid-ask spread. Once the market value is calculated it
allows calculation ... | def update_market_value(self, bid, ask):
| midpoint = ((bid + ask) // 2)
self.market_value = ((self.quantity * midpoint) * sign(self.net))
self.unrealised_pnl = (self.market_value - self.cost_basis)
|
'Calculates the adjustments to the Position that occur
once new shares are bought and sold.
Takes care to update the average bought/sold, total
bought/sold, the cost basis and PnL calculations,
as carried out through Interactive Brokers TWS.'
| def transact_shares(self, action, quantity, price, commission):
| self.total_commission += commission
if (action == 'BOT'):
self.avg_bot = (((self.avg_bot * self.buys) + (price * quantity)) // (self.buys + quantity))
if (self.action != 'SLD'):
self.avg_price = ((((self.avg_price * self.buys) + (price * quantity)) + commission) // (self.buys + quant... |
'Update all the statistics according to values of the portfolio
and open positions. This should be called from within the
event loop.'
| @abstractmethod
def update(self):
| raise NotImplementedError('Should implement update()')
|
'Return a dict containing all statistics.'
| @abstractmethod
def get_results(self):
| raise NotImplementedError('Should implement get_results()')
|
'Plot all statistics collected up until \'now\''
| @abstractmethod
def plot_results(self):
| raise NotImplementedError('Should implement plot_results()')
|
'Save statistics results to filename'
| @abstractmethod
def save(self, filename):
| raise NotImplementedError('Should implement save()')
|
'Takes in a portfolio handler.'
| def __init__(self, config, portfolio_handler, title=None, benchmark=None, periods=252, rolling_sharpe=False):
| self.config = config
self.portfolio_handler = portfolio_handler
self.price_handler = portfolio_handler.price_handler
self.title = '\n'.join(title)
self.benchmark = benchmark
self.periods = periods
self.rolling_sharpe = rolling_sharpe
self.equity = {}
self.equity_benchmark = {}
se... |
'Update equity curve and benchmark equity curve that must be tracked
over time.'
| def update(self, timestamp, portfolio_handler):
| self.equity[timestamp] = PriceParser.display(self.portfolio_handler.portfolio.equity)
if (self.benchmark is not None):
self.equity_benchmark[timestamp] = PriceParser.display(self.price_handler.get_last_close(self.benchmark))
|
'Return a dict with all important results & stats.'
| def get_results(self):
| equity_s = pd.Series(self.equity).sort_index()
returns_s = equity_s.pct_change().fillna(0.0)
rolling = returns_s.rolling(window=self.periods)
rolling_sharpe_s = (np.sqrt(self.periods) * (rolling.mean() / rolling.std()))
cum_returns_s = np.exp(np.log((1 + returns_s)).cumsum())
(dd_s, max_dd, dd_d... |
'Retrieve the list of closed Positions objects from the portfolio
and reformat into a pandas dataframe to be returned'
| def _get_positions(self):
| def x(p):
return PriceParser.display(p)
pos = self.portfolio_handler.portfolio.closed_positions
a = []
for p in pos:
a.append(p.__dict__)
if (len(a) == 0):
return None
else:
df = pd.DataFrame(a)
df['avg_bot'] = df['avg_bot'].apply(x)
df['avg_price'... |
'Plots cumulative rolling returns versus some benchmark.'
| def _plot_equity(self, stats, ax=None, **kwargs):
| def format_two_dec(x, pos):
return ('%.2f' % x)
equity = stats['cum_returns']
if (ax is None):
ax = plt.gca()
y_axis_formatter = FuncFormatter(format_two_dec)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
ax.xaxis.set_tick_params(reset=True)
ax.yaxis.grid(line... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.