repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
hyperledger/indy-plenum
plenum/server/replica.py
Replica.validateCommit
def validateCommit(self, commit: Commit, sender: str) -> bool: """ Return whether the COMMIT specified is valid. :param commit: the COMMIT to validate :return: True if `request` is valid, False otherwise """ key = (commit.viewNo, commit.ppSeqNo) if not self.has_prepared(key): self.enqueue_commit(commit, sender) return False if self.commits.hasCommitFrom(commit, sender): raise SuspiciousNode(sender, Suspicions.DUPLICATE_CM_SENT, commit) # BLS multi-sig: pre_prepare = self.getPrePrepare(commit.viewNo, commit.ppSeqNo) why_not = self._bls_bft_replica.validate_commit(commit, sender, pre_prepare) if why_not == BlsBftReplica.CM_BLS_SIG_WRONG: self.logger.warning("{} discard Commit message from " "{}:{}".format(self, sender, commit)) raise SuspiciousNode(sender, Suspicions.CM_BLS_SIG_WRONG, commit) elif why_not is not None: self.logger.warning("Unknown error code returned for bls commit " "validation {}".format(why_not)) return True
python
def validateCommit(self, commit: Commit, sender: str) -> bool: """ Return whether the COMMIT specified is valid. :param commit: the COMMIT to validate :return: True if `request` is valid, False otherwise """ key = (commit.viewNo, commit.ppSeqNo) if not self.has_prepared(key): self.enqueue_commit(commit, sender) return False if self.commits.hasCommitFrom(commit, sender): raise SuspiciousNode(sender, Suspicions.DUPLICATE_CM_SENT, commit) # BLS multi-sig: pre_prepare = self.getPrePrepare(commit.viewNo, commit.ppSeqNo) why_not = self._bls_bft_replica.validate_commit(commit, sender, pre_prepare) if why_not == BlsBftReplica.CM_BLS_SIG_WRONG: self.logger.warning("{} discard Commit message from " "{}:{}".format(self, sender, commit)) raise SuspiciousNode(sender, Suspicions.CM_BLS_SIG_WRONG, commit) elif why_not is not None: self.logger.warning("Unknown error code returned for bls commit " "validation {}".format(why_not)) return True
[ "def", "validateCommit", "(", "self", ",", "commit", ":", "Commit", ",", "sender", ":", "str", ")", "->", "bool", ":", "key", "=", "(", "commit", ".", "viewNo", ",", "commit", ".", "ppSeqNo", ")", "if", "not", "self", ".", "has_prepared", "(", "key",...
Return whether the COMMIT specified is valid. :param commit: the COMMIT to validate :return: True if `request` is valid, False otherwise
[ "Return", "whether", "the", "COMMIT", "specified", "is", "valid", "." ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L1761-L1790
train
229,200
hyperledger/indy-plenum
plenum/server/replica.py
Replica.addToCommits
def addToCommits(self, commit: Commit, sender: str): """ Add the specified COMMIT to this replica's list of received commit requests. :param commit: the COMMIT to add to the list :param sender: the name of the node that sent the COMMIT """ # BLS multi-sig: self._bls_bft_replica.process_commit(commit, sender) self.commits.addVote(commit, sender) self.tryOrder(commit)
python
def addToCommits(self, commit: Commit, sender: str): """ Add the specified COMMIT to this replica's list of received commit requests. :param commit: the COMMIT to add to the list :param sender: the name of the node that sent the COMMIT """ # BLS multi-sig: self._bls_bft_replica.process_commit(commit, sender) self.commits.addVote(commit, sender) self.tryOrder(commit)
[ "def", "addToCommits", "(", "self", ",", "commit", ":", "Commit", ",", "sender", ":", "str", ")", ":", "# BLS multi-sig:", "self", ".", "_bls_bft_replica", ".", "process_commit", "(", "commit", ",", "sender", ")", "self", ".", "commits", ".", "addVote", "(...
Add the specified COMMIT to this replica's list of received commit requests. :param commit: the COMMIT to add to the list :param sender: the name of the node that sent the COMMIT
[ "Add", "the", "specified", "COMMIT", "to", "this", "replica", "s", "list", "of", "received", "commit", "requests", "." ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L1792-L1804
train
229,201
hyperledger/indy-plenum
plenum/server/replica.py
Replica.canOrder
def canOrder(self, commit: Commit) -> Tuple[bool, Optional[str]]: """ Return whether the specified commitRequest can be returned to the node. Decision criteria: - If have got just n-f Commit requests then return request to node - If less than n-f of commit requests then probably don't have consensus on the request; don't return request to node - If more than n-f then already returned to node; don't return request to node :param commit: the COMMIT """ quorum = self.quorums.commit.value if not self.commits.hasQuorum(commit, quorum): return False, "no quorum ({}): {} commits where f is {}". \ format(quorum, commit, self.f) key = (commit.viewNo, commit.ppSeqNo) if self.has_already_ordered(*key): return False, "already ordered" if commit.ppSeqNo > 1 and not self.all_prev_ordered(commit): viewNo, ppSeqNo = commit.viewNo, commit.ppSeqNo if viewNo not in self.stashed_out_of_order_commits: self.stashed_out_of_order_commits[viewNo] = {} self.stashed_out_of_order_commits[viewNo][ppSeqNo] = commit self.startRepeating(self.process_stashed_out_of_order_commits, self.config.PROCESS_STASHED_OUT_OF_ORDER_COMMITS_INTERVAL) return False, "stashing {} since out of order". \ format(commit) return True, None
python
def canOrder(self, commit: Commit) -> Tuple[bool, Optional[str]]: """ Return whether the specified commitRequest can be returned to the node. Decision criteria: - If have got just n-f Commit requests then return request to node - If less than n-f of commit requests then probably don't have consensus on the request; don't return request to node - If more than n-f then already returned to node; don't return request to node :param commit: the COMMIT """ quorum = self.quorums.commit.value if not self.commits.hasQuorum(commit, quorum): return False, "no quorum ({}): {} commits where f is {}". \ format(quorum, commit, self.f) key = (commit.viewNo, commit.ppSeqNo) if self.has_already_ordered(*key): return False, "already ordered" if commit.ppSeqNo > 1 and not self.all_prev_ordered(commit): viewNo, ppSeqNo = commit.viewNo, commit.ppSeqNo if viewNo not in self.stashed_out_of_order_commits: self.stashed_out_of_order_commits[viewNo] = {} self.stashed_out_of_order_commits[viewNo][ppSeqNo] = commit self.startRepeating(self.process_stashed_out_of_order_commits, self.config.PROCESS_STASHED_OUT_OF_ORDER_COMMITS_INTERVAL) return False, "stashing {} since out of order". \ format(commit) return True, None
[ "def", "canOrder", "(", "self", ",", "commit", ":", "Commit", ")", "->", "Tuple", "[", "bool", ",", "Optional", "[", "str", "]", "]", ":", "quorum", "=", "self", ".", "quorums", ".", "commit", ".", "value", "if", "not", "self", ".", "commits", ".",...
Return whether the specified commitRequest can be returned to the node. Decision criteria: - If have got just n-f Commit requests then return request to node - If less than n-f of commit requests then probably don't have consensus on the request; don't return request to node - If more than n-f then already returned to node; don't return request to node :param commit: the COMMIT
[ "Return", "whether", "the", "specified", "commitRequest", "can", "be", "returned", "to", "the", "node", "." ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L1806-L1839
train
229,202
hyperledger/indy-plenum
plenum/server/replica.py
Replica.all_prev_ordered
def all_prev_ordered(self, commit: Commit): """ Return True if all previous COMMITs have been ordered """ # TODO: This method does a lot of work, choose correct data # structures to make it efficient. viewNo, ppSeqNo = commit.viewNo, commit.ppSeqNo if self.last_ordered_3pc == (viewNo, ppSeqNo - 1): # Last ordered was in same view as this COMMIT return True # if some PREPAREs/COMMITs were completely missed in the same view toCheck = set() toCheck.update(set(self.sentPrePrepares.keys())) toCheck.update(set(self.prePrepares.keys())) toCheck.update(set(self.prepares.keys())) toCheck.update(set(self.commits.keys())) for (v, p) in toCheck: if v < viewNo and (v, p) not in self.ordered: # Have commits from previous view that are unordered. return False if v == viewNo and p < ppSeqNo and (v, p) not in self.ordered: # If unordered commits are found with lower ppSeqNo then this # cannot be ordered. return False return True
python
def all_prev_ordered(self, commit: Commit): """ Return True if all previous COMMITs have been ordered """ # TODO: This method does a lot of work, choose correct data # structures to make it efficient. viewNo, ppSeqNo = commit.viewNo, commit.ppSeqNo if self.last_ordered_3pc == (viewNo, ppSeqNo - 1): # Last ordered was in same view as this COMMIT return True # if some PREPAREs/COMMITs were completely missed in the same view toCheck = set() toCheck.update(set(self.sentPrePrepares.keys())) toCheck.update(set(self.prePrepares.keys())) toCheck.update(set(self.prepares.keys())) toCheck.update(set(self.commits.keys())) for (v, p) in toCheck: if v < viewNo and (v, p) not in self.ordered: # Have commits from previous view that are unordered. return False if v == viewNo and p < ppSeqNo and (v, p) not in self.ordered: # If unordered commits are found with lower ppSeqNo then this # cannot be ordered. return False return True
[ "def", "all_prev_ordered", "(", "self", ",", "commit", ":", "Commit", ")", ":", "# TODO: This method does a lot of work, choose correct data", "# structures to make it efficient.", "viewNo", ",", "ppSeqNo", "=", "commit", ".", "viewNo", ",", "commit", ".", "ppSeqNo", "i...
Return True if all previous COMMITs have been ordered
[ "Return", "True", "if", "all", "previous", "COMMITs", "have", "been", "ordered" ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L1841-L1869
train
229,203
hyperledger/indy-plenum
plenum/server/replica.py
Replica.process_checkpoint
def process_checkpoint(self, msg: Checkpoint, sender: str) -> bool: """ Process checkpoint messages :return: whether processed (True) or stashed (False) """ self.logger.info('{} processing checkpoint {} from {}'.format(self, msg, sender)) result, reason = self.validator.validate_checkpoint_msg(msg) if result == DISCARD: self.discard(msg, "{} discard message {} from {} " "with the reason: {}".format(self, msg, sender, reason), self.logger.trace) elif result == PROCESS: self._do_process_checkpoint(msg, sender) else: self.logger.debug("{} stashing checkpoint message {} with " "the reason: {}".format(self, msg, reason)) self.stasher.stash((msg, sender), result) return False return True
python
def process_checkpoint(self, msg: Checkpoint, sender: str) -> bool: """ Process checkpoint messages :return: whether processed (True) or stashed (False) """ self.logger.info('{} processing checkpoint {} from {}'.format(self, msg, sender)) result, reason = self.validator.validate_checkpoint_msg(msg) if result == DISCARD: self.discard(msg, "{} discard message {} from {} " "with the reason: {}".format(self, msg, sender, reason), self.logger.trace) elif result == PROCESS: self._do_process_checkpoint(msg, sender) else: self.logger.debug("{} stashing checkpoint message {} with " "the reason: {}".format(self, msg, reason)) self.stasher.stash((msg, sender), result) return False return True
[ "def", "process_checkpoint", "(", "self", ",", "msg", ":", "Checkpoint", ",", "sender", ":", "str", ")", "->", "bool", ":", "self", ".", "logger", ".", "info", "(", "'{} processing checkpoint {} from {}'", ".", "format", "(", "self", ",", "msg", ",", "send...
Process checkpoint messages :return: whether processed (True) or stashed (False)
[ "Process", "checkpoint", "messages" ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L2050-L2069
train
229,204
hyperledger/indy-plenum
plenum/server/replica.py
Replica._process_stashed_pre_prepare_for_time_if_possible
def _process_stashed_pre_prepare_for_time_if_possible( self, key: Tuple[int, int]): """ Check if any PRE-PREPAREs that were stashed since their time was not acceptable, can now be accepted since enough PREPAREs are received """ self.logger.debug('{} going to process stashed PRE-PREPAREs with ' 'incorrect times'.format(self)) q = self.quorums.f if len(self.preparesWaitingForPrePrepare[key]) > q: times = [pr.ppTime for (pr, _) in self.preparesWaitingForPrePrepare[key]] most_common_time, freq = mostCommonElement(times) if self.quorums.timestamp.is_reached(freq): self.logger.debug('{} found sufficient PREPAREs for the ' 'PRE-PREPARE{}'.format(self, key)) stashed_pp = self.pre_prepares_stashed_for_incorrect_time pp, sender, done = stashed_pp[key] if done: self.logger.debug('{} already processed PRE-PREPARE{}'.format(self, key)) return True # True is set since that will indicate to `is_pre_prepare_time_acceptable` # that sufficient PREPAREs are received stashed_pp[key] = (pp, sender, True) self.process_three_phase_msg(pp, sender) return True return False
python
def _process_stashed_pre_prepare_for_time_if_possible( self, key: Tuple[int, int]): """ Check if any PRE-PREPAREs that were stashed since their time was not acceptable, can now be accepted since enough PREPAREs are received """ self.logger.debug('{} going to process stashed PRE-PREPAREs with ' 'incorrect times'.format(self)) q = self.quorums.f if len(self.preparesWaitingForPrePrepare[key]) > q: times = [pr.ppTime for (pr, _) in self.preparesWaitingForPrePrepare[key]] most_common_time, freq = mostCommonElement(times) if self.quorums.timestamp.is_reached(freq): self.logger.debug('{} found sufficient PREPAREs for the ' 'PRE-PREPARE{}'.format(self, key)) stashed_pp = self.pre_prepares_stashed_for_incorrect_time pp, sender, done = stashed_pp[key] if done: self.logger.debug('{} already processed PRE-PREPARE{}'.format(self, key)) return True # True is set since that will indicate to `is_pre_prepare_time_acceptable` # that sufficient PREPAREs are received stashed_pp[key] = (pp, sender, True) self.process_three_phase_msg(pp, sender) return True return False
[ "def", "_process_stashed_pre_prepare_for_time_if_possible", "(", "self", ",", "key", ":", "Tuple", "[", "int", ",", "int", "]", ")", ":", "self", ".", "logger", ".", "debug", "(", "'{} going to process stashed PRE-PREPAREs with '", "'incorrect times'", ".", "format", ...
Check if any PRE-PREPAREs that were stashed since their time was not acceptable, can now be accepted since enough PREPAREs are received
[ "Check", "if", "any", "PRE", "-", "PREPAREs", "that", "were", "stashed", "since", "their", "time", "was", "not", "acceptable", "can", "now", "be", "accepted", "since", "enough", "PREPAREs", "are", "received" ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L2742-L2768
train
229,205
hyperledger/indy-plenum
plenum/server/replica.py
Replica._remove_till_caught_up_3pc
def _remove_till_caught_up_3pc(self, last_caught_up_3PC): """ Remove any 3 phase messages till the last ordered key and also remove any corresponding request keys """ outdated_pre_prepares = {} for key, pp in self.prePrepares.items(): if compare_3PC_keys(key, last_caught_up_3PC) >= 0: outdated_pre_prepares[key] = pp for key, pp in self.sentPrePrepares.items(): if compare_3PC_keys(key, last_caught_up_3PC) >= 0: outdated_pre_prepares[key] = pp self.logger.trace('{} going to remove messages for {} 3PC keys'.format( self, len(outdated_pre_prepares))) for key, pp in outdated_pre_prepares.items(): self.batches.pop(key, None) self.sentPrePrepares.pop(key, None) self.prePrepares.pop(key, None) self.prepares.pop(key, None) self.commits.pop(key, None) self._discard_ordered_req_keys(pp)
python
def _remove_till_caught_up_3pc(self, last_caught_up_3PC): """ Remove any 3 phase messages till the last ordered key and also remove any corresponding request keys """ outdated_pre_prepares = {} for key, pp in self.prePrepares.items(): if compare_3PC_keys(key, last_caught_up_3PC) >= 0: outdated_pre_prepares[key] = pp for key, pp in self.sentPrePrepares.items(): if compare_3PC_keys(key, last_caught_up_3PC) >= 0: outdated_pre_prepares[key] = pp self.logger.trace('{} going to remove messages for {} 3PC keys'.format( self, len(outdated_pre_prepares))) for key, pp in outdated_pre_prepares.items(): self.batches.pop(key, None) self.sentPrePrepares.pop(key, None) self.prePrepares.pop(key, None) self.prepares.pop(key, None) self.commits.pop(key, None) self._discard_ordered_req_keys(pp)
[ "def", "_remove_till_caught_up_3pc", "(", "self", ",", "last_caught_up_3PC", ")", ":", "outdated_pre_prepares", "=", "{", "}", "for", "key", ",", "pp", "in", "self", ".", "prePrepares", ".", "items", "(", ")", ":", "if", "compare_3PC_keys", "(", "key", ",", ...
Remove any 3 phase messages till the last ordered key and also remove any corresponding request keys
[ "Remove", "any", "3", "phase", "messages", "till", "the", "last", "ordered", "key", "and", "also", "remove", "any", "corresponding", "request", "keys" ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L2843-L2865
train
229,206
hyperledger/indy-plenum
plenum/server/replica.py
Replica._remove_ordered_from_queue
def _remove_ordered_from_queue(self, last_caught_up_3PC=None): """ Remove any Ordered that the replica might be sending to node which is less than or equal to `last_caught_up_3PC` if `last_caught_up_3PC` is passed else remove all ordered, needed in catchup """ to_remove = [] for i, msg in enumerate(self.outBox): if isinstance(msg, Ordered) and \ (not last_caught_up_3PC or compare_3PC_keys((msg.viewNo, msg.ppSeqNo), last_caught_up_3PC) >= 0): to_remove.append(i) self.logger.trace('{} going to remove {} Ordered messages from outbox'.format(self, len(to_remove))) # Removing Ordered from queue but returning `Ordered` in order that # they should be processed. removed = [] for i in reversed(to_remove): removed.insert(0, self.outBox[i]) del self.outBox[i] return removed
python
def _remove_ordered_from_queue(self, last_caught_up_3PC=None): """ Remove any Ordered that the replica might be sending to node which is less than or equal to `last_caught_up_3PC` if `last_caught_up_3PC` is passed else remove all ordered, needed in catchup """ to_remove = [] for i, msg in enumerate(self.outBox): if isinstance(msg, Ordered) and \ (not last_caught_up_3PC or compare_3PC_keys((msg.viewNo, msg.ppSeqNo), last_caught_up_3PC) >= 0): to_remove.append(i) self.logger.trace('{} going to remove {} Ordered messages from outbox'.format(self, len(to_remove))) # Removing Ordered from queue but returning `Ordered` in order that # they should be processed. removed = [] for i in reversed(to_remove): removed.insert(0, self.outBox[i]) del self.outBox[i] return removed
[ "def", "_remove_ordered_from_queue", "(", "self", ",", "last_caught_up_3PC", "=", "None", ")", ":", "to_remove", "=", "[", "]", "for", "i", ",", "msg", "in", "enumerate", "(", "self", ".", "outBox", ")", ":", "if", "isinstance", "(", "msg", ",", "Ordered...
Remove any Ordered that the replica might be sending to node which is less than or equal to `last_caught_up_3PC` if `last_caught_up_3PC` is passed else remove all ordered, needed in catchup
[ "Remove", "any", "Ordered", "that", "the", "replica", "might", "be", "sending", "to", "node", "which", "is", "less", "than", "or", "equal", "to", "last_caught_up_3PC", "if", "last_caught_up_3PC", "is", "passed", "else", "remove", "all", "ordered", "needed", "i...
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L2867-L2888
train
229,207
hyperledger/indy-plenum
plenum/server/replica.py
Replica._remove_stashed_checkpoints
def _remove_stashed_checkpoints(self, till_3pc_key=None): """ Remove stashed received checkpoints up to `till_3pc_key` if provided, otherwise remove all stashed received checkpoints """ if till_3pc_key is None: self.stashedRecvdCheckpoints.clear() self.logger.info('{} removing all stashed checkpoints'.format(self)) return for view_no in list(self.stashedRecvdCheckpoints.keys()): if view_no < till_3pc_key[0]: self.logger.info('{} removing stashed checkpoints for view {}'.format(self, view_no)) del self.stashedRecvdCheckpoints[view_no] elif view_no == till_3pc_key[0]: for (s, e) in list(self.stashedRecvdCheckpoints[view_no].keys()): if e <= till_3pc_key[1]: self.logger.info('{} removing stashed checkpoints: ' 'viewNo={}, seqNoStart={}, seqNoEnd={}'. format(self, view_no, s, e)) del self.stashedRecvdCheckpoints[view_no][(s, e)] if len(self.stashedRecvdCheckpoints[view_no]) == 0: del self.stashedRecvdCheckpoints[view_no]
python
def _remove_stashed_checkpoints(self, till_3pc_key=None): """ Remove stashed received checkpoints up to `till_3pc_key` if provided, otherwise remove all stashed received checkpoints """ if till_3pc_key is None: self.stashedRecvdCheckpoints.clear() self.logger.info('{} removing all stashed checkpoints'.format(self)) return for view_no in list(self.stashedRecvdCheckpoints.keys()): if view_no < till_3pc_key[0]: self.logger.info('{} removing stashed checkpoints for view {}'.format(self, view_no)) del self.stashedRecvdCheckpoints[view_no] elif view_no == till_3pc_key[0]: for (s, e) in list(self.stashedRecvdCheckpoints[view_no].keys()): if e <= till_3pc_key[1]: self.logger.info('{} removing stashed checkpoints: ' 'viewNo={}, seqNoStart={}, seqNoEnd={}'. format(self, view_no, s, e)) del self.stashedRecvdCheckpoints[view_no][(s, e)] if len(self.stashedRecvdCheckpoints[view_no]) == 0: del self.stashedRecvdCheckpoints[view_no]
[ "def", "_remove_stashed_checkpoints", "(", "self", ",", "till_3pc_key", "=", "None", ")", ":", "if", "till_3pc_key", "is", "None", ":", "self", ".", "stashedRecvdCheckpoints", ".", "clear", "(", ")", "self", ".", "logger", ".", "info", "(", "'{} removing all s...
Remove stashed received checkpoints up to `till_3pc_key` if provided, otherwise remove all stashed received checkpoints
[ "Remove", "stashed", "received", "checkpoints", "up", "to", "till_3pc_key", "if", "provided", "otherwise", "remove", "all", "stashed", "received", "checkpoints" ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L2890-L2914
train
229,208
hyperledger/indy-plenum
stp_core/network/util.py
checkPortAvailable
def checkPortAvailable(ha): """Checks whether the given port is available""" # Not sure why OS would allow binding to one type and not other. # Checking for port available for TCP and UDP. sockTypes = (socket.SOCK_DGRAM, socket.SOCK_STREAM) for typ in sockTypes: sock = socket.socket(socket.AF_INET, typ) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(ha) if typ == socket.SOCK_STREAM: l_onoff = 1 l_linger = 0 sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', l_onoff, l_linger)) except OSError as exc: if exc.errno in [ errno.EADDRINUSE, errno.EADDRNOTAVAIL, WS_SOCKET_BIND_ERROR_ALREADY_IN_USE, WS_SOCKET_BIND_ERROR_NOT_AVAILABLE ]: raise PortNotAvailable(ha) else: raise exc finally: sock.close()
python
def checkPortAvailable(ha): """Checks whether the given port is available""" # Not sure why OS would allow binding to one type and not other. # Checking for port available for TCP and UDP. sockTypes = (socket.SOCK_DGRAM, socket.SOCK_STREAM) for typ in sockTypes: sock = socket.socket(socket.AF_INET, typ) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(ha) if typ == socket.SOCK_STREAM: l_onoff = 1 l_linger = 0 sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', l_onoff, l_linger)) except OSError as exc: if exc.errno in [ errno.EADDRINUSE, errno.EADDRNOTAVAIL, WS_SOCKET_BIND_ERROR_ALREADY_IN_USE, WS_SOCKET_BIND_ERROR_NOT_AVAILABLE ]: raise PortNotAvailable(ha) else: raise exc finally: sock.close()
[ "def", "checkPortAvailable", "(", "ha", ")", ":", "# Not sure why OS would allow binding to one type and not other.", "# Checking for port available for TCP and UDP.", "sockTypes", "=", "(", "socket", ".", "SOCK_DGRAM", ",", "socket", ".", "SOCK_STREAM", ")", "for", "typ", ...
Checks whether the given port is available
[ "Checks", "whether", "the", "given", "port", "is", "available" ]
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/util.py#L19-L44
train
229,209
hyperledger/indy-plenum
stp_core/network/util.py
evenCompare
def evenCompare(a: str, b: str) -> bool: """ A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false """ ab = a.encode('utf-8') bb = b.encode('utf-8') ac = crypto_hash_sha256(ab) bc = crypto_hash_sha256(bb) return ac < bc
python
def evenCompare(a: str, b: str) -> bool: """ A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false """ ab = a.encode('utf-8') bb = b.encode('utf-8') ac = crypto_hash_sha256(ab) bc = crypto_hash_sha256(bb) return ac < bc
[ "def", "evenCompare", "(", "a", ":", "str", ",", "b", ":", "str", ")", "->", "bool", ":", "ab", "=", "a", ".", "encode", "(", "'utf-8'", ")", "bb", "=", "b", ".", "encode", "(", "'utf-8'", ")", "ac", "=", "crypto_hash_sha256", "(", "ab", ")", "...
A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false
[ "A", "deterministic", "but", "more", "evenly", "distributed", "comparator", "than", "simple", "alphabetical", ".", "Useful", "when", "comparing", "consecutive", "strings", "and", "an", "even", "distribution", "is", "needed", ".", "Provides", "an", "even", "chance"...
dcd144e238af7f17a869ffc9412f13dc488b7020
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/stp_core/network/util.py#L47-L57
train
229,210
kylejusticemagnuson/pyti
pyti/keltner_bands.py
center_band
def center_band(close_data, high_data, low_data, period): """ Center Band. Formula: CB = SMA(TP) """ tp = typical_price(close_data, high_data, low_data) cb = sma(tp, period) return cb
python
def center_band(close_data, high_data, low_data, period): """ Center Band. Formula: CB = SMA(TP) """ tp = typical_price(close_data, high_data, low_data) cb = sma(tp, period) return cb
[ "def", "center_band", "(", "close_data", ",", "high_data", ",", "low_data", ",", "period", ")", ":", "tp", "=", "typical_price", "(", "close_data", ",", "high_data", ",", "low_data", ")", "cb", "=", "sma", "(", "tp", ",", "period", ")", "return", "cb" ]
Center Band. Formula: CB = SMA(TP)
[ "Center", "Band", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/keltner_bands.py#L23-L32
train
229,211
kylejusticemagnuson/pyti
pyti/simple_moving_average.py
simple_moving_average
def simple_moving_average(data, period): """ Simple Moving Average. Formula: SUM(data / N) """ catch_errors.check_for_period_error(data, period) # Mean of Empty Slice RuntimeWarning doesn't affect output so it is # supressed with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) sma = [np.mean(data[idx-(period-1):idx+1]) for idx in range(0, len(data))] sma = fill_for_noncomputable_vals(data, sma) return sma
python
def simple_moving_average(data, period): """ Simple Moving Average. Formula: SUM(data / N) """ catch_errors.check_for_period_error(data, period) # Mean of Empty Slice RuntimeWarning doesn't affect output so it is # supressed with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) sma = [np.mean(data[idx-(period-1):idx+1]) for idx in range(0, len(data))] sma = fill_for_noncomputable_vals(data, sma) return sma
[ "def", "simple_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "# Mean of Empty Slice RuntimeWarning doesn't affect output so it is", "# supressed", "with", "warnings", ".", "catch_warnin...
Simple Moving Average. Formula: SUM(data / N)
[ "Simple", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/simple_moving_average.py#L9-L23
train
229,212
kylejusticemagnuson/pyti
pyti/average_true_range_percent.py
average_true_range_percent
def average_true_range_percent(close_data, period): """ Average True Range Percent. Formula: ATRP = (ATR / CLOSE) * 100 """ catch_errors.check_for_period_error(close_data, period) atrp = (atr(close_data, period) / np.array(close_data)) * 100 return atrp
python
def average_true_range_percent(close_data, period): """ Average True Range Percent. Formula: ATRP = (ATR / CLOSE) * 100 """ catch_errors.check_for_period_error(close_data, period) atrp = (atr(close_data, period) / np.array(close_data)) * 100 return atrp
[ "def", "average_true_range_percent", "(", "close_data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "close_data", ",", "period", ")", "atrp", "=", "(", "atr", "(", "close_data", ",", "period", ")", "/", "np", ".", "array", "(...
Average True Range Percent. Formula: ATRP = (ATR / CLOSE) * 100
[ "Average", "True", "Range", "Percent", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/average_true_range_percent.py#L9-L18
train
229,213
kylejusticemagnuson/pyti
pyti/on_balance_volume.py
on_balance_volume
def on_balance_volume(close_data, volume): """ On Balance Volume. Formula: start = 1 if CLOSEt > CLOSEt-1 obv = obvt-1 + volumet elif CLOSEt < CLOSEt-1 obv = obvt-1 - volumet elif CLOSEt == CLOSTt-1 obv = obvt-1 """ catch_errors.check_for_input_len_diff(close_data, volume) obv = np.zeros(len(volume)) obv[0] = 1 for idx in range(1, len(obv)): if close_data[idx] > close_data[idx-1]: obv[idx] = obv[idx-1] + volume[idx] elif close_data[idx] < close_data[idx-1]: obv[idx] = obv[idx-1] - volume[idx] elif close_data[idx] == close_data[idx-1]: obv[idx] = obv[idx-1] return obv
python
def on_balance_volume(close_data, volume): """ On Balance Volume. Formula: start = 1 if CLOSEt > CLOSEt-1 obv = obvt-1 + volumet elif CLOSEt < CLOSEt-1 obv = obvt-1 - volumet elif CLOSEt == CLOSTt-1 obv = obvt-1 """ catch_errors.check_for_input_len_diff(close_data, volume) obv = np.zeros(len(volume)) obv[0] = 1 for idx in range(1, len(obv)): if close_data[idx] > close_data[idx-1]: obv[idx] = obv[idx-1] + volume[idx] elif close_data[idx] < close_data[idx-1]: obv[idx] = obv[idx-1] - volume[idx] elif close_data[idx] == close_data[idx-1]: obv[idx] = obv[idx-1] return obv
[ "def", "on_balance_volume", "(", "close_data", ",", "volume", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "volume", ")", "obv", "=", "np", ".", "zeros", "(", "len", "(", "volume", ")", ")", "obv", "[", "0", "]", "="...
On Balance Volume. Formula: start = 1 if CLOSEt > CLOSEt-1 obv = obvt-1 + volumet elif CLOSEt < CLOSEt-1 obv = obvt-1 - volumet elif CLOSEt == CLOSTt-1 obv = obvt-1
[ "On", "Balance", "Volume", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/on_balance_volume.py#L7-L30
train
229,214
kylejusticemagnuson/pyti
pyti/rate_of_change.py
rate_of_change
def rate_of_change(data, period): """ Rate of Change. Formula: (Close - Close n periods ago) / (Close n periods ago) * 100 """ catch_errors.check_for_period_error(data, period) rocs = [((data[idx] - data[idx - (period - 1)]) / data[idx - (period - 1)]) * 100 for idx in range(period - 1, len(data))] rocs = fill_for_noncomputable_vals(data, rocs) return rocs
python
def rate_of_change(data, period): """ Rate of Change. Formula: (Close - Close n periods ago) / (Close n periods ago) * 100 """ catch_errors.check_for_period_error(data, period) rocs = [((data[idx] - data[idx - (period - 1)]) / data[idx - (period - 1)]) * 100 for idx in range(period - 1, len(data))] rocs = fill_for_noncomputable_vals(data, rocs) return rocs
[ "def", "rate_of_change", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "rocs", "=", "[", "(", "(", "data", "[", "idx", "]", "-", "data", "[", "idx", "-", "(", "period", "-", "1",...
Rate of Change. Formula: (Close - Close n periods ago) / (Close n periods ago) * 100
[ "Rate", "of", "Change", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/rate_of_change.py#L7-L19
train
229,215
kylejusticemagnuson/pyti
pyti/average_true_range.py
average_true_range
def average_true_range(close_data, period): """ Average True Range. Formula: ATRt = ATRt-1 * (n - 1) + TRt / n """ tr = true_range(close_data, period) atr = smoothed_moving_average(tr, period) atr[0:period-1] = tr[0:period-1] return atr
python
def average_true_range(close_data, period): """ Average True Range. Formula: ATRt = ATRt-1 * (n - 1) + TRt / n """ tr = true_range(close_data, period) atr = smoothed_moving_average(tr, period) atr[0:period-1] = tr[0:period-1] return atr
[ "def", "average_true_range", "(", "close_data", ",", "period", ")", ":", "tr", "=", "true_range", "(", "close_data", ",", "period", ")", "atr", "=", "smoothed_moving_average", "(", "tr", ",", "period", ")", "atr", "[", "0", ":", "period", "-", "1", "]", ...
Average True Range. Formula: ATRt = ATRt-1 * (n - 1) + TRt / n
[ "Average", "True", "Range", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/average_true_range.py#L8-L18
train
229,216
kylejusticemagnuson/pyti
pyti/relative_strength_index.py
relative_strength_index
def relative_strength_index(data, period): """ Relative Strength Index. Formula: RSI = 100 - (100 / 1 + (prevGain/prevLoss)) """ catch_errors.check_for_period_error(data, period) period = int(period) changes = [data_tup[1] - data_tup[0] for data_tup in zip(data[::1], data[1::1])] filtered_gain = [val < 0 for val in changes] gains = [0 if filtered_gain[idx] is True else changes[idx] for idx in range(0, len(filtered_gain))] filtered_loss = [val > 0 for val in changes] losses = [0 if filtered_loss[idx] is True else abs(changes[idx]) for idx in range(0, len(filtered_loss))] avg_gain = np.mean(gains[:period]) avg_loss = np.mean(losses[:period]) rsi = [] if avg_loss == 0: rsi.append(100) else: rs = avg_gain / avg_loss rsi.append(100 - (100 / (1 + rs))) for idx in range(1, len(data) - period): avg_gain = ((avg_gain * (period - 1) + gains[idx + (period - 1)]) / period) avg_loss = ((avg_loss * (period - 1) + losses[idx + (period - 1)]) / period) if avg_loss == 0: rsi.append(100) else: rs = avg_gain / avg_loss rsi.append(100 - (100 / (1 + rs))) rsi = fill_for_noncomputable_vals(data, rsi) return rsi
python
def relative_strength_index(data, period): """ Relative Strength Index. Formula: RSI = 100 - (100 / 1 + (prevGain/prevLoss)) """ catch_errors.check_for_period_error(data, period) period = int(period) changes = [data_tup[1] - data_tup[0] for data_tup in zip(data[::1], data[1::1])] filtered_gain = [val < 0 for val in changes] gains = [0 if filtered_gain[idx] is True else changes[idx] for idx in range(0, len(filtered_gain))] filtered_loss = [val > 0 for val in changes] losses = [0 if filtered_loss[idx] is True else abs(changes[idx]) for idx in range(0, len(filtered_loss))] avg_gain = np.mean(gains[:period]) avg_loss = np.mean(losses[:period]) rsi = [] if avg_loss == 0: rsi.append(100) else: rs = avg_gain / avg_loss rsi.append(100 - (100 / (1 + rs))) for idx in range(1, len(data) - period): avg_gain = ((avg_gain * (period - 1) + gains[idx + (period - 1)]) / period) avg_loss = ((avg_loss * (period - 1) + losses[idx + (period - 1)]) / period) if avg_loss == 0: rsi.append(100) else: rs = avg_gain / avg_loss rsi.append(100 - (100 / (1 + rs))) rsi = fill_for_noncomputable_vals(data, rsi) return rsi
[ "def", "relative_strength_index", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "changes", "=", "[", "data_tup", "[", "1", "]", "-", "data_tup...
Relative Strength Index. Formula: RSI = 100 - (100 / 1 + (prevGain/prevLoss))
[ "Relative", "Strength", "Index", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/relative_strength_index.py#L9-L51
train
229,217
kylejusticemagnuson/pyti
pyti/vertical_horizontal_filter.py
vertical_horizontal_filter
def vertical_horizontal_filter(data, period): """ Vertical Horizontal Filter. Formula: ABS(pHIGH - pLOW) / SUM(ABS(Pi - Pi-1)) """ catch_errors.check_for_period_error(data, period) vhf = [abs(np.max(data[idx+1-period:idx+1]) - np.min(data[idx+1-period:idx+1])) / sum([abs(data[idx+1-period:idx+1][i] - data[idx+1-period:idx+1][i-1]) for i in range(0, len(data[idx+1-period:idx+1]))]) for idx in range(period - 1, len(data))] vhf = fill_for_noncomputable_vals(data, vhf) return vhf
python
def vertical_horizontal_filter(data, period): """ Vertical Horizontal Filter. Formula: ABS(pHIGH - pLOW) / SUM(ABS(Pi - Pi-1)) """ catch_errors.check_for_period_error(data, period) vhf = [abs(np.max(data[idx+1-period:idx+1]) - np.min(data[idx+1-period:idx+1])) / sum([abs(data[idx+1-period:idx+1][i] - data[idx+1-period:idx+1][i-1]) for i in range(0, len(data[idx+1-period:idx+1]))]) for idx in range(period - 1, len(data))] vhf = fill_for_noncomputable_vals(data, vhf) return vhf
[ "def", "vertical_horizontal_filter", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "vhf", "=", "[", "abs", "(", "np", ".", "max", "(", "data", "[", "idx", "+", "1", "-", "period", ...
Vertical Horizontal Filter. Formula: ABS(pHIGH - pLOW) / SUM(ABS(Pi - Pi-1))
[ "Vertical", "Horizontal", "Filter", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/vertical_horizontal_filter.py#L8-L22
train
229,218
kylejusticemagnuson/pyti
pyti/ultimate_oscillator.py
buying_pressure
def buying_pressure(close_data, low_data): """ Buying Pressure. Formula: BP = current close - min() """ catch_errors.check_for_input_len_diff(close_data, low_data) bp = [close_data[idx] - np.min([low_data[idx], close_data[idx-1]]) for idx in range(1, len(close_data))] bp = fill_for_noncomputable_vals(close_data, bp) return bp
python
def buying_pressure(close_data, low_data): """ Buying Pressure. Formula: BP = current close - min() """ catch_errors.check_for_input_len_diff(close_data, low_data) bp = [close_data[idx] - np.min([low_data[idx], close_data[idx-1]]) for idx in range(1, len(close_data))] bp = fill_for_noncomputable_vals(close_data, bp) return bp
[ "def", "buying_pressure", "(", "close_data", ",", "low_data", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "low_data", ")", "bp", "=", "[", "close_data", "[", "idx", "]", "-", "np", ".", "min", "(", "[", "low_data", "[...
Buying Pressure. Formula: BP = current close - min()
[ "Buying", "Pressure", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/ultimate_oscillator.py#L9-L19
train
229,219
kylejusticemagnuson/pyti
pyti/ultimate_oscillator.py
ultimate_oscillator
def ultimate_oscillator(close_data, low_data): """ Ultimate Oscillator. Formula: UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1) """ a7 = 4 * average_7(close_data, low_data) a14 = 2 * average_14(close_data, low_data) a28 = average_28(close_data, low_data) uo = 100 * ((a7 + a14 + a28) / 7) return uo
python
def ultimate_oscillator(close_data, low_data): """ Ultimate Oscillator. Formula: UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1) """ a7 = 4 * average_7(close_data, low_data) a14 = 2 * average_14(close_data, low_data) a28 = average_28(close_data, low_data) uo = 100 * ((a7 + a14 + a28) / 7) return uo
[ "def", "ultimate_oscillator", "(", "close_data", ",", "low_data", ")", ":", "a7", "=", "4", "*", "average_7", "(", "close_data", ",", "low_data", ")", "a14", "=", "2", "*", "average_14", "(", "close_data", ",", "low_data", ")", "a28", "=", "average_28", ...
Ultimate Oscillator. Formula: UO = 100 * ((4 * AVG7) + (2 * AVG14) + AVG28) / (4 + 2 + 1)
[ "Ultimate", "Oscillator", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/ultimate_oscillator.py#L62-L73
train
229,220
kylejusticemagnuson/pyti
pyti/aroon.py
aroon_up
def aroon_up(data, period): """ Aroon Up. Formula: AROONUP = (((PERIOD) - (PERIODS since PERIOD high)) / (PERIOD)) * 100 """ catch_errors.check_for_period_error(data, period) period = int(period) a_up = [((period - list(reversed(data[idx+1-period:idx+1])).index(np.max(data[idx+1-period:idx+1]))) / float(period)) * 100 for idx in range(period-1, len(data))] a_up = fill_for_noncomputable_vals(data, a_up) return a_up
python
def aroon_up(data, period): """ Aroon Up. Formula: AROONUP = (((PERIOD) - (PERIODS since PERIOD high)) / (PERIOD)) * 100 """ catch_errors.check_for_period_error(data, period) period = int(period) a_up = [((period - list(reversed(data[idx+1-period:idx+1])).index(np.max(data[idx+1-period:idx+1]))) / float(period)) * 100 for idx in range(period-1, len(data))] a_up = fill_for_noncomputable_vals(data, a_up) return a_up
[ "def", "aroon_up", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "a_up", "=", "[", "(", "(", "period", "-", "list", "(", "reversed", "(", ...
Aroon Up. Formula: AROONUP = (((PERIOD) - (PERIODS since PERIOD high)) / (PERIOD)) * 100
[ "Aroon", "Up", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/aroon.py#L8-L22
train
229,221
kylejusticemagnuson/pyti
pyti/aroon.py
aroon_down
def aroon_down(data, period): """ Aroon Down. Formula: AROONDWN = (((PERIOD) - (PERIODS SINCE PERIOD LOW)) / (PERIOD)) * 100 """ catch_errors.check_for_period_error(data, period) period = int(period) a_down = [((period - list(reversed(data[idx+1-period:idx+1])).index(np.min(data[idx+1-period:idx+1]))) / float(period)) * 100 for idx in range(period-1, len(data))] a_down = fill_for_noncomputable_vals(data, a_down) return a_down
python
def aroon_down(data, period): """ Aroon Down. Formula: AROONDWN = (((PERIOD) - (PERIODS SINCE PERIOD LOW)) / (PERIOD)) * 100 """ catch_errors.check_for_period_error(data, period) period = int(period) a_down = [((period - list(reversed(data[idx+1-period:idx+1])).index(np.min(data[idx+1-period:idx+1]))) / float(period)) * 100 for idx in range(period-1, len(data))] a_down = fill_for_noncomputable_vals(data, a_down) return a_down
[ "def", "aroon_down", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "a_down", "=", "[", "(", "(", "period", "-", "list", "(", "reversed", "...
Aroon Down. Formula: AROONDWN = (((PERIOD) - (PERIODS SINCE PERIOD LOW)) / (PERIOD)) * 100
[ "Aroon", "Down", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/aroon.py#L25-L39
train
229,222
kylejusticemagnuson/pyti
pyti/price_channels.py
upper_price_channel
def upper_price_channel(data, period, upper_percent): """ Upper Price Channel. Formula: upc = EMA(t) * (1 + upper_percent / 100) """ catch_errors.check_for_period_error(data, period) emas = ema(data, period) upper_channel = [val * (1+float(upper_percent)/100) for val in emas] return upper_channel
python
def upper_price_channel(data, period, upper_percent): """ Upper Price Channel. Formula: upc = EMA(t) * (1 + upper_percent / 100) """ catch_errors.check_for_period_error(data, period) emas = ema(data, period) upper_channel = [val * (1+float(upper_percent)/100) for val in emas] return upper_channel
[ "def", "upper_price_channel", "(", "data", ",", "period", ",", "upper_percent", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "emas", "=", "ema", "(", "data", ",", "period", ")", "upper_channel", "=", "[", "val", ...
Upper Price Channel. Formula: upc = EMA(t) * (1 + upper_percent / 100)
[ "Upper", "Price", "Channel", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/price_channels.py#L8-L19
train
229,223
kylejusticemagnuson/pyti
pyti/price_channels.py
lower_price_channel
def lower_price_channel(data, period, lower_percent): """ Lower Price Channel. Formula: lpc = EMA(t) * (1 - lower_percent / 100) """ catch_errors.check_for_period_error(data, period) emas = ema(data, period) lower_channel = [val * (1-float(lower_percent)/100) for val in emas] return lower_channel
python
def lower_price_channel(data, period, lower_percent): """ Lower Price Channel. Formula: lpc = EMA(t) * (1 - lower_percent / 100) """ catch_errors.check_for_period_error(data, period) emas = ema(data, period) lower_channel = [val * (1-float(lower_percent)/100) for val in emas] return lower_channel
[ "def", "lower_price_channel", "(", "data", ",", "period", ",", "lower_percent", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "emas", "=", "ema", "(", "data", ",", "period", ")", "lower_channel", "=", "[", "val", ...
Lower Price Channel. Formula: lpc = EMA(t) * (1 - lower_percent / 100)
[ "Lower", "Price", "Channel", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/price_channels.py#L22-L33
train
229,224
kylejusticemagnuson/pyti
pyti/exponential_moving_average.py
exponential_moving_average
def exponential_moving_average(data, period): """ Exponential Moving Average. Formula: p0 + (1 - w) * p1 + (1 - w)^2 * p2 + (1 + w)^3 * p3 +... / 1 + (1 - w) + (1 - w)^2 + (1 - w)^3 +... where: w = 2 / (N + 1) """ catch_errors.check_for_period_error(data, period) emas = [exponential_moving_average_helper( data[idx - period + 1:idx + 1], period) for idx in range(period - 1, len(data))] emas = fill_for_noncomputable_vals(data, emas) return emas
python
def exponential_moving_average(data, period): """ Exponential Moving Average. Formula: p0 + (1 - w) * p1 + (1 - w)^2 * p2 + (1 + w)^3 * p3 +... / 1 + (1 - w) + (1 - w)^2 + (1 - w)^3 +... where: w = 2 / (N + 1) """ catch_errors.check_for_period_error(data, period) emas = [exponential_moving_average_helper( data[idx - period + 1:idx + 1], period) for idx in range(period - 1, len(data))] emas = fill_for_noncomputable_vals(data, emas) return emas
[ "def", "exponential_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "emas", "=", "[", "exponential_moving_average_helper", "(", "data", "[", "idx", "-", "period", "+", "1", ...
Exponential Moving Average. Formula: p0 + (1 - w) * p1 + (1 - w)^2 * p2 + (1 + w)^3 * p3 +... / 1 + (1 - w) + (1 - w)^2 + (1 - w)^3 +... where: w = 2 / (N + 1)
[ "Exponential", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/exponential_moving_average.py#L7-L21
train
229,225
kylejusticemagnuson/pyti
pyti/commodity_channel_index.py
commodity_channel_index
def commodity_channel_index(close_data, high_data, low_data, period): """ Commodity Channel Index. Formula: CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation) """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) catch_errors.check_for_period_error(close_data, period) tp = typical_price(close_data, high_data, low_data) cci = ((tp - sma(tp, period)) / (0.015 * np.mean(np.absolute(tp - np.mean(tp))))) return cci
python
def commodity_channel_index(close_data, high_data, low_data, period): """ Commodity Channel Index. Formula: CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation) """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) catch_errors.check_for_period_error(close_data, period) tp = typical_price(close_data, high_data, low_data) cci = ((tp - sma(tp, period)) / (0.015 * np.mean(np.absolute(tp - np.mean(tp))))) return cci
[ "def", "commodity_channel_index", "(", "close_data", ",", "high_data", ",", "low_data", ",", "period", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "high_data", ",", "low_data", ")", "catch_errors", ".", "check_for_period_error", ...
Commodity Channel Index. Formula: CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation)
[ "Commodity", "Channel", "Index", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/commodity_channel_index.py#L10-L22
train
229,226
kylejusticemagnuson/pyti
pyti/williams_percent_r.py
williams_percent_r
def williams_percent_r(close_data): """ Williams %R. Formula: wr = (HighestHigh - close / HighestHigh - LowestLow) * -100 """ highest_high = np.max(close_data) lowest_low = np.min(close_data) wr = [((highest_high - close) / (highest_high - lowest_low)) * -100 for close in close_data] return wr
python
def williams_percent_r(close_data): """ Williams %R. Formula: wr = (HighestHigh - close / HighestHigh - LowestLow) * -100 """ highest_high = np.max(close_data) lowest_low = np.min(close_data) wr = [((highest_high - close) / (highest_high - lowest_low)) * -100 for close in close_data] return wr
[ "def", "williams_percent_r", "(", "close_data", ")", ":", "highest_high", "=", "np", ".", "max", "(", "close_data", ")", "lowest_low", "=", "np", ".", "min", "(", "close_data", ")", "wr", "=", "[", "(", "(", "highest_high", "-", "close", ")", "/", "(",...
Williams %R. Formula: wr = (HighestHigh - close / HighestHigh - LowestLow) * -100
[ "Williams", "%R", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/williams_percent_r.py#L5-L15
train
229,227
kylejusticemagnuson/pyti
pyti/moving_average_convergence_divergence.py
moving_average_convergence_divergence
def moving_average_convergence_divergence(data, short_period, long_period): """ Moving Average Convergence Divergence. Formula: EMA(DATA, P1) - EMA(DATA, P2) """ catch_errors.check_for_period_error(data, short_period) catch_errors.check_for_period_error(data, long_period) macd = ema(data, short_period) - ema(data, long_period) return macd
python
def moving_average_convergence_divergence(data, short_period, long_period): """ Moving Average Convergence Divergence. Formula: EMA(DATA, P1) - EMA(DATA, P2) """ catch_errors.check_for_period_error(data, short_period) catch_errors.check_for_period_error(data, long_period) macd = ema(data, short_period) - ema(data, long_period) return macd
[ "def", "moving_average_convergence_divergence", "(", "data", ",", "short_period", ",", "long_period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "short_period", ")", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "long...
Moving Average Convergence Divergence. Formula: EMA(DATA, P1) - EMA(DATA, P2)
[ "Moving", "Average", "Convergence", "Divergence", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/moving_average_convergence_divergence.py#L8-L19
train
229,228
kylejusticemagnuson/pyti
pyti/money_flow_index.py
money_flow_index
def money_flow_index(close_data, high_data, low_data, volume, period): """ Money Flow Index. Formula: MFI = 100 - (100 / (1 + PMF / NMF)) """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) catch_errors.check_for_period_error(close_data, period) mf = money_flow(close_data, high_data, low_data, volume) tp = typical_price(close_data, high_data, low_data) flow = [tp[idx] > tp[idx-1] for idx in range(1, len(tp))] pf = [mf[idx] if flow[idx] else 0 for idx in range(0, len(flow))] nf = [mf[idx] if not flow[idx] else 0 for idx in range(0, len(flow))] pmf = [sum(pf[idx+1-period:idx+1]) for idx in range(period-1, len(pf))] nmf = [sum(nf[idx+1-period:idx+1]) for idx in range(period-1, len(nf))] # Dividing by 0 is not an issue, it turns the value into NaN which we would # want in that case with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) money_ratio = np.array(pmf) / np.array(nmf) mfi = 100 - (100 / (1 + money_ratio)) mfi = fill_for_noncomputable_vals(close_data, mfi) return mfi
python
def money_flow_index(close_data, high_data, low_data, volume, period): """ Money Flow Index. Formula: MFI = 100 - (100 / (1 + PMF / NMF)) """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) catch_errors.check_for_period_error(close_data, period) mf = money_flow(close_data, high_data, low_data, volume) tp = typical_price(close_data, high_data, low_data) flow = [tp[idx] > tp[idx-1] for idx in range(1, len(tp))] pf = [mf[idx] if flow[idx] else 0 for idx in range(0, len(flow))] nf = [mf[idx] if not flow[idx] else 0 for idx in range(0, len(flow))] pmf = [sum(pf[idx+1-period:idx+1]) for idx in range(period-1, len(pf))] nmf = [sum(nf[idx+1-period:idx+1]) for idx in range(period-1, len(nf))] # Dividing by 0 is not an issue, it turns the value into NaN which we would # want in that case with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) money_ratio = np.array(pmf) / np.array(nmf) mfi = 100 - (100 / (1 + money_ratio)) mfi = fill_for_noncomputable_vals(close_data, mfi) return mfi
[ "def", "money_flow_index", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ",", "period", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ")", "catch_errors", "....
Money Flow Index. Formula: MFI = 100 - (100 / (1 + PMF / NMF))
[ "Money", "Flow", "Index", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/money_flow_index.py#L11-L43
train
229,229
kylejusticemagnuson/pyti
pyti/typical_price.py
typical_price
def typical_price(close_data, high_data, low_data): """ Typical Price. Formula: TPt = (HIGHt + LOWt + CLOSEt) / 3 """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) tp = [(high_data[idx] + low_data[idx] + close_data[idx]) / 3 for idx in range(0, len(close_data))] return np.array(tp)
python
def typical_price(close_data, high_data, low_data): """ Typical Price. Formula: TPt = (HIGHt + LOWt + CLOSEt) / 3 """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) tp = [(high_data[idx] + low_data[idx] + close_data[idx]) / 3 for idx in range(0, len(close_data))] return np.array(tp)
[ "def", "typical_price", "(", "close_data", ",", "high_data", ",", "low_data", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "high_data", ",", "low_data", ")", "tp", "=", "[", "(", "high_data", "[", "idx", "]", "+", "low_d...
Typical Price. Formula: TPt = (HIGHt + LOWt + CLOSEt) / 3
[ "Typical", "Price", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/typical_price.py#L7-L16
train
229,230
kylejusticemagnuson/pyti
pyti/true_range.py
true_range
def true_range(close_data, period): """ True Range. Formula: TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1)) """ catch_errors.check_for_period_error(close_data, period) tr = [np.max([np.max(close_data[idx+1-period:idx+1]) - np.min(close_data[idx+1-period:idx+1]), abs(np.max(close_data[idx+1-period:idx+1]) - close_data[idx-1]), abs(np.min(close_data[idx+1-period:idx+1]) - close_data[idx-1])]) for idx in range(period-1, len(close_data))] tr = fill_for_noncomputable_vals(close_data, tr) return tr
python
def true_range(close_data, period): """ True Range. Formula: TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1)) """ catch_errors.check_for_period_error(close_data, period) tr = [np.max([np.max(close_data[idx+1-period:idx+1]) - np.min(close_data[idx+1-period:idx+1]), abs(np.max(close_data[idx+1-period:idx+1]) - close_data[idx-1]), abs(np.min(close_data[idx+1-period:idx+1]) - close_data[idx-1])]) for idx in range(period-1, len(close_data))] tr = fill_for_noncomputable_vals(close_data, tr) return tr
[ "def", "true_range", "(", "close_data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "close_data", ",", "period", ")", "tr", "=", "[", "np", ".", "max", "(", "[", "np", ".", "max", "(", "close_data", "[", "idx", "+", "1"...
True Range. Formula: TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1))
[ "True", "Range", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/true_range.py#L8-L24
train
229,231
kylejusticemagnuson/pyti
pyti/double_smoothed_stochastic.py
double_smoothed_stochastic
def double_smoothed_stochastic(data, period): """ Double Smoothed Stochastic. Formula: dss = 100 * EMA(Close - Lowest Low) / EMA(Highest High - Lowest Low) """ catch_errors.check_for_period_error(data, period) lows = [data[idx] - np.min(data[idx+1-period:idx+1]) for idx in range(period-1, len(data))] sm_lows = ema(ema(lows, period), period) highs = [np.max(data[idx+1-period:idx+1]) - np.min(data[idx+1-period:idx+1]) for idx in range(period-1, len(data))] sm_highs = ema(ema(highs, period), period) dss = (sm_lows / sm_highs) * 100 dss = fill_for_noncomputable_vals(data, dss) return dss
python
def double_smoothed_stochastic(data, period): """ Double Smoothed Stochastic. Formula: dss = 100 * EMA(Close - Lowest Low) / EMA(Highest High - Lowest Low) """ catch_errors.check_for_period_error(data, period) lows = [data[idx] - np.min(data[idx+1-period:idx+1]) for idx in range(period-1, len(data))] sm_lows = ema(ema(lows, period), period) highs = [np.max(data[idx+1-period:idx+1]) - np.min(data[idx+1-period:idx+1]) for idx in range(period-1, len(data))] sm_highs = ema(ema(highs, period), period) dss = (sm_lows / sm_highs) * 100 dss = fill_for_noncomputable_vals(data, dss) return dss
[ "def", "double_smoothed_stochastic", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "lows", "=", "[", "data", "[", "idx", "]", "-", "np", ".", "min", "(", "data", "[", "idx", "+", "...
Double Smoothed Stochastic. Formula: dss = 100 * EMA(Close - Lowest Low) / EMA(Highest High - Lowest Low)
[ "Double", "Smoothed", "Stochastic", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/double_smoothed_stochastic.py#L11-L26
train
229,232
kylejusticemagnuson/pyti
pyti/volume_adjusted_moving_average.py
volume_adjusted_moving_average
def volume_adjusted_moving_average(close_data, volume, period): """ Volume Adjusted Moving Average. Formula: VAMA = SUM(CLOSE * VolumeRatio) / period """ catch_errors.check_for_input_len_diff(close_data, volume) catch_errors.check_for_period_error(close_data, period) avg_vol = np.mean(volume) vol_incr = avg_vol * 0.67 vol_ratio = [val / vol_incr for val in volume] close_vol = np.array(close_data) * vol_ratio vama = [sum(close_vol[idx+1-period:idx+1]) / period for idx in range(period-1, len(close_data))] vama = fill_for_noncomputable_vals(close_data, vama) return vama
python
def volume_adjusted_moving_average(close_data, volume, period): """ Volume Adjusted Moving Average. Formula: VAMA = SUM(CLOSE * VolumeRatio) / period """ catch_errors.check_for_input_len_diff(close_data, volume) catch_errors.check_for_period_error(close_data, period) avg_vol = np.mean(volume) vol_incr = avg_vol * 0.67 vol_ratio = [val / vol_incr for val in volume] close_vol = np.array(close_data) * vol_ratio vama = [sum(close_vol[idx+1-period:idx+1]) / period for idx in range(period-1, len(close_data))] vama = fill_for_noncomputable_vals(close_data, vama) return vama
[ "def", "volume_adjusted_moving_average", "(", "close_data", ",", "volume", ",", "period", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "volume", ")", "catch_errors", ".", "check_for_period_error", "(", "close_data", ",", "period",...
Volume Adjusted Moving Average. Formula: VAMA = SUM(CLOSE * VolumeRatio) / period
[ "Volume", "Adjusted", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/volume_adjusted_moving_average.py#L8-L24
train
229,233
kylejusticemagnuson/pyti
pyti/double_exponential_moving_average.py
double_exponential_moving_average
def double_exponential_moving_average(data, period): """ Double Exponential Moving Average. Formula: DEMA = 2*EMA - EMA(EMA) """ catch_errors.check_for_period_error(data, period) dema = (2 * ema(data, period)) - ema(ema(data, period), period) return dema
python
def double_exponential_moving_average(data, period): """ Double Exponential Moving Average. Formula: DEMA = 2*EMA - EMA(EMA) """ catch_errors.check_for_period_error(data, period) dema = (2 * ema(data, period)) - ema(ema(data, period), period) return dema
[ "def", "double_exponential_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "dema", "=", "(", "2", "*", "ema", "(", "data", ",", "period", ")", ")", "-", "ema", "(", "e...
Double Exponential Moving Average. Formula: DEMA = 2*EMA - EMA(EMA)
[ "Double", "Exponential", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/double_exponential_moving_average.py#L8-L18
train
229,234
kylejusticemagnuson/pyti
pyti/triangular_moving_average.py
triangular_moving_average
def triangular_moving_average(data, period): """ Triangular Moving Average. Formula: TMA = SMA(SMA()) """ catch_errors.check_for_period_error(data, period) tma = sma(sma(data, period), period) return tma
python
def triangular_moving_average(data, period): """ Triangular Moving Average. Formula: TMA = SMA(SMA()) """ catch_errors.check_for_period_error(data, period) tma = sma(sma(data, period), period) return tma
[ "def", "triangular_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "tma", "=", "sma", "(", "sma", "(", "data", ",", "period", ")", ",", "period", ")", "return", "tma" ]
Triangular Moving Average. Formula: TMA = SMA(SMA())
[ "Triangular", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/triangular_moving_average.py#L8-L18
train
229,235
kylejusticemagnuson/pyti
pyti/weighted_moving_average.py
weighted_moving_average
def weighted_moving_average(data, period): """ Weighted Moving Average. Formula: (P1 + 2 P2 + 3 P3 + ... + n Pn) / K where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price """ catch_errors.check_for_period_error(data, period) k = (period * (period + 1)) / 2.0 wmas = [] for idx in range(0, len(data)-period+1): product = [data[idx + period_idx] * (period_idx + 1) for period_idx in range(0, period)] wma = sum(product) / k wmas.append(wma) wmas = fill_for_noncomputable_vals(data, wmas) return wmas
python
def weighted_moving_average(data, period): """ Weighted Moving Average. Formula: (P1 + 2 P2 + 3 P3 + ... + n Pn) / K where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price """ catch_errors.check_for_period_error(data, period) k = (period * (period + 1)) / 2.0 wmas = [] for idx in range(0, len(data)-period+1): product = [data[idx + period_idx] * (period_idx + 1) for period_idx in range(0, period)] wma = sum(product) / k wmas.append(wma) wmas = fill_for_noncomputable_vals(data, wmas) return wmas
[ "def", "weighted_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "k", "=", "(", "period", "*", "(", "period", "+", "1", ")", ")", "/", "2.0", "wmas", "=", "[", "]", ...
Weighted Moving Average. Formula: (P1 + 2 P2 + 3 P3 + ... + n Pn) / K where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price
[ "Weighted", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/weighted_moving_average.py#L7-L25
train
229,236
kylejusticemagnuson/pyti
pyti/ichimoku_cloud.py
conversion_base_line_helper
def conversion_base_line_helper(data, period): """ The only real difference between TenkanSen and KijunSen is the period value """ catch_errors.check_for_period_error(data, period) cblh = [(np.max(data[idx+1-period:idx+1]) + np.min(data[idx+1-period:idx+1])) / 2 for idx in range(period-1, len(data))] cblh = fill_for_noncomputable_vals(data, cblh) return cblh
python
def conversion_base_line_helper(data, period): """ The only real difference between TenkanSen and KijunSen is the period value """ catch_errors.check_for_period_error(data, period) cblh = [(np.max(data[idx+1-period:idx+1]) + np.min(data[idx+1-period:idx+1])) / 2 for idx in range(period-1, len(data))] cblh = fill_for_noncomputable_vals(data, cblh) return cblh
[ "def", "conversion_base_line_helper", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "cblh", "=", "[", "(", "np", ".", "max", "(", "data", "[", "idx", "+", "1", "-", "period", ":", ...
The only real difference between TenkanSen and KijunSen is the period value
[ "The", "only", "real", "difference", "between", "TenkanSen", "and", "KijunSen", "is", "the", "period", "value" ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/ichimoku_cloud.py#L8-L17
train
229,237
kylejusticemagnuson/pyti
pyti/chande_momentum_oscillator.py
chande_momentum_oscillator
def chande_momentum_oscillator(close_data, period): """ Chande Momentum Oscillator. Formula: cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down)) """ catch_errors.check_for_period_error(close_data, period) close_data = np.array(close_data) moving_period_diffs = [[(close_data[idx+1-period:idx+1][i] - close_data[idx+1-period:idx+1][i-1]) for i in range(1, len(close_data[idx+1-period:idx+1]))] for idx in range(0, len(close_data))] sum_up = [] sum_down = [] for period_diffs in moving_period_diffs: ups = [val if val > 0 else 0 for val in period_diffs] sum_up.append(sum(ups)) downs = [abs(val) if val < 0 else 0 for val in period_diffs] sum_down.append(sum(downs)) sum_up = np.array(sum_up) sum_down = np.array(sum_down) # numpy is able to handle dividing by zero and makes those calculations # nans which is what we want, so we safely suppress the RuntimeWarning with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down)) return cmo
python
def chande_momentum_oscillator(close_data, period): """ Chande Momentum Oscillator. Formula: cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down)) """ catch_errors.check_for_period_error(close_data, period) close_data = np.array(close_data) moving_period_diffs = [[(close_data[idx+1-period:idx+1][i] - close_data[idx+1-period:idx+1][i-1]) for i in range(1, len(close_data[idx+1-period:idx+1]))] for idx in range(0, len(close_data))] sum_up = [] sum_down = [] for period_diffs in moving_period_diffs: ups = [val if val > 0 else 0 for val in period_diffs] sum_up.append(sum(ups)) downs = [abs(val) if val < 0 else 0 for val in period_diffs] sum_down.append(sum(downs)) sum_up = np.array(sum_up) sum_down = np.array(sum_down) # numpy is able to handle dividing by zero and makes those calculations # nans which is what we want, so we safely suppress the RuntimeWarning with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down)) return cmo
[ "def", "chande_momentum_oscillator", "(", "close_data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "close_data", ",", "period", ")", "close_data", "=", "np", ".", "array", "(", "close_data", ")", "moving_period_diffs", "=", "[", ...
Chande Momentum Oscillator. Formula: cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down))
[ "Chande", "Momentum", "Oscillator", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/chande_momentum_oscillator.py#L8-L37
train
229,238
kylejusticemagnuson/pyti
pyti/price_oscillator.py
price_oscillator
def price_oscillator(data, short_period, long_period): """ Price Oscillator. Formula: (short EMA - long EMA / long EMA) * 100 """ catch_errors.check_for_period_error(data, short_period) catch_errors.check_for_period_error(data, long_period) ema_short = ema(data, short_period) ema_long = ema(data, long_period) po = ((ema_short - ema_long) / ema_long) * 100 return po
python
def price_oscillator(data, short_period, long_period): """ Price Oscillator. Formula: (short EMA - long EMA / long EMA) * 100 """ catch_errors.check_for_period_error(data, short_period) catch_errors.check_for_period_error(data, long_period) ema_short = ema(data, short_period) ema_long = ema(data, long_period) po = ((ema_short - ema_long) / ema_long) * 100 return po
[ "def", "price_oscillator", "(", "data", ",", "short_period", ",", "long_period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "short_period", ")", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "long_period", ")", "e...
Price Oscillator. Formula: (short EMA - long EMA / long EMA) * 100
[ "Price", "Oscillator", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/price_oscillator.py#L8-L22
train
229,239
kylejusticemagnuson/pyti
pyti/catch_errors.py
check_for_period_error
def check_for_period_error(data, period): """ Check for Period Error. This method checks if the developer is trying to enter a period that is larger than the data set being entered. If that is the case an exception is raised with a custom message that informs the developer that their period is greater than the data set. """ period = int(period) data_len = len(data) if data_len < period: raise Exception("Error: data_len < period")
python
def check_for_period_error(data, period): """ Check for Period Error. This method checks if the developer is trying to enter a period that is larger than the data set being entered. If that is the case an exception is raised with a custom message that informs the developer that their period is greater than the data set. """ period = int(period) data_len = len(data) if data_len < period: raise Exception("Error: data_len < period")
[ "def", "check_for_period_error", "(", "data", ",", "period", ")", ":", "period", "=", "int", "(", "period", ")", "data_len", "=", "len", "(", "data", ")", "if", "data_len", "<", "period", ":", "raise", "Exception", "(", "\"Error: data_len < period\"", ")" ]
Check for Period Error. This method checks if the developer is trying to enter a period that is larger than the data set being entered. If that is the case an exception is raised with a custom message that informs the developer that their period is greater than the data set.
[ "Check", "for", "Period", "Error", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/catch_errors.py#L2-L14
train
229,240
kylejusticemagnuson/pyti
pyti/catch_errors.py
check_for_input_len_diff
def check_for_input_len_diff(*args): """ Check for Input Length Difference. This method checks if multiple data sets that are inputted are all the same size. If they are not the same length an error is raised with a custom message that informs the developer that the data set's lengths are not the same. """ arrays_len = [len(arr) for arr in args] if not all(a == arrays_len[0] for a in arrays_len): err_msg = ("Error: mismatched data lengths, check to ensure that all " "input data is the same length and valid") raise Exception(err_msg)
python
def check_for_input_len_diff(*args): """ Check for Input Length Difference. This method checks if multiple data sets that are inputted are all the same size. If they are not the same length an error is raised with a custom message that informs the developer that the data set's lengths are not the same. """ arrays_len = [len(arr) for arr in args] if not all(a == arrays_len[0] for a in arrays_len): err_msg = ("Error: mismatched data lengths, check to ensure that all " "input data is the same length and valid") raise Exception(err_msg)
[ "def", "check_for_input_len_diff", "(", "*", "args", ")", ":", "arrays_len", "=", "[", "len", "(", "arr", ")", "for", "arr", "in", "args", "]", "if", "not", "all", "(", "a", "==", "arrays_len", "[", "0", "]", "for", "a", "in", "arrays_len", ")", ":...
Check for Input Length Difference. This method checks if multiple data sets that are inputted are all the same size. If they are not the same length an error is raised with a custom message that informs the developer that the data set's lengths are not the same.
[ "Check", "for", "Input", "Length", "Difference", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/catch_errors.py#L17-L30
train
229,241
kylejusticemagnuson/pyti
pyti/bollinger_bands.py
upper_bollinger_band
def upper_bollinger_band(data, period, std_mult=2.0): """ Upper Bollinger Band. Formula: u_bb = SMA(t) + STD(SMA(t-n:t)) * std_mult """ catch_errors.check_for_period_error(data, period) period = int(period) simple_ma = sma(data, period)[period-1:] upper_bb = [] for idx in range(len(data) - period + 1): std_dev = np.std(data[idx:idx + period]) upper_bb.append(simple_ma[idx] + std_dev * std_mult) upper_bb = fill_for_noncomputable_vals(data, upper_bb) return np.array(upper_bb)
python
def upper_bollinger_band(data, period, std_mult=2.0): """ Upper Bollinger Band. Formula: u_bb = SMA(t) + STD(SMA(t-n:t)) * std_mult """ catch_errors.check_for_period_error(data, period) period = int(period) simple_ma = sma(data, period)[period-1:] upper_bb = [] for idx in range(len(data) - period + 1): std_dev = np.std(data[idx:idx + period]) upper_bb.append(simple_ma[idx] + std_dev * std_mult) upper_bb = fill_for_noncomputable_vals(data, upper_bb) return np.array(upper_bb)
[ "def", "upper_bollinger_band", "(", "data", ",", "period", ",", "std_mult", "=", "2.0", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "simple_ma", "=", "sma", "(", "data"...
Upper Bollinger Band. Formula: u_bb = SMA(t) + STD(SMA(t-n:t)) * std_mult
[ "Upper", "Bollinger", "Band", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/bollinger_bands.py#L11-L29
train
229,242
kylejusticemagnuson/pyti
pyti/bollinger_bands.py
middle_bollinger_band
def middle_bollinger_band(data, period, std=2.0): """ Middle Bollinger Band. Formula: m_bb = sma() """ catch_errors.check_for_period_error(data, period) period = int(period) mid_bb = sma(data, period) return mid_bb
python
def middle_bollinger_band(data, period, std=2.0): """ Middle Bollinger Band. Formula: m_bb = sma() """ catch_errors.check_for_period_error(data, period) period = int(period) mid_bb = sma(data, period) return mid_bb
[ "def", "middle_bollinger_band", "(", "data", ",", "period", ",", "std", "=", "2.0", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "mid_bb", "=", "sma", "(", "data", ","...
Middle Bollinger Band. Formula: m_bb = sma()
[ "Middle", "Bollinger", "Band", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/bollinger_bands.py#L32-L44
train
229,243
kylejusticemagnuson/pyti
pyti/bollinger_bands.py
lower_bollinger_band
def lower_bollinger_band(data, period, std=2.0): """ Lower Bollinger Band. Formula: u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult """ catch_errors.check_for_period_error(data, period) period = int(period) simple_ma = sma(data, period)[period-1:] lower_bb = [] for idx in range(len(data) - period + 1): std_dev = np.std(data[idx:idx + period]) lower_bb.append(simple_ma[idx] - std_dev * std) lower_bb = fill_for_noncomputable_vals(data, lower_bb) return np.array(lower_bb)
python
def lower_bollinger_band(data, period, std=2.0): """ Lower Bollinger Band. Formula: u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult """ catch_errors.check_for_period_error(data, period) period = int(period) simple_ma = sma(data, period)[period-1:] lower_bb = [] for idx in range(len(data) - period + 1): std_dev = np.std(data[idx:idx + period]) lower_bb.append(simple_ma[idx] - std_dev * std) lower_bb = fill_for_noncomputable_vals(data, lower_bb) return np.array(lower_bb)
[ "def", "lower_bollinger_band", "(", "data", ",", "period", ",", "std", "=", "2.0", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "simple_ma", "=", "sma", "(", "data", "...
Lower Bollinger Band. Formula: u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult
[ "Lower", "Bollinger", "Band", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/bollinger_bands.py#L47-L65
train
229,244
kylejusticemagnuson/pyti
pyti/bollinger_bands.py
percent_bandwidth
def percent_bandwidth(data, period, std=2.0): """ Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range() """ catch_errors.check_for_period_error(data, period) period = int(period) percent_bandwidth = ((np.array(data) - lower_bollinger_band(data, period, std)) / bb_range(data, period, std) ) return percent_bandwidth
python
def percent_bandwidth(data, period, std=2.0): """ Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range() """ catch_errors.check_for_period_error(data, period) period = int(period) percent_bandwidth = ((np.array(data) - lower_bollinger_band(data, period, std)) / bb_range(data, period, std) ) return percent_bandwidth
[ "def", "percent_bandwidth", "(", "data", ",", "period", ",", "std", "=", "2.0", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "percent_bandwidth", "=", "(", "(", "np", ...
Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range()
[ "Percent", "Bandwidth", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/bollinger_bands.py#L102-L117
train
229,245
kylejusticemagnuson/pyti
pyti/standard_deviation.py
standard_deviation
def standard_deviation(data, period): """ Standard Deviation. Formula: std = sqrt(avg(abs(x - avg(x))^2)) """ catch_errors.check_for_period_error(data, period) stds = [np.std(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))] stds = fill_for_noncomputable_vals(data, stds) return stds
python
def standard_deviation(data, period): """ Standard Deviation. Formula: std = sqrt(avg(abs(x - avg(x))^2)) """ catch_errors.check_for_period_error(data, period) stds = [np.std(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))] stds = fill_for_noncomputable_vals(data, stds) return stds
[ "def", "standard_deviation", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "stds", "=", "[", "np", ".", "std", "(", "data", "[", "idx", "+", "1", "-", "period", ":", "idx", "+", ...
Standard Deviation. Formula: std = sqrt(avg(abs(x - avg(x))^2))
[ "Standard", "Deviation", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/standard_deviation.py#L8-L20
train
229,246
kylejusticemagnuson/pyti
pyti/detrended_price_oscillator.py
detrended_price_oscillator
def detrended_price_oscillator(data, period): """ Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1]) """ catch_errors.check_for_period_error(data, period) period = int(period) dop = [data[idx] - np.mean(data[idx+1-(int(period/2)+1):idx+1]) for idx in range(period-1, len(data))] dop = fill_for_noncomputable_vals(data, dop) return dop
python
def detrended_price_oscillator(data, period): """ Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1]) """ catch_errors.check_for_period_error(data, period) period = int(period) dop = [data[idx] - np.mean(data[idx+1-(int(period/2)+1):idx+1]) for idx in range(period-1, len(data))] dop = fill_for_noncomputable_vals(data, dop) return dop
[ "def", "detrended_price_oscillator", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "dop", "=", "[", "data", "[", "idx", "]", "-", "np", ".",...
Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1])
[ "Detrended", "Price", "Oscillator", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/detrended_price_oscillator.py#L8-L19
train
229,247
kylejusticemagnuson/pyti
pyti/smoothed_moving_average.py
smoothed_moving_average
def smoothed_moving_average(data, period): """ Smoothed Moving Average. Formula: smma = avg(data(n)) - avg(data(n)/n) + data(t)/n """ catch_errors.check_for_period_error(data, period) series = pd.Series(data) return series.ewm(alpha = 1.0/period).mean().values.flatten()
python
def smoothed_moving_average(data, period): """ Smoothed Moving Average. Formula: smma = avg(data(n)) - avg(data(n)/n) + data(t)/n """ catch_errors.check_for_period_error(data, period) series = pd.Series(data) return series.ewm(alpha = 1.0/period).mean().values.flatten()
[ "def", "smoothed_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "series", "=", "pd", ".", "Series", "(", "data", ")", "return", "series", ".", "ewm", "(", "alpha", "=",...
Smoothed Moving Average. Formula: smma = avg(data(n)) - avg(data(n)/n) + data(t)/n
[ "Smoothed", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/smoothed_moving_average.py#L9-L18
train
229,248
kylejusticemagnuson/pyti
pyti/chaikin_money_flow.py
chaikin_money_flow
def chaikin_money_flow(close_data, high_data, low_data, volume, period): """ Chaikin Money Flow. Formula: CMF = SUM[(((Cn - Ln) - (Hn - Cn)) / (Hn - Ln)) * V] / SUM(Vn) """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume) catch_errors.check_for_period_error(close_data, period) close_data = np.array(close_data) high_data = np.array(high_data) low_data = np.array(low_data) volume = np.array(volume) cmf = [sum((((close_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1]) - (high_data[idx+1-period:idx+1] - close_data[idx+1-period:idx+1])) / (high_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1])) * volume[idx+1-period:idx+1]) / sum(volume[idx+1-period:idx+1]) for idx in range(period-1, len(close_data))] cmf = fill_for_noncomputable_vals(close_data, cmf) return cmf
python
def chaikin_money_flow(close_data, high_data, low_data, volume, period): """ Chaikin Money Flow. Formula: CMF = SUM[(((Cn - Ln) - (Hn - Cn)) / (Hn - Ln)) * V] / SUM(Vn) """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume) catch_errors.check_for_period_error(close_data, period) close_data = np.array(close_data) high_data = np.array(high_data) low_data = np.array(low_data) volume = np.array(volume) cmf = [sum((((close_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1]) - (high_data[idx+1-period:idx+1] - close_data[idx+1-period:idx+1])) / (high_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1])) * volume[idx+1-period:idx+1]) / sum(volume[idx+1-period:idx+1]) for idx in range(period-1, len(close_data))] cmf = fill_for_noncomputable_vals(close_data, cmf) return cmf
[ "def", "chaikin_money_flow", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ",", "period", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ")", "catch_errors", ...
Chaikin Money Flow. Formula: CMF = SUM[(((Cn - Ln) - (Hn - Cn)) / (Hn - Ln)) * V] / SUM(Vn)
[ "Chaikin", "Money", "Flow", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/chaikin_money_flow.py#L8-L28
train
229,249
kylejusticemagnuson/pyti
pyti/hull_moving_average.py
hull_moving_average
def hull_moving_average(data, period): """ Hull Moving Average. Formula: HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n) """ catch_errors.check_for_period_error(data, period) hma = wma( 2 * wma(data, int(period/2)) - wma(data, period), int(np.sqrt(period)) ) return hma
python
def hull_moving_average(data, period): """ Hull Moving Average. Formula: HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n) """ catch_errors.check_for_period_error(data, period) hma = wma( 2 * wma(data, int(period/2)) - wma(data, period), int(np.sqrt(period)) ) return hma
[ "def", "hull_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "hma", "=", "wma", "(", "2", "*", "wma", "(", "data", ",", "int", "(", "period", "/", "2", ")", ")", "...
Hull Moving Average. Formula: HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n)
[ "Hull", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/hull_moving_average.py#L9-L20
train
229,250
kylejusticemagnuson/pyti
pyti/standard_variance.py
standard_variance
def standard_variance(data, period): """ Standard Variance. Formula: (Ct - AVGt)^2 / N """ catch_errors.check_for_period_error(data, period) sv = [np.var(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))] sv = fill_for_noncomputable_vals(data, sv) return sv
python
def standard_variance(data, period): """ Standard Variance. Formula: (Ct - AVGt)^2 / N """ catch_errors.check_for_period_error(data, period) sv = [np.var(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))] sv = fill_for_noncomputable_vals(data, sv) return sv
[ "def", "standard_variance", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "sv", "=", "[", "np", ".", "var", "(", "data", "[", "idx", "+", "1", "-", "period", ":", "idx", "+", "1"...
Standard Variance. Formula: (Ct - AVGt)^2 / N
[ "Standard", "Variance", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/standard_variance.py#L8-L19
train
229,251
kylejusticemagnuson/pyti
pyti/directional_indicators.py
calculate_up_moves
def calculate_up_moves(high_data): """ Up Move. Formula: UPMOVE = Ht - Ht-1 """ up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))] return [np.nan] + up_moves
python
def calculate_up_moves(high_data): """ Up Move. Formula: UPMOVE = Ht - Ht-1 """ up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))] return [np.nan] + up_moves
[ "def", "calculate_up_moves", "(", "high_data", ")", ":", "up_moves", "=", "[", "high_data", "[", "idx", "]", "-", "high_data", "[", "idx", "-", "1", "]", "for", "idx", "in", "range", "(", "1", ",", "len", "(", "high_data", ")", ")", "]", "return", ...
Up Move. Formula: UPMOVE = Ht - Ht-1
[ "Up", "Move", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/directional_indicators.py#L13-L21
train
229,252
kylejusticemagnuson/pyti
pyti/directional_indicators.py
calculate_down_moves
def calculate_down_moves(low_data): """ Down Move. Formula: DWNMOVE = Lt-1 - Lt """ down_moves = [low_data[idx-1] - low_data[idx] for idx in range(1, len(low_data))] return [np.nan] + down_moves
python
def calculate_down_moves(low_data): """ Down Move. Formula: DWNMOVE = Lt-1 - Lt """ down_moves = [low_data[idx-1] - low_data[idx] for idx in range(1, len(low_data))] return [np.nan] + down_moves
[ "def", "calculate_down_moves", "(", "low_data", ")", ":", "down_moves", "=", "[", "low_data", "[", "idx", "-", "1", "]", "-", "low_data", "[", "idx", "]", "for", "idx", "in", "range", "(", "1", ",", "len", "(", "low_data", ")", ")", "]", "return", ...
Down Move. Formula: DWNMOVE = Lt-1 - Lt
[ "Down", "Move", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/directional_indicators.py#L24-L32
train
229,253
kylejusticemagnuson/pyti
pyti/directional_indicators.py
average_directional_index
def average_directional_index(close_data, high_data, low_data, period): """ Average Directional Index. Formula: ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI))) """ avg_di = (abs( (positive_directional_index( close_data, high_data, low_data, period) - negative_directional_index( close_data, high_data, low_data, period)) / (positive_directional_index( close_data, high_data, low_data, period) + negative_directional_index( close_data, high_data, low_data, period))) ) adx = 100 * smma(avg_di, period) return adx
python
def average_directional_index(close_data, high_data, low_data, period): """ Average Directional Index. Formula: ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI))) """ avg_di = (abs( (positive_directional_index( close_data, high_data, low_data, period) - negative_directional_index( close_data, high_data, low_data, period)) / (positive_directional_index( close_data, high_data, low_data, period) + negative_directional_index( close_data, high_data, low_data, period))) ) adx = 100 * smma(avg_di, period) return adx
[ "def", "average_directional_index", "(", "close_data", ",", "high_data", ",", "low_data", ",", "period", ")", ":", "avg_di", "=", "(", "abs", "(", "(", "positive_directional_index", "(", "close_data", ",", "high_data", ",", "low_data", ",", "period", ")", "-",...
Average Directional Index. Formula: ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI)))
[ "Average", "Directional", "Index", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/directional_indicators.py#L107-L125
train
229,254
kylejusticemagnuson/pyti
pyti/linear_weighted_moving_average.py
linear_weighted_moving_average
def linear_weighted_moving_average(data, period): """ Linear Weighted Moving Average. Formula: LWMA = SUM(DATA[i]) * i / SUM(i) """ catch_errors.check_for_period_error(data, period) idx_period = list(range(1, period+1)) lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)] for i in data[idx-(period-1):idx+1]])) / sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))] lwma = fill_for_noncomputable_vals(data, lwma) return lwma
python
def linear_weighted_moving_average(data, period): """ Linear Weighted Moving Average. Formula: LWMA = SUM(DATA[i]) * i / SUM(i) """ catch_errors.check_for_period_error(data, period) idx_period = list(range(1, period+1)) lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)] for i in data[idx-(period-1):idx+1]])) / sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))] lwma = fill_for_noncomputable_vals(data, lwma) return lwma
[ "def", "linear_weighted_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "idx_period", "=", "list", "(", "range", "(", "1", ",", "period", "+", "1", ")", ")", "lwma", "="...
Linear Weighted Moving Average. Formula: LWMA = SUM(DATA[i]) * i / SUM(i)
[ "Linear", "Weighted", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/linear_weighted_moving_average.py#L7-L21
train
229,255
kylejusticemagnuson/pyti
pyti/volume_oscillator.py
volume_oscillator
def volume_oscillator(volume, short_period, long_period): """ Volume Oscillator. Formula: vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long)) """ catch_errors.check_for_period_error(volume, short_period) catch_errors.check_for_period_error(volume, long_period) vo = (100 * ((sma(volume, short_period) - sma(volume, long_period)) / sma(volume, long_period))) return vo
python
def volume_oscillator(volume, short_period, long_period): """ Volume Oscillator. Formula: vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long)) """ catch_errors.check_for_period_error(volume, short_period) catch_errors.check_for_period_error(volume, long_period) vo = (100 * ((sma(volume, short_period) - sma(volume, long_period)) / sma(volume, long_period))) return vo
[ "def", "volume_oscillator", "(", "volume", ",", "short_period", ",", "long_period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "volume", ",", "short_period", ")", "catch_errors", ".", "check_for_period_error", "(", "volume", ",", "long_period", ")...
Volume Oscillator. Formula: vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long))
[ "Volume", "Oscillator", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/volume_oscillator.py#L6-L18
train
229,256
kylejusticemagnuson/pyti
pyti/triple_exponential_moving_average.py
triple_exponential_moving_average
def triple_exponential_moving_average(data, period): """ Triple Exponential Moving Average. Formula: TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA)) """ catch_errors.check_for_period_error(data, period) tema = ((3 * ema(data, period) - (3 * ema(ema(data, period), period))) + ema(ema(ema(data, period), period), period) ) return tema
python
def triple_exponential_moving_average(data, period): """ Triple Exponential Moving Average. Formula: TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA)) """ catch_errors.check_for_period_error(data, period) tema = ((3 * ema(data, period) - (3 * ema(ema(data, period), period))) + ema(ema(ema(data, period), period), period) ) return tema
[ "def", "triple_exponential_moving_average", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "tema", "=", "(", "(", "3", "*", "ema", "(", "data", ",", "period", ")", "-", "(", "3", "*",...
Triple Exponential Moving Average. Formula: TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA))
[ "Triple", "Exponential", "Moving", "Average", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/triple_exponential_moving_average.py#L8-L20
train
229,257
kylejusticemagnuson/pyti
pyti/money_flow.py
money_flow
def money_flow(close_data, high_data, low_data, volume): """ Money Flow. Formula: MF = VOLUME * TYPICAL PRICE """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) mf = volume * tp(close_data, high_data, low_data) return mf
python
def money_flow(close_data, high_data, low_data, volume): """ Money Flow. Formula: MF = VOLUME * TYPICAL PRICE """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) mf = volume * tp(close_data, high_data, low_data) return mf
[ "def", "money_flow", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ")", "mf", "=", "volume", "*", "tp", "("...
Money Flow. Formula: MF = VOLUME * TYPICAL PRICE
[ "Money", "Flow", "." ]
2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2
https://github.com/kylejusticemagnuson/pyti/blob/2f78430dfd60a0d20f4e7fc0cb4588c03107c4b2/pyti/money_flow.py#L6-L17
train
229,258
mrooney/mintapi
mintapi/api.py
Mint.request_and_check
def request_and_check(self, url, method='get', expected_content_type=None, **kwargs): """Performs a request, and checks that the status is OK, and that the content-type matches expectations. Args: url: URL to request method: either 'get' or 'post' expected_content_type: prefix to match response content-type against **kwargs: passed to the request method directly. Raises: RuntimeError if status_code does not match. """ assert method in ['get', 'post'] result = self.driver.request(method, url, **kwargs) if result.status_code != requests.codes.ok: raise RuntimeError('Error requesting %r, status = %d' % (url, result.status_code)) if expected_content_type is not None: content_type = result.headers.get('content-type', '') if not re.match(expected_content_type, content_type): raise RuntimeError( 'Error requesting %r, content type %r does not match %r' % (url, content_type, expected_content_type)) return result
python
def request_and_check(self, url, method='get', expected_content_type=None, **kwargs): """Performs a request, and checks that the status is OK, and that the content-type matches expectations. Args: url: URL to request method: either 'get' or 'post' expected_content_type: prefix to match response content-type against **kwargs: passed to the request method directly. Raises: RuntimeError if status_code does not match. """ assert method in ['get', 'post'] result = self.driver.request(method, url, **kwargs) if result.status_code != requests.codes.ok: raise RuntimeError('Error requesting %r, status = %d' % (url, result.status_code)) if expected_content_type is not None: content_type = result.headers.get('content-type', '') if not re.match(expected_content_type, content_type): raise RuntimeError( 'Error requesting %r, content type %r does not match %r' % (url, content_type, expected_content_type)) return result
[ "def", "request_and_check", "(", "self", ",", "url", ",", "method", "=", "'get'", ",", "expected_content_type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "method", "in", "[", "'get'", ",", "'post'", "]", "result", "=", "self", ".", "dri...
Performs a request, and checks that the status is OK, and that the content-type matches expectations. Args: url: URL to request method: either 'get' or 'post' expected_content_type: prefix to match response content-type against **kwargs: passed to the request method directly. Raises: RuntimeError if status_code does not match.
[ "Performs", "a", "request", "and", "checks", "that", "the", "status", "is", "OK", "and", "that", "the", "content", "-", "type", "matches", "expectations", "." ]
44fddbeac79a68da657ad8118e02fcde968f8dfe
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L394-L419
train
229,259
mrooney/mintapi
mintapi/api.py
Mint.get_transactions_json
def get_transactions_json(self, include_investment=False, skip_duplicates=False, start_date=None, id=0): """Returns the raw JSON transaction data as downloaded from Mint. The JSON transaction data includes some additional information missing from the CSV data, such as whether the transaction is pending or completed, but leaves off the year for current year transactions. Warning: In order to reliably include or exclude duplicates, it is necessary to change the user account property 'hide_duplicates' to the appropriate value. This affects what is displayed in the web interface. Note that the CSV transactions never exclude duplicates. """ # Warning: This is a global property for the user that we are changing. self.set_user_property( 'hide_duplicates', 'T' if skip_duplicates else 'F') # Converts the start date into datetime format - must be mm/dd/yy try: start_date = datetime.strptime(start_date, '%m/%d/%y') except (TypeError, ValueError): start_date = None all_txns = [] offset = 0 # Mint only returns some of the transactions at once. To get all of # them, we have to keep asking for more until we reach the end. while 1: url = MINT_ROOT_URL + '/getJsonData.xevent' params = { 'queryNew': '', 'offset': offset, 'comparableType': '8', 'rnd': Mint.get_rnd(), } # Specifying accountId=0 causes Mint to return investment # transactions as well. Otherwise they are skipped by # default. if id > 0 or include_investment: params['id'] = id if include_investment: params['task'] = 'transactions' else: params['task'] = 'transactions,txnfilters' params['filterType'] = 'cash' result = self.request_and_check( url, headers=JSON_HEADER, params=params, expected_content_type='text/json|application/json') data = json.loads(result.text) txns = data['set'][0].get('data', []) if not txns: break if start_date: last_dt = json_date_to_datetime(txns[-1]['odate']) if last_dt < start_date: keep_txns = [ t for t in txns if json_date_to_datetime(t['odate']) >= start_date] all_txns.extend(keep_txns) break all_txns.extend(txns) offset += len(txns) return all_txns
python
def get_transactions_json(self, include_investment=False, skip_duplicates=False, start_date=None, id=0): """Returns the raw JSON transaction data as downloaded from Mint. The JSON transaction data includes some additional information missing from the CSV data, such as whether the transaction is pending or completed, but leaves off the year for current year transactions. Warning: In order to reliably include or exclude duplicates, it is necessary to change the user account property 'hide_duplicates' to the appropriate value. This affects what is displayed in the web interface. Note that the CSV transactions never exclude duplicates. """ # Warning: This is a global property for the user that we are changing. self.set_user_property( 'hide_duplicates', 'T' if skip_duplicates else 'F') # Converts the start date into datetime format - must be mm/dd/yy try: start_date = datetime.strptime(start_date, '%m/%d/%y') except (TypeError, ValueError): start_date = None all_txns = [] offset = 0 # Mint only returns some of the transactions at once. To get all of # them, we have to keep asking for more until we reach the end. while 1: url = MINT_ROOT_URL + '/getJsonData.xevent' params = { 'queryNew': '', 'offset': offset, 'comparableType': '8', 'rnd': Mint.get_rnd(), } # Specifying accountId=0 causes Mint to return investment # transactions as well. Otherwise they are skipped by # default. if id > 0 or include_investment: params['id'] = id if include_investment: params['task'] = 'transactions' else: params['task'] = 'transactions,txnfilters' params['filterType'] = 'cash' result = self.request_and_check( url, headers=JSON_HEADER, params=params, expected_content_type='text/json|application/json') data = json.loads(result.text) txns = data['set'][0].get('data', []) if not txns: break if start_date: last_dt = json_date_to_datetime(txns[-1]['odate']) if last_dt < start_date: keep_txns = [ t for t in txns if json_date_to_datetime(t['odate']) >= start_date] all_txns.extend(keep_txns) break all_txns.extend(txns) offset += len(txns) return all_txns
[ "def", "get_transactions_json", "(", "self", ",", "include_investment", "=", "False", ",", "skip_duplicates", "=", "False", ",", "start_date", "=", "None", ",", "id", "=", "0", ")", ":", "# Warning: This is a global property for the user that we are changing.", "self", ...
Returns the raw JSON transaction data as downloaded from Mint. The JSON transaction data includes some additional information missing from the CSV data, such as whether the transaction is pending or completed, but leaves off the year for current year transactions. Warning: In order to reliably include or exclude duplicates, it is necessary to change the user account property 'hide_duplicates' to the appropriate value. This affects what is displayed in the web interface. Note that the CSV transactions never exclude duplicates.
[ "Returns", "the", "raw", "JSON", "transaction", "data", "as", "downloaded", "from", "Mint", ".", "The", "JSON", "transaction", "data", "includes", "some", "additional", "information", "missing", "from", "the", "CSV", "data", "such", "as", "whether", "the", "tr...
44fddbeac79a68da657ad8118e02fcde968f8dfe
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L533-L594
train
229,260
mrooney/mintapi
mintapi/api.py
Mint.get_detailed_transactions
def get_detailed_transactions(self, include_investment=False, skip_duplicates=False, remove_pending=True, start_date=None): """Returns the JSON transaction data as a DataFrame, and converts current year dates and prior year dates into consistent datetime format, and reverses credit activity. Note: start_date must be in format mm/dd/yy. If pulls take too long, use a more recent start date. See json explanations of include_investment and skip_duplicates. Also note: Mint includes pending transactions, however these sometimes change dates/amounts after the transactions post. They have been removed by default in this pull, but can be included by changing remove_pending to False """ assert_pd() result = self.get_transactions_json(include_investment, skip_duplicates, start_date) df = pd.DataFrame(result) df['odate'] = df['odate'].apply(json_date_to_datetime) if remove_pending: df = df[~df.isPending] df.reset_index(drop=True, inplace=True) df.amount = df.apply(reverse_credit_amount, axis=1) return df
python
def get_detailed_transactions(self, include_investment=False, skip_duplicates=False, remove_pending=True, start_date=None): """Returns the JSON transaction data as a DataFrame, and converts current year dates and prior year dates into consistent datetime format, and reverses credit activity. Note: start_date must be in format mm/dd/yy. If pulls take too long, use a more recent start date. See json explanations of include_investment and skip_duplicates. Also note: Mint includes pending transactions, however these sometimes change dates/amounts after the transactions post. They have been removed by default in this pull, but can be included by changing remove_pending to False """ assert_pd() result = self.get_transactions_json(include_investment, skip_duplicates, start_date) df = pd.DataFrame(result) df['odate'] = df['odate'].apply(json_date_to_datetime) if remove_pending: df = df[~df.isPending] df.reset_index(drop=True, inplace=True) df.amount = df.apply(reverse_credit_amount, axis=1) return df
[ "def", "get_detailed_transactions", "(", "self", ",", "include_investment", "=", "False", ",", "skip_duplicates", "=", "False", ",", "remove_pending", "=", "True", ",", "start_date", "=", "None", ")", ":", "assert_pd", "(", ")", "result", "=", "self", ".", "...
Returns the JSON transaction data as a DataFrame, and converts current year dates and prior year dates into consistent datetime format, and reverses credit activity. Note: start_date must be in format mm/dd/yy. If pulls take too long, use a more recent start date. See json explanations of include_investment and skip_duplicates. Also note: Mint includes pending transactions, however these sometimes change dates/amounts after the transactions post. They have been removed by default in this pull, but can be included by changing remove_pending to False
[ "Returns", "the", "JSON", "transaction", "data", "as", "a", "DataFrame", "and", "converts", "current", "year", "dates", "and", "prior", "year", "dates", "into", "consistent", "datetime", "format", "and", "reverses", "credit", "activity", "." ]
44fddbeac79a68da657ad8118e02fcde968f8dfe
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L596-L627
train
229,261
mrooney/mintapi
mintapi/api.py
Mint.get_transactions_csv
def get_transactions_csv(self, include_investment=False, acct=0): """Returns the raw CSV transaction data as downloaded from Mint. If include_investment == True, also includes transactions that Mint classifies as investment-related. You may find that the investment transaction data is not sufficiently detailed to actually be useful, however. """ # Specifying accountId=0 causes Mint to return investment # transactions as well. Otherwise they are skipped by # default. params = None if include_investment or acct > 0: params = {'accountId': acct} result = self.request_and_check( '{}/transactionDownload.event'.format(MINT_ROOT_URL), params=params, expected_content_type='text/csv') return result.content
python
def get_transactions_csv(self, include_investment=False, acct=0): """Returns the raw CSV transaction data as downloaded from Mint. If include_investment == True, also includes transactions that Mint classifies as investment-related. You may find that the investment transaction data is not sufficiently detailed to actually be useful, however. """ # Specifying accountId=0 causes Mint to return investment # transactions as well. Otherwise they are skipped by # default. params = None if include_investment or acct > 0: params = {'accountId': acct} result = self.request_and_check( '{}/transactionDownload.event'.format(MINT_ROOT_URL), params=params, expected_content_type='text/csv') return result.content
[ "def", "get_transactions_csv", "(", "self", ",", "include_investment", "=", "False", ",", "acct", "=", "0", ")", ":", "# Specifying accountId=0 causes Mint to return investment", "# transactions as well. Otherwise they are skipped by", "# default.", "params", "=", "None", "i...
Returns the raw CSV transaction data as downloaded from Mint. If include_investment == True, also includes transactions that Mint classifies as investment-related. You may find that the investment transaction data is not sufficiently detailed to actually be useful, however.
[ "Returns", "the", "raw", "CSV", "transaction", "data", "as", "downloaded", "from", "Mint", "." ]
44fddbeac79a68da657ad8118e02fcde968f8dfe
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L629-L648
train
229,262
mrooney/mintapi
mintapi/api.py
Mint.get_transactions
def get_transactions(self, include_investment=False): """Returns the transaction data as a Pandas DataFrame.""" assert_pd() s = StringIO(self.get_transactions_csv( include_investment=include_investment)) s.seek(0) df = pd.read_csv(s, parse_dates=['Date']) df.columns = [c.lower().replace(' ', '_') for c in df.columns] df.category = (df.category.str.lower() .replace('uncategorized', pd.np.nan)) return df
python
def get_transactions(self, include_investment=False): """Returns the transaction data as a Pandas DataFrame.""" assert_pd() s = StringIO(self.get_transactions_csv( include_investment=include_investment)) s.seek(0) df = pd.read_csv(s, parse_dates=['Date']) df.columns = [c.lower().replace(' ', '_') for c in df.columns] df.category = (df.category.str.lower() .replace('uncategorized', pd.np.nan)) return df
[ "def", "get_transactions", "(", "self", ",", "include_investment", "=", "False", ")", ":", "assert_pd", "(", ")", "s", "=", "StringIO", "(", "self", ".", "get_transactions_csv", "(", "include_investment", "=", "include_investment", ")", ")", "s", ".", "seek", ...
Returns the transaction data as a Pandas DataFrame.
[ "Returns", "the", "transaction", "data", "as", "a", "Pandas", "DataFrame", "." ]
44fddbeac79a68da657ad8118e02fcde968f8dfe
https://github.com/mrooney/mintapi/blob/44fddbeac79a68da657ad8118e02fcde968f8dfe/mintapi/api.py#L662-L672
train
229,263
StellarCN/py-stellar-base
stellar_base/address.py
Address.payments
def payments(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the payments JSON from this instance's Horizon server. Retrieve the payments JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_payments(address=self.address, cursor=cursor, order=order, limit=limit, sse=sse)
python
def payments(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the payments JSON from this instance's Horizon server. Retrieve the payments JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_payments(address=self.address, cursor=cursor, order=order, limit=limit, sse=sse)
[ "def", "payments", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "return", "self", ".", "horizon", ".", "account_payments", "(", "address", "=", "self", ".", "address...
Retrieve the payments JSON from this instance's Horizon server. Retrieve the payments JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses.
[ "Retrieve", "the", "payments", "JSON", "from", "this", "instance", "s", "Horizon", "server", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L95-L109
train
229,264
StellarCN/py-stellar-base
stellar_base/address.py
Address.offers
def offers(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the offers JSON from this instance's Horizon server. Retrieve the offers JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_offers(self.address, cursor=cursor, order=order, limit=limit, sse=sse)
python
def offers(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the offers JSON from this instance's Horizon server. Retrieve the offers JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_offers(self.address, cursor=cursor, order=order, limit=limit, sse=sse)
[ "def", "offers", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "return", "self", ".", "horizon", ".", "account_offers", "(", "self", ".", "address", ",", "cursor", ...
Retrieve the offers JSON from this instance's Horizon server. Retrieve the offers JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses.
[ "Retrieve", "the", "offers", "JSON", "from", "this", "instance", "s", "Horizon", "server", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L111-L125
train
229,265
StellarCN/py-stellar-base
stellar_base/address.py
Address.transactions
def transactions(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the transactions JSON from this instance's Horizon server. Retrieve the transactions JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_transactions( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
python
def transactions(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the transactions JSON from this instance's Horizon server. Retrieve the transactions JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_transactions( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
[ "def", "transactions", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "return", "self", ".", "horizon", ".", "account_transactions", "(", "self", ".", "address", ",", ...
Retrieve the transactions JSON from this instance's Horizon server. Retrieve the transactions JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses.
[ "Retrieve", "the", "transactions", "JSON", "from", "this", "instance", "s", "Horizon", "server", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L127-L141
train
229,266
StellarCN/py-stellar-base
stellar_base/address.py
Address.operations
def operations(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the operations JSON from this instance's Horizon server. Retrieve the operations JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_operations( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
python
def operations(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the operations JSON from this instance's Horizon server. Retrieve the operations JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_operations( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
[ "def", "operations", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "return", "self", ".", "horizon", ".", "account_operations", "(", "self", ".", "address", ",", "cur...
Retrieve the operations JSON from this instance's Horizon server. Retrieve the operations JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon.
[ "Retrieve", "the", "operations", "JSON", "from", "this", "instance", "s", "Horizon", "server", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L143-L158
train
229,267
StellarCN/py-stellar-base
stellar_base/address.py
Address.trades
def trades(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the trades JSON from this instance's Horizon server. Retrieve the trades JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_trades( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
python
def trades(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the trades JSON from this instance's Horizon server. Retrieve the trades JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_trades( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
[ "def", "trades", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "return", "self", ".", "horizon", ".", "account_trades", "(", "self", ".", "address", ",", "cursor", ...
Retrieve the trades JSON from this instance's Horizon server. Retrieve the trades JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon.
[ "Retrieve", "the", "trades", "JSON", "from", "this", "instance", "s", "Horizon", "server", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L160-L174
train
229,268
StellarCN/py-stellar-base
stellar_base/address.py
Address.effects
def effects(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the effects JSON from this instance's Horizon server. Retrieve the effects JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_effects( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
python
def effects(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the effects JSON from this instance's Horizon server. Retrieve the effects JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_effects( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
[ "def", "effects", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "return", "self", ".", "horizon", ".", "account_effects", "(", "self", ".", "address", ",", "cursor", ...
Retrieve the effects JSON from this instance's Horizon server. Retrieve the effects JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon.
[ "Retrieve", "the", "effects", "JSON", "from", "this", "instance", "s", "Horizon", "server", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/address.py#L176-L191
train
229,269
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.submit
def submit(self, te): """Submit the transaction using a pooled connection, and retry on failure. `POST /transactions <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_ Uses form-encoded data to send over to Horizon. :return: The JSON response indicating the success/failure of the submitted transaction. :rtype: dict """ params = {'tx': te} url = urljoin(self.horizon_uri, 'transactions/') # POST is not included in Retry's method_whitelist for a good reason. # our custom retry mechanism follows reply = None retry_count = self.num_retries while True: try: reply = self._session.post( url, data=params, timeout=self.request_timeout) return check_horizon_reply(reply.json()) except (RequestException, NewConnectionError, ValueError) as e: if reply is not None: msg = 'Horizon submit exception: {}, reply: [{}] {}'.format( str(e), reply.status_code, reply.text) else: msg = 'Horizon submit exception: {}'.format(str(e)) logging.warning(msg) if (reply is not None and reply.status_code not in self.status_forcelist) or retry_count <= 0: if reply is None: raise HorizonRequestError(e) raise HorizonError('Invalid horizon reply: [{}] {}'.format( reply.status_code, reply.text), reply.status_code) retry_count -= 1 logging.warning('Submit retry attempt {}'.format(retry_count)) sleep(self.backoff_factor)
python
def submit(self, te): """Submit the transaction using a pooled connection, and retry on failure. `POST /transactions <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_ Uses form-encoded data to send over to Horizon. :return: The JSON response indicating the success/failure of the submitted transaction. :rtype: dict """ params = {'tx': te} url = urljoin(self.horizon_uri, 'transactions/') # POST is not included in Retry's method_whitelist for a good reason. # our custom retry mechanism follows reply = None retry_count = self.num_retries while True: try: reply = self._session.post( url, data=params, timeout=self.request_timeout) return check_horizon_reply(reply.json()) except (RequestException, NewConnectionError, ValueError) as e: if reply is not None: msg = 'Horizon submit exception: {}, reply: [{}] {}'.format( str(e), reply.status_code, reply.text) else: msg = 'Horizon submit exception: {}'.format(str(e)) logging.warning(msg) if (reply is not None and reply.status_code not in self.status_forcelist) or retry_count <= 0: if reply is None: raise HorizonRequestError(e) raise HorizonError('Invalid horizon reply: [{}] {}'.format( reply.status_code, reply.text), reply.status_code) retry_count -= 1 logging.warning('Submit retry attempt {}'.format(retry_count)) sleep(self.backoff_factor)
[ "def", "submit", "(", "self", ",", "te", ")", ":", "params", "=", "{", "'tx'", ":", "te", "}", "url", "=", "urljoin", "(", "self", ".", "horizon_uri", ",", "'transactions/'", ")", "# POST is not included in Retry's method_whitelist for a good reason.", "# our cust...
Submit the transaction using a pooled connection, and retry on failure. `POST /transactions <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_ Uses form-encoded data to send over to Horizon. :return: The JSON response indicating the success/failure of the submitted transaction. :rtype: dict
[ "Submit", "the", "transaction", "using", "a", "pooled", "connection", "and", "retry", "on", "failure", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L118-L158
train
229,270
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.account
def account(self, address): """Returns information and links relating to a single account. `GET /accounts/{account} <https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_ :param str address: The account ID to retrieve details about. :return: The account details in a JSON response. :rtype: dict """ endpoint = '/accounts/{account_id}'.format(account_id=address) return self.query(endpoint)
python
def account(self, address): """Returns information and links relating to a single account. `GET /accounts/{account} <https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_ :param str address: The account ID to retrieve details about. :return: The account details in a JSON response. :rtype: dict """ endpoint = '/accounts/{account_id}'.format(account_id=address) return self.query(endpoint)
[ "def", "account", "(", "self", ",", "address", ")", ":", "endpoint", "=", "'/accounts/{account_id}'", ".", "format", "(", "account_id", "=", "address", ")", "return", "self", ".", "query", "(", "endpoint", ")" ]
Returns information and links relating to a single account. `GET /accounts/{account} <https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_ :param str address: The account ID to retrieve details about. :return: The account details in a JSON response. :rtype: dict
[ "Returns", "information", "and", "links", "relating", "to", "a", "single", "account", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L188-L200
train
229,271
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.account_data
def account_data(self, address, key): """This endpoint represents a single data associated with a given account. `GET /accounts/{account}/data/{key} <https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_ :param str address: The account ID to look up a data item from. :param str key: The name of the key for the data item in question. :return: The value of the data field for the given account and data key. :rtype: dict """ endpoint = '/accounts/{account_id}/data/{data_key}'.format( account_id=address, data_key=key) return self.query(endpoint)
python
def account_data(self, address, key): """This endpoint represents a single data associated with a given account. `GET /accounts/{account}/data/{key} <https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_ :param str address: The account ID to look up a data item from. :param str key: The name of the key for the data item in question. :return: The value of the data field for the given account and data key. :rtype: dict """ endpoint = '/accounts/{account_id}/data/{data_key}'.format( account_id=address, data_key=key) return self.query(endpoint)
[ "def", "account_data", "(", "self", ",", "address", ",", "key", ")", ":", "endpoint", "=", "'/accounts/{account_id}/data/{data_key}'", ".", "format", "(", "account_id", "=", "address", ",", "data_key", "=", "key", ")", "return", "self", ".", "query", "(", "e...
This endpoint represents a single data associated with a given account. `GET /accounts/{account}/data/{key} <https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_ :param str address: The account ID to look up a data item from. :param str key: The name of the key for the data item in question. :return: The value of the data field for the given account and data key. :rtype: dict
[ "This", "endpoint", "represents", "a", "single", "data", "associated", "with", "a", "given", "account", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L202-L217
train
229,272
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.account_effects
def account_effects(self, address, cursor=None, order='asc', limit=10, sse=False): """This endpoint represents all effects that changed a given account. `GET /accounts/{account}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_ :param str address: The account ID to look up effects for. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: The list of effects in a JSON response. :rtype: dict """ endpoint = '/accounts/{account_id}/effects'.format(account_id=address) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params, sse)
python
def account_effects(self, address, cursor=None, order='asc', limit=10, sse=False): """This endpoint represents all effects that changed a given account. `GET /accounts/{account}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_ :param str address: The account ID to look up effects for. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: The list of effects in a JSON response. :rtype: dict """ endpoint = '/accounts/{account_id}/effects'.format(account_id=address) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params, sse)
[ "def", "account_effects", "(", "self", ",", "address", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "endpoint", "=", "'/accounts/{account_id}/effects'", ".", "format", "(", "account_id...
This endpoint represents all effects that changed a given account. `GET /accounts/{account}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_ :param str address: The account ID to look up effects for. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: The list of effects in a JSON response. :rtype: dict
[ "This", "endpoint", "represents", "all", "effects", "that", "changed", "a", "given", "account", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L219-L238
train
229,273
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.assets
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10): """This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets{?asset_code,asset_issuer,cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_ :param str asset_code: Code of the Asset to filter by. :param str asset_issuer: Issuer of the Asset to filter by. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc", ordered by asset_code then by asset_issuer. :param int limit: Maximum number of records to return. :return: A list of all valid payment operations :rtype: dict """ endpoint = '/assets' params = self.__query_params(asset_code=asset_code, asset_issuer=asset_issuer, cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
python
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10): """This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets{?asset_code,asset_issuer,cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_ :param str asset_code: Code of the Asset to filter by. :param str asset_issuer: Issuer of the Asset to filter by. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc", ordered by asset_code then by asset_issuer. :param int limit: Maximum number of records to return. :return: A list of all valid payment operations :rtype: dict """ endpoint = '/assets' params = self.__query_params(asset_code=asset_code, asset_issuer=asset_issuer, cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
[ "def", "assets", "(", "self", ",", "asset_code", "=", "None", ",", "asset_issuer", "=", "None", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/assets'", "params", "=", "self", ".", "__qu...
This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets{?asset_code,asset_issuer,cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_ :param str asset_code: Code of the Asset to filter by. :param str asset_issuer: Issuer of the Asset to filter by. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc", ordered by asset_code then by asset_issuer. :param int limit: Maximum number of records to return. :return: A list of all valid payment operations :rtype: dict
[ "This", "endpoint", "represents", "all", "assets", ".", "It", "will", "give", "you", "all", "the", "assets", "in", "the", "system", "along", "with", "various", "statistics", "about", "each", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L352-L376
train
229,274
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.transaction
def transaction(self, tx_hash): """The transaction details endpoint provides information on a single transaction. `GET /transactions/{hash} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_ :param str tx_hash: The hex-encoded transaction hash. :return: A single transaction's details. :rtype: dict """ endpoint = '/transactions/{tx_hash}'.format(tx_hash=tx_hash) return self.query(endpoint)
python
def transaction(self, tx_hash): """The transaction details endpoint provides information on a single transaction. `GET /transactions/{hash} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_ :param str tx_hash: The hex-encoded transaction hash. :return: A single transaction's details. :rtype: dict """ endpoint = '/transactions/{tx_hash}'.format(tx_hash=tx_hash) return self.query(endpoint)
[ "def", "transaction", "(", "self", ",", "tx_hash", ")", ":", "endpoint", "=", "'/transactions/{tx_hash}'", ".", "format", "(", "tx_hash", "=", "tx_hash", ")", "return", "self", ".", "query", "(", "endpoint", ")" ]
The transaction details endpoint provides information on a single transaction. `GET /transactions/{hash} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_ :param str tx_hash: The hex-encoded transaction hash. :return: A single transaction's details. :rtype: dict
[ "The", "transaction", "details", "endpoint", "provides", "information", "on", "a", "single", "transaction", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L399-L412
train
229,275
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.transaction_operations
def transaction_operations(self, tx_hash, cursor=None, order='asc', include_failed=False, limit=10): """This endpoint represents all operations that are part of a given transaction. `GET /transactions/{hash}/operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :return: A single transaction's operations. :rtype: dict """ endpoint = '/transactions/{tx_hash}/operations'.format(tx_hash=tx_hash) params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params)
python
def transaction_operations(self, tx_hash, cursor=None, order='asc', include_failed=False, limit=10): """This endpoint represents all operations that are part of a given transaction. `GET /transactions/{hash}/operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :return: A single transaction's operations. :rtype: dict """ endpoint = '/transactions/{tx_hash}/operations'.format(tx_hash=tx_hash) params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params)
[ "def", "transaction_operations", "(", "self", ",", "tx_hash", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "include_failed", "=", "False", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/transactions/{tx_hash}/operations'", ".", "format"...
This endpoint represents all operations that are part of a given transaction. `GET /transactions/{hash}/operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :return: A single transaction's operations. :rtype: dict
[ "This", "endpoint", "represents", "all", "operations", "that", "are", "part", "of", "a", "given", "transaction", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L414-L432
train
229,276
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.transaction_effects
def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred as a result of a given transaction. `GET /transactions/{hash}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A single transaction's effects. :rtype: dict """ endpoint = '/transactions/{tx_hash}/effects'.format(tx_hash=tx_hash) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
python
def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred as a result of a given transaction. `GET /transactions/{hash}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A single transaction's effects. :rtype: dict """ endpoint = '/transactions/{tx_hash}/effects'.format(tx_hash=tx_hash) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
[ "def", "transaction_effects", "(", "self", ",", "tx_hash", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/transactions/{tx_hash}/effects'", ".", "format", "(", "tx_hash", "=", "tx_hash", ")", ...
This endpoint represents all effects that occurred as a result of a given transaction. `GET /transactions/{hash}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A single transaction's effects. :rtype: dict
[ "This", "endpoint", "represents", "all", "effects", "that", "occurred", "as", "a", "result", "of", "a", "given", "transaction", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L434-L451
train
229,277
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.order_book
def order_book(self, selling_asset_code, buying_asset_code, selling_asset_issuer=None, buying_asset_issuer=None, limit=10): """Return, for each orderbook, a summary of the orderbook and the bids and asks associated with that orderbook. See the external docs below for information on the arguments required. `GET /order_book <https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_ :param str selling_asset_code: Code of the Asset being sold. :param str buying_asset_code: Type of the Asset being bought. :param str selling_asset_issuer: Account ID of the issuer of the Asset being sold, if it is a native asset, let it be `None`. :param str buying_asset_issuer: Account ID of the issuer of the Asset being bought, if it is a native asset, let it be `None`. :param int limit: Limit the number of items returned. :return: A list of orderbook summaries as a JSON object. :rtype: dict """ selling_asset = Asset(selling_asset_code, selling_asset_issuer) buying_asset = Asset(buying_asset_code, buying_asset_issuer) asset_params = { 'selling_asset_type': selling_asset.type, 'selling_asset_code': None if selling_asset.is_native() else selling_asset.code, 'selling_asset_issuer': selling_asset.issuer, 'buying_asset_type': buying_asset.type, 'buying_asset_code': None if buying_asset.is_native() else buying_asset.code, 'buying_asset_issuer': buying_asset.issuer, } endpoint = '/order_book' params = self.__query_params(limit=limit, **asset_params) return self.query(endpoint, params)
python
def order_book(self, selling_asset_code, buying_asset_code, selling_asset_issuer=None, buying_asset_issuer=None, limit=10): """Return, for each orderbook, a summary of the orderbook and the bids and asks associated with that orderbook. See the external docs below for information on the arguments required. `GET /order_book <https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_ :param str selling_asset_code: Code of the Asset being sold. :param str buying_asset_code: Type of the Asset being bought. :param str selling_asset_issuer: Account ID of the issuer of the Asset being sold, if it is a native asset, let it be `None`. :param str buying_asset_issuer: Account ID of the issuer of the Asset being bought, if it is a native asset, let it be `None`. :param int limit: Limit the number of items returned. :return: A list of orderbook summaries as a JSON object. :rtype: dict """ selling_asset = Asset(selling_asset_code, selling_asset_issuer) buying_asset = Asset(buying_asset_code, buying_asset_issuer) asset_params = { 'selling_asset_type': selling_asset.type, 'selling_asset_code': None if selling_asset.is_native() else selling_asset.code, 'selling_asset_issuer': selling_asset.issuer, 'buying_asset_type': buying_asset.type, 'buying_asset_code': None if buying_asset.is_native() else buying_asset.code, 'buying_asset_issuer': buying_asset.issuer, } endpoint = '/order_book' params = self.__query_params(limit=limit, **asset_params) return self.query(endpoint, params)
[ "def", "order_book", "(", "self", ",", "selling_asset_code", ",", "buying_asset_code", ",", "selling_asset_issuer", "=", "None", ",", "buying_asset_issuer", "=", "None", ",", "limit", "=", "10", ")", ":", "selling_asset", "=", "Asset", "(", "selling_asset_code", ...
Return, for each orderbook, a summary of the orderbook and the bids and asks associated with that orderbook. See the external docs below for information on the arguments required. `GET /order_book <https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_ :param str selling_asset_code: Code of the Asset being sold. :param str buying_asset_code: Type of the Asset being bought. :param str selling_asset_issuer: Account ID of the issuer of the Asset being sold, if it is a native asset, let it be `None`. :param str buying_asset_issuer: Account ID of the issuer of the Asset being bought, if it is a native asset, let it be `None`. :param int limit: Limit the number of items returned. :return: A list of orderbook summaries as a JSON object. :rtype: dict
[ "Return", "for", "each", "orderbook", "a", "summary", "of", "the", "orderbook", "and", "the", "bids", "and", "asks", "associated", "with", "that", "orderbook", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L472-L505
train
229,278
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.ledger
def ledger(self, ledger_id): """The ledger details endpoint provides information on a single ledger. `GET /ledgers/{sequence} <https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_ :param int ledger_id: The id of the ledger to look up. :return: The details of a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}'.format(ledger_id=ledger_id) return self.query(endpoint)
python
def ledger(self, ledger_id): """The ledger details endpoint provides information on a single ledger. `GET /ledgers/{sequence} <https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_ :param int ledger_id: The id of the ledger to look up. :return: The details of a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}'.format(ledger_id=ledger_id) return self.query(endpoint)
[ "def", "ledger", "(", "self", ",", "ledger_id", ")", ":", "endpoint", "=", "'/ledgers/{ledger_id}'", ".", "format", "(", "ledger_id", "=", "ledger_id", ")", "return", "self", ".", "query", "(", "endpoint", ")" ]
The ledger details endpoint provides information on a single ledger. `GET /ledgers/{sequence} <https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_ :param int ledger_id: The id of the ledger to look up. :return: The details of a single ledger. :rtype: dict
[ "The", "ledger", "details", "endpoint", "provides", "information", "on", "a", "single", "ledger", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L527-L539
train
229,279
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.ledger_effects
def ledger_effects(self, ledger_id, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred in the given ledger. `GET /ledgers/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: The effects for a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}/effects'.format(ledger_id=ledger_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
python
def ledger_effects(self, ledger_id, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred in the given ledger. `GET /ledgers/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: The effects for a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}/effects'.format(ledger_id=ledger_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
[ "def", "ledger_effects", "(", "self", ",", "ledger_id", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/ledgers/{ledger_id}/effects'", ".", "format", "(", "ledger_id", "=", "ledger_id", ")", "p...
This endpoint represents all effects that occurred in the given ledger. `GET /ledgers/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: The effects for a single ledger. :rtype: dict
[ "This", "endpoint", "represents", "all", "effects", "that", "occurred", "in", "the", "given", "ledger", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L541-L558
train
229,280
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.ledger_transactions
def ledger_transactions(self, ledger_id, cursor=None, order='asc', include_failed=False, limit=10): """This endpoint represents all transactions in a given ledger. `GET /ledgers/{id}/transactions{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include failed transactions in results. :return: The transactions contained in a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}/transactions'.format( ledger_id=ledger_id) params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params)
python
def ledger_transactions(self, ledger_id, cursor=None, order='asc', include_failed=False, limit=10): """This endpoint represents all transactions in a given ledger. `GET /ledgers/{id}/transactions{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include failed transactions in results. :return: The transactions contained in a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}/transactions'.format( ledger_id=ledger_id) params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params)
[ "def", "ledger_transactions", "(", "self", ",", "ledger_id", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "include_failed", "=", "False", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/ledgers/{ledger_id}/transactions'", ".", "format", ...
This endpoint represents all transactions in a given ledger. `GET /ledgers/{id}/transactions{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include failed transactions in results. :return: The transactions contained in a single ledger. :rtype: dict
[ "This", "endpoint", "represents", "all", "transactions", "in", "a", "given", "ledger", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L600-L618
train
229,281
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.effects
def effects(self, cursor=None, order='asc', limit=10, sse=False): """This endpoint represents all effects. `GET /effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: A list of all effects. :rtype: dict """ endpoint = '/effects' params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params, sse)
python
def effects(self, cursor=None, order='asc', limit=10, sse=False): """This endpoint represents all effects. `GET /effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: A list of all effects. :rtype: dict """ endpoint = '/effects' params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params, sse)
[ "def", "effects", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "sse", "=", "False", ")", ":", "endpoint", "=", "'/effects'", "params", "=", "self", ".", "__query_params", "(", "cursor", "=", "curs...
This endpoint represents all effects. `GET /effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: A list of all effects. :rtype: dict
[ "This", "endpoint", "represents", "all", "effects", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L620-L638
train
229,282
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.operations
def operations(self, cursor=None, order='asc', limit=10, include_failed=False, sse=False): """This endpoint represents all operations that are part of validated transactions. `GET /operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :param bool sse: Use server side events for streaming responses. :return: A list of all operations. :rtype: dict """ endpoint = '/operations' params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params, sse)
python
def operations(self, cursor=None, order='asc', limit=10, include_failed=False, sse=False): """This endpoint represents all operations that are part of validated transactions. `GET /operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :param bool sse: Use server side events for streaming responses. :return: A list of all operations. :rtype: dict """ endpoint = '/operations' params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params, sse)
[ "def", "operations", "(", "self", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ",", "include_failed", "=", "False", ",", "sse", "=", "False", ")", ":", "endpoint", "=", "'/operations'", "params", "=", "self", ".", ...
This endpoint represents all operations that are part of validated transactions. `GET /operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :param bool sse: Use server side events for streaming responses. :return: A list of all operations. :rtype: dict
[ "This", "endpoint", "represents", "all", "operations", "that", "are", "part", "of", "validated", "transactions", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L640-L660
train
229,283
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.operation
def operation(self, op_id): """The operation details endpoint provides information on a single operation. `GET /operations/{id} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_ :param id op_id: The operation ID to get details on. :return: Details on a single operation. :rtype: dict """ endpoint = '/operations/{op_id}'.format(op_id=op_id) return self.query(endpoint)
python
def operation(self, op_id): """The operation details endpoint provides information on a single operation. `GET /operations/{id} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_ :param id op_id: The operation ID to get details on. :return: Details on a single operation. :rtype: dict """ endpoint = '/operations/{op_id}'.format(op_id=op_id) return self.query(endpoint)
[ "def", "operation", "(", "self", ",", "op_id", ")", ":", "endpoint", "=", "'/operations/{op_id}'", ".", "format", "(", "op_id", "=", "op_id", ")", "return", "self", ".", "query", "(", "endpoint", ")" ]
The operation details endpoint provides information on a single operation. `GET /operations/{id} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_ :param id op_id: The operation ID to get details on. :return: Details on a single operation. :rtype: dict
[ "The", "operation", "details", "endpoint", "provides", "information", "on", "a", "single", "operation", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L662-L674
train
229,284
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.operation_effects
def operation_effects(self, op_id, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred as a result of a given operation. `GET /operations/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_ :param int op_id: The operation ID to get effects on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict """ endpoint = '/operations/{op_id}/effects'.format(op_id=op_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
python
def operation_effects(self, op_id, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred as a result of a given operation. `GET /operations/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_ :param int op_id: The operation ID to get effects on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict """ endpoint = '/operations/{op_id}/effects'.format(op_id=op_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
[ "def", "operation_effects", "(", "self", ",", "op_id", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/operations/{op_id}/effects'", ".", "format", "(", "op_id", "=", "op_id", ")", "params", ...
This endpoint represents all effects that occurred as a result of a given operation. `GET /operations/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_ :param int op_id: The operation ID to get effects on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict
[ "This", "endpoint", "represents", "all", "effects", "that", "occurred", "as", "a", "result", "of", "a", "given", "operation", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L676-L693
train
229,285
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.paths
def paths(self, destination_account, destination_amount, source_account, destination_asset_code, destination_asset_issuer=None): """Load a list of assets available to the source account id and find any payment paths from those source assets to the desired destination asset. See the below docs for more information on required and optional parameters for further specifying your search. `GET /paths <https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_ :param str destination_account: The destination account that any returned path should use. :param str destination_amount: The amount, denominated in the destination asset, that any returned path should be able to satisfy. :param str source_account: The sender's account id. Any returned path must use a source that the sender can hold. :param str destination_asset_code: The asset code for the destination. :param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`. :type destination_asset_issuer: str, None :return: A list of paths that can be used to complete a payment based on a given query. :rtype: dict """ destination_asset = Asset(destination_asset_code, destination_asset_issuer) destination_asset_params = { 'destination_asset_type': destination_asset.type, 'destination_asset_code': None if destination_asset.is_native() else destination_asset.code, 'destination_asset_issuer': destination_asset.issuer } endpoint = '/paths' params = self.__query_params(destination_account=destination_account, source_account=source_account, destination_amount=destination_amount, **destination_asset_params ) return self.query(endpoint, params)
python
def paths(self, destination_account, destination_amount, source_account, destination_asset_code, destination_asset_issuer=None): """Load a list of assets available to the source account id and find any payment paths from those source assets to the desired destination asset. See the below docs for more information on required and optional parameters for further specifying your search. `GET /paths <https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_ :param str destination_account: The destination account that any returned path should use. :param str destination_amount: The amount, denominated in the destination asset, that any returned path should be able to satisfy. :param str source_account: The sender's account id. Any returned path must use a source that the sender can hold. :param str destination_asset_code: The asset code for the destination. :param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`. :type destination_asset_issuer: str, None :return: A list of paths that can be used to complete a payment based on a given query. :rtype: dict """ destination_asset = Asset(destination_asset_code, destination_asset_issuer) destination_asset_params = { 'destination_asset_type': destination_asset.type, 'destination_asset_code': None if destination_asset.is_native() else destination_asset.code, 'destination_asset_issuer': destination_asset.issuer } endpoint = '/paths' params = self.__query_params(destination_account=destination_account, source_account=source_account, destination_amount=destination_amount, **destination_asset_params ) return self.query(endpoint, params)
[ "def", "paths", "(", "self", ",", "destination_account", ",", "destination_amount", ",", "source_account", ",", "destination_asset_code", ",", "destination_asset_issuer", "=", "None", ")", ":", "destination_asset", "=", "Asset", "(", "destination_asset_code", ",", "de...
Load a list of assets available to the source account id and find any payment paths from those source assets to the desired destination asset. See the below docs for more information on required and optional parameters for further specifying your search. `GET /paths <https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_ :param str destination_account: The destination account that any returned path should use. :param str destination_amount: The amount, denominated in the destination asset, that any returned path should be able to satisfy. :param str source_account: The sender's account id. Any returned path must use a source that the sender can hold. :param str destination_asset_code: The asset code for the destination. :param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`. :type destination_asset_issuer: str, None :return: A list of paths that can be used to complete a payment based on a given query. :rtype: dict
[ "Load", "a", "list", "of", "assets", "available", "to", "the", "source", "account", "id", "and", "find", "any", "payment", "paths", "from", "those", "source", "assets", "to", "the", "desired", "destination", "asset", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L716-L754
train
229,286
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.trades
def trades(self, base_asset_code=None, counter_asset_code=None, base_asset_issuer=None, counter_asset_issuer=None, offer_id=None, cursor=None, order='asc', limit=10): """Load a list of trades, optionally filtered by an orderbook. See the below docs for more information on required and optional parameters for further specifying your search. `GET /trades <https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_ :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param int offer_id: Filter for by a specific offer id. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of trades filtered by a given query. :rtype: dict """ base_asset = Asset(base_asset_code, base_asset_issuer) counter_asset = Asset(counter_asset_code, counter_asset_issuer) asset_params = { 'base_asset_type': base_asset.type, 'base_asset_code': None if base_asset.is_native() else base_asset.code, 'base_asset_issuer': base_asset.issuer, 'counter_asset_type': counter_asset.type, 'counter_asset_code': None if counter_asset.is_native() else counter_asset.code, 'counter_asset_issuer': counter_asset.issuer } endpoint = '/trades' params = self.__query_params(offer_id=offer_id, cursor=cursor, order=order, limit=limit, **asset_params) return self.query(endpoint, params)
python
def trades(self, base_asset_code=None, counter_asset_code=None, base_asset_issuer=None, counter_asset_issuer=None, offer_id=None, cursor=None, order='asc', limit=10): """Load a list of trades, optionally filtered by an orderbook. See the below docs for more information on required and optional parameters for further specifying your search. `GET /trades <https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_ :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param int offer_id: Filter for by a specific offer id. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of trades filtered by a given query. :rtype: dict """ base_asset = Asset(base_asset_code, base_asset_issuer) counter_asset = Asset(counter_asset_code, counter_asset_issuer) asset_params = { 'base_asset_type': base_asset.type, 'base_asset_code': None if base_asset.is_native() else base_asset.code, 'base_asset_issuer': base_asset.issuer, 'counter_asset_type': counter_asset.type, 'counter_asset_code': None if counter_asset.is_native() else counter_asset.code, 'counter_asset_issuer': counter_asset.issuer } endpoint = '/trades' params = self.__query_params(offer_id=offer_id, cursor=cursor, order=order, limit=limit, **asset_params) return self.query(endpoint, params)
[ "def", "trades", "(", "self", ",", "base_asset_code", "=", "None", ",", "counter_asset_code", "=", "None", ",", "base_asset_issuer", "=", "None", ",", "counter_asset_issuer", "=", "None", ",", "offer_id", "=", "None", ",", "cursor", "=", "None", ",", "order"...
Load a list of trades, optionally filtered by an orderbook. See the below docs for more information on required and optional parameters for further specifying your search. `GET /trades <https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_ :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param int offer_id: Filter for by a specific offer id. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of trades filtered by a given query. :rtype: dict
[ "Load", "a", "list", "of", "trades", "optionally", "filtered", "by", "an", "orderbook", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L756-L790
train
229,287
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.trade_aggregations
def trade_aggregations(self, resolution, base_asset_code, counter_asset_code, base_asset_issuer=None, counter_asset_issuer=None, start_time=None, end_time=None, order='asc', limit=10, offset=0): """Load a list of aggregated historical trade data, optionally filtered by an orderbook. `GET /trade_aggregations <https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_ :param int start_time: Lower time boundary represented as millis since epoch. :param int end_time: Upper time boundary represented as millis since epoch. :param int resolution: Segment duration as millis since epoch. Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param int offset: segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. :return: A list of collected trade aggregations. :rtype: dict """ allowed_resolutions = (60000, 300000, 900000, 3600000, 86400000, 604800000) if resolution not in allowed_resolutions: raise NotValidParamError("resolution is invalid") if offset > resolution or offset >= 24 * 3600000 or offset % 3600000 != 0: raise NotValidParamError("offset is invalid") base_asset = Asset(base_asset_code, base_asset_issuer) counter_asset = Asset(counter_asset_code, counter_asset_issuer) asset_params = { 'base_asset_type': base_asset.type, 'base_asset_code': None if base_asset.is_native() else base_asset.code, 'base_asset_issuer': base_asset.issuer, 'counter_asset_type': counter_asset.type, 'counter_asset_code': None if counter_asset.is_native() else counter_asset.code, 'counter_asset_issuer': counter_asset.issuer } endpoint = '/trade_aggregations' params = self.__query_params(start_time=start_time, end_time=end_time, resolution=resolution, order=order, limit=limit, offset=offset, **asset_params) return self.query(endpoint, params)
python
def trade_aggregations(self, resolution, base_asset_code, counter_asset_code, base_asset_issuer=None, counter_asset_issuer=None, start_time=None, end_time=None, order='asc', limit=10, offset=0): """Load a list of aggregated historical trade data, optionally filtered by an orderbook. `GET /trade_aggregations <https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_ :param int start_time: Lower time boundary represented as millis since epoch. :param int end_time: Upper time boundary represented as millis since epoch. :param int resolution: Segment duration as millis since epoch. Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param int offset: segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. :return: A list of collected trade aggregations. :rtype: dict """ allowed_resolutions = (60000, 300000, 900000, 3600000, 86400000, 604800000) if resolution not in allowed_resolutions: raise NotValidParamError("resolution is invalid") if offset > resolution or offset >= 24 * 3600000 or offset % 3600000 != 0: raise NotValidParamError("offset is invalid") base_asset = Asset(base_asset_code, base_asset_issuer) counter_asset = Asset(counter_asset_code, counter_asset_issuer) asset_params = { 'base_asset_type': base_asset.type, 'base_asset_code': None if base_asset.is_native() else base_asset.code, 'base_asset_issuer': base_asset.issuer, 'counter_asset_type': counter_asset.type, 'counter_asset_code': None if counter_asset.is_native() else counter_asset.code, 'counter_asset_issuer': counter_asset.issuer } endpoint = '/trade_aggregations' params = self.__query_params(start_time=start_time, end_time=end_time, resolution=resolution, order=order, limit=limit, offset=offset, **asset_params) return self.query(endpoint, params)
[ "def", "trade_aggregations", "(", "self", ",", "resolution", ",", "base_asset_code", ",", "counter_asset_code", ",", "base_asset_issuer", "=", "None", ",", "counter_asset_issuer", "=", "None", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "o...
Load a list of aggregated historical trade data, optionally filtered by an orderbook. `GET /trade_aggregations <https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_ :param int start_time: Lower time boundary represented as millis since epoch. :param int end_time: Upper time boundary represented as millis since epoch. :param int resolution: Segment duration as millis since epoch. Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param int offset: segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. :return: A list of collected trade aggregations. :rtype: dict
[ "Load", "a", "list", "of", "aggregated", "historical", "trade", "data", "optionally", "filtered", "by", "an", "orderbook", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L792-L839
train
229,288
StellarCN/py-stellar-base
stellar_base/horizon.py
Horizon.offer_trades
def offer_trades(self, offer_id, cursor=None, order='asc', limit=10): """This endpoint represents all trades for a given offer. `GET /offers/{offer_id}/trades{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_ :param int offer_id: The offer ID to get trades on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict """ endpoint = '/offers/{offer_id}/trades'.format(offer_id=offer_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
python
def offer_trades(self, offer_id, cursor=None, order='asc', limit=10): """This endpoint represents all trades for a given offer. `GET /offers/{offer_id}/trades{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_ :param int offer_id: The offer ID to get trades on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict """ endpoint = '/offers/{offer_id}/trades'.format(offer_id=offer_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
[ "def", "offer_trades", "(", "self", ",", "offer_id", ",", "cursor", "=", "None", ",", "order", "=", "'asc'", ",", "limit", "=", "10", ")", ":", "endpoint", "=", "'/offers/{offer_id}/trades'", ".", "format", "(", "offer_id", "=", "offer_id", ")", "params", ...
This endpoint represents all trades for a given offer. `GET /offers/{offer_id}/trades{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_ :param int offer_id: The offer ID to get trades on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict
[ "This", "endpoint", "represents", "all", "trades", "for", "a", "given", "offer", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L841-L857
train
229,289
StellarCN/py-stellar-base
stellar_base/transaction_envelope.py
TransactionEnvelope.sign
def sign(self, keypair): """Sign this transaction envelope with a given keypair. Note that the signature must not already be in this instance's list of signatures. :param keypair: The keypair to use for signing this transaction envelope. :type keypair: :class:`Keypair <stellar_base.keypair.Keypair>` :raises: :exc:`SignatureExistError <stellar_base.utils.SignatureExistError>` """ assert isinstance(keypair, Keypair) tx_hash = self.hash_meta() sig = keypair.sign_decorated(tx_hash) sig_dict = [signature.__dict__ for signature in self.signatures] if sig.__dict__ in sig_dict: raise SignatureExistError('The keypair has already signed') else: self.signatures.append(sig)
python
def sign(self, keypair): """Sign this transaction envelope with a given keypair. Note that the signature must not already be in this instance's list of signatures. :param keypair: The keypair to use for signing this transaction envelope. :type keypair: :class:`Keypair <stellar_base.keypair.Keypair>` :raises: :exc:`SignatureExistError <stellar_base.utils.SignatureExistError>` """ assert isinstance(keypair, Keypair) tx_hash = self.hash_meta() sig = keypair.sign_decorated(tx_hash) sig_dict = [signature.__dict__ for signature in self.signatures] if sig.__dict__ in sig_dict: raise SignatureExistError('The keypair has already signed') else: self.signatures.append(sig)
[ "def", "sign", "(", "self", ",", "keypair", ")", ":", "assert", "isinstance", "(", "keypair", ",", "Keypair", ")", "tx_hash", "=", "self", ".", "hash_meta", "(", ")", "sig", "=", "keypair", ".", "sign_decorated", "(", "tx_hash", ")", "sig_dict", "=", "...
Sign this transaction envelope with a given keypair. Note that the signature must not already be in this instance's list of signatures. :param keypair: The keypair to use for signing this transaction envelope. :type keypair: :class:`Keypair <stellar_base.keypair.Keypair>` :raises: :exc:`SignatureExistError <stellar_base.utils.SignatureExistError>`
[ "Sign", "this", "transaction", "envelope", "with", "a", "given", "keypair", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/transaction_envelope.py#L43-L63
train
229,290
StellarCN/py-stellar-base
stellar_base/transaction_envelope.py
TransactionEnvelope.signature_base
def signature_base(self): """Get the signature base of this transaction envelope. Return the "signature base" of this transaction, which is the value that, when hashed, should be signed to create a signature that validators on the Stellar Network will accept. It is composed of a 4 prefix bytes followed by the xdr-encoded form of this transaction. :return: The signature base of this transaction envelope. """ network_id = self.network_id tx_type = Xdr.StellarXDRPacker() tx_type.pack_EnvelopeType(Xdr.const.ENVELOPE_TYPE_TX) tx_type = tx_type.get_buffer() tx = Xdr.StellarXDRPacker() tx.pack_Transaction(self.tx.to_xdr_object()) tx = tx.get_buffer() return network_id + tx_type + tx
python
def signature_base(self): """Get the signature base of this transaction envelope. Return the "signature base" of this transaction, which is the value that, when hashed, should be signed to create a signature that validators on the Stellar Network will accept. It is composed of a 4 prefix bytes followed by the xdr-encoded form of this transaction. :return: The signature base of this transaction envelope. """ network_id = self.network_id tx_type = Xdr.StellarXDRPacker() tx_type.pack_EnvelopeType(Xdr.const.ENVELOPE_TYPE_TX) tx_type = tx_type.get_buffer() tx = Xdr.StellarXDRPacker() tx.pack_Transaction(self.tx.to_xdr_object()) tx = tx.get_buffer() return network_id + tx_type + tx
[ "def", "signature_base", "(", "self", ")", ":", "network_id", "=", "self", ".", "network_id", "tx_type", "=", "Xdr", ".", "StellarXDRPacker", "(", ")", "tx_type", ".", "pack_EnvelopeType", "(", "Xdr", ".", "const", ".", "ENVELOPE_TYPE_TX", ")", "tx_type", "=...
Get the signature base of this transaction envelope. Return the "signature base" of this transaction, which is the value that, when hashed, should be signed to create a signature that validators on the Stellar Network will accept. It is composed of a 4 prefix bytes followed by the xdr-encoded form of this transaction. :return: The signature base of this transaction envelope.
[ "Get", "the", "signature", "base", "of", "this", "transaction", "envelope", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/transaction_envelope.py#L99-L120
train
229,291
StellarCN/py-stellar-base
stellar_base/federation.py
get_federation_service
def get_federation_service(domain, allow_http=False): """Retrieve the FEDERATION_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The FEDERATION_SERVER url. """ st = get_stellar_toml(domain, allow_http) if not st: return None return st.get('FEDERATION_SERVER')
python
def get_federation_service(domain, allow_http=False): """Retrieve the FEDERATION_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The FEDERATION_SERVER url. """ st = get_stellar_toml(domain, allow_http) if not st: return None return st.get('FEDERATION_SERVER')
[ "def", "get_federation_service", "(", "domain", ",", "allow_http", "=", "False", ")", ":", "st", "=", "get_stellar_toml", "(", "domain", ",", "allow_http", ")", "if", "not", "st", ":", "return", "None", "return", "st", ".", "get", "(", "'FEDERATION_SERVER'",...
Retrieve the FEDERATION_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The FEDERATION_SERVER url.
[ "Retrieve", "the", "FEDERATION_SERVER", "config", "from", "a", "domain", "s", "stellar", ".", "toml", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L76-L88
train
229,292
StellarCN/py-stellar-base
stellar_base/federation.py
get_auth_server
def get_auth_server(domain, allow_http=False): """Retrieve the AUTH_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The AUTH_SERVER url. """ st = get_stellar_toml(domain, allow_http) if not st: return None return st.get('AUTH_SERVER')
python
def get_auth_server(domain, allow_http=False): """Retrieve the AUTH_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The AUTH_SERVER url. """ st = get_stellar_toml(domain, allow_http) if not st: return None return st.get('AUTH_SERVER')
[ "def", "get_auth_server", "(", "domain", ",", "allow_http", "=", "False", ")", ":", "st", "=", "get_stellar_toml", "(", "domain", ",", "allow_http", ")", "if", "not", "st", ":", "return", "None", "return", "st", ".", "get", "(", "'AUTH_SERVER'", ")" ]
Retrieve the AUTH_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The AUTH_SERVER url.
[ "Retrieve", "the", "AUTH_SERVER", "config", "from", "a", "domain", "s", "stellar", ".", "toml", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L91-L103
train
229,293
StellarCN/py-stellar-base
stellar_base/federation.py
get_stellar_toml
def get_stellar_toml(domain, allow_http=False): """Retrieve the stellar.toml file from a given domain. Retrieve the stellar.toml file for information about interacting with Stellar's federation protocol for a given Stellar Anchor (specified by a domain). :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return: The stellar.toml file as a an object via :func:`toml.loads`. """ toml_link = '/.well-known/stellar.toml' if allow_http: protocol = 'http://' else: protocol = 'https://' url_list = ['', 'www.', 'stellar.'] url_list = [protocol + url + domain + toml_link for url in url_list] for url in url_list: r = requests.get(url) if r.status_code == 200: return toml.loads(r.text) return None
python
def get_stellar_toml(domain, allow_http=False): """Retrieve the stellar.toml file from a given domain. Retrieve the stellar.toml file for information about interacting with Stellar's federation protocol for a given Stellar Anchor (specified by a domain). :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return: The stellar.toml file as a an object via :func:`toml.loads`. """ toml_link = '/.well-known/stellar.toml' if allow_http: protocol = 'http://' else: protocol = 'https://' url_list = ['', 'www.', 'stellar.'] url_list = [protocol + url + domain + toml_link for url in url_list] for url in url_list: r = requests.get(url) if r.status_code == 200: return toml.loads(r.text) return None
[ "def", "get_stellar_toml", "(", "domain", ",", "allow_http", "=", "False", ")", ":", "toml_link", "=", "'/.well-known/stellar.toml'", "if", "allow_http", ":", "protocol", "=", "'http://'", "else", ":", "protocol", "=", "'https://'", "url_list", "=", "[", "''", ...
Retrieve the stellar.toml file from a given domain. Retrieve the stellar.toml file for information about interacting with Stellar's federation protocol for a given Stellar Anchor (specified by a domain). :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return: The stellar.toml file as a an object via :func:`toml.loads`.
[ "Retrieve", "the", "stellar", ".", "toml", "file", "from", "a", "given", "domain", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/federation.py#L106-L132
train
229,294
StellarCN/py-stellar-base
stellar_base/keypair.py
Keypair.account_xdr_object
def account_xdr_object(self): """Create PublicKey XDR object via public key bytes. :return: Serialized XDR of PublicKey type. """ return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519, self.verifying_key.to_bytes())
python
def account_xdr_object(self): """Create PublicKey XDR object via public key bytes. :return: Serialized XDR of PublicKey type. """ return Xdr.types.PublicKey(Xdr.const.KEY_TYPE_ED25519, self.verifying_key.to_bytes())
[ "def", "account_xdr_object", "(", "self", ")", ":", "return", "Xdr", ".", "types", ".", "PublicKey", "(", "Xdr", ".", "const", ".", "KEY_TYPE_ED25519", ",", "self", ".", "verifying_key", ".", "to_bytes", "(", ")", ")" ]
Create PublicKey XDR object via public key bytes. :return: Serialized XDR of PublicKey type.
[ "Create", "PublicKey", "XDR", "object", "via", "public", "key", "bytes", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L154-L160
train
229,295
StellarCN/py-stellar-base
stellar_base/keypair.py
Keypair.xdr
def xdr(self): """Generate base64 encoded XDR PublicKey object. Return a base64 encoded PublicKey XDR object, for sending over the wire when interacting with stellar. :return: The base64 encoded PublicKey XDR structure. """ kp = Xdr.StellarXDRPacker() kp.pack_PublicKey(self.account_xdr_object()) return base64.b64encode(kp.get_buffer())
python
def xdr(self): """Generate base64 encoded XDR PublicKey object. Return a base64 encoded PublicKey XDR object, for sending over the wire when interacting with stellar. :return: The base64 encoded PublicKey XDR structure. """ kp = Xdr.StellarXDRPacker() kp.pack_PublicKey(self.account_xdr_object()) return base64.b64encode(kp.get_buffer())
[ "def", "xdr", "(", "self", ")", ":", "kp", "=", "Xdr", ".", "StellarXDRPacker", "(", ")", "kp", ".", "pack_PublicKey", "(", "self", ".", "account_xdr_object", "(", ")", ")", "return", "base64", ".", "b64encode", "(", "kp", ".", "get_buffer", "(", ")", ...
Generate base64 encoded XDR PublicKey object. Return a base64 encoded PublicKey XDR object, for sending over the wire when interacting with stellar. :return: The base64 encoded PublicKey XDR structure.
[ "Generate", "base64", "encoded", "XDR", "PublicKey", "object", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L162-L172
train
229,296
StellarCN/py-stellar-base
stellar_base/keypair.py
Keypair.verify
def verify(self, data, signature): """Verify the signature of a sequence of bytes. Verify the signature of a sequence of bytes using the verifying (public) key and the data that was originally signed, otherwise throws an exception. :param bytes data: A sequence of bytes that were previously signed by the private key associated with this verifying key. :param bytes signature: A sequence of bytes that comprised the signature for the corresponding data. """ try: return self.verifying_key.verify(signature, data) except ed25519.BadSignatureError: raise BadSignatureError("Signature verification failed.")
python
def verify(self, data, signature): """Verify the signature of a sequence of bytes. Verify the signature of a sequence of bytes using the verifying (public) key and the data that was originally signed, otherwise throws an exception. :param bytes data: A sequence of bytes that were previously signed by the private key associated with this verifying key. :param bytes signature: A sequence of bytes that comprised the signature for the corresponding data. """ try: return self.verifying_key.verify(signature, data) except ed25519.BadSignatureError: raise BadSignatureError("Signature verification failed.")
[ "def", "verify", "(", "self", ",", "data", ",", "signature", ")", ":", "try", ":", "return", "self", ".", "verifying_key", ".", "verify", "(", "signature", ",", "data", ")", "except", "ed25519", ".", "BadSignatureError", ":", "raise", "BadSignatureError", ...
Verify the signature of a sequence of bytes. Verify the signature of a sequence of bytes using the verifying (public) key and the data that was originally signed, otherwise throws an exception. :param bytes data: A sequence of bytes that were previously signed by the private key associated with this verifying key. :param bytes signature: A sequence of bytes that comprised the signature for the corresponding data.
[ "Verify", "the", "signature", "of", "a", "sequence", "of", "bytes", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L228-L243
train
229,297
StellarCN/py-stellar-base
stellar_base/keypair.py
Keypair.sign_decorated
def sign_decorated(self, data): """Sign a bytes-like object and return the decorated signature. Sign a bytes-like object by signing the data using the signing (private) key, and return a decorated signature, which includes the last four bytes of the public key as a signature hint to go along with the signature as an XDR DecoratedSignature object. :param bytes data: A sequence of bytes to sign, typically a transaction. """ signature = self.sign(data) hint = self.signature_hint() return Xdr.types.DecoratedSignature(hint, signature)
python
def sign_decorated(self, data): """Sign a bytes-like object and return the decorated signature. Sign a bytes-like object by signing the data using the signing (private) key, and return a decorated signature, which includes the last four bytes of the public key as a signature hint to go along with the signature as an XDR DecoratedSignature object. :param bytes data: A sequence of bytes to sign, typically a transaction. """ signature = self.sign(data) hint = self.signature_hint() return Xdr.types.DecoratedSignature(hint, signature)
[ "def", "sign_decorated", "(", "self", ",", "data", ")", ":", "signature", "=", "self", ".", "sign", "(", "data", ")", "hint", "=", "self", ".", "signature_hint", "(", ")", "return", "Xdr", ".", "types", ".", "DecoratedSignature", "(", "hint", ",", "sig...
Sign a bytes-like object and return the decorated signature. Sign a bytes-like object by signing the data using the signing (private) key, and return a decorated signature, which includes the last four bytes of the public key as a signature hint to go along with the signature as an XDR DecoratedSignature object. :param bytes data: A sequence of bytes to sign, typically a transaction.
[ "Sign", "a", "bytes", "-", "like", "object", "and", "return", "the", "decorated", "signature", "." ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/keypair.py#L245-L259
train
229,298
StellarCN/py-stellar-base
stellar_base/utils.py
bytes_from_decode_data
def bytes_from_decode_data(s): """copy from base64._bytes_from_decode_data """ if isinstance(s, (str, unicode)): try: return s.encode('ascii') except UnicodeEncodeError: raise NotValidParamError( 'String argument should contain only ASCII characters') if isinstance(s, bytes_types): return s try: return memoryview(s).tobytes() except TypeError: raise suppress_context( TypeError( 'Argument should be a bytes-like object or ASCII string, not ' '{!r}'.format(s.__class__.__name__)))
python
def bytes_from_decode_data(s): """copy from base64._bytes_from_decode_data """ if isinstance(s, (str, unicode)): try: return s.encode('ascii') except UnicodeEncodeError: raise NotValidParamError( 'String argument should contain only ASCII characters') if isinstance(s, bytes_types): return s try: return memoryview(s).tobytes() except TypeError: raise suppress_context( TypeError( 'Argument should be a bytes-like object or ASCII string, not ' '{!r}'.format(s.__class__.__name__)))
[ "def", "bytes_from_decode_data", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "(", "str", ",", "unicode", ")", ")", ":", "try", ":", "return", "s", ".", "encode", "(", "'ascii'", ")", "except", "UnicodeEncodeError", ":", "raise", "NotValidParam...
copy from base64._bytes_from_decode_data
[ "copy", "from", "base64", ".", "_bytes_from_decode_data" ]
cce2e782064fb3955c85e1696e630d67b1010848
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/utils.py#L75-L92
train
229,299