id
int32
0
252k
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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
16,900
JonathanRaiman/pytreebank
pytreebank/parse.py
LabeledTreeCorpus.to_file
def to_file(self, path, mode="w"): """ Save the corpus to a text file in the original format. Arguments: ---------- path : str, where to save the corpus. mode : str, how to open the file. """ with open(path, mode=mode) as f: for tree in self: for label, line in tree.to_labeled_lines(): f.write(line + "\n")
python
def to_file(self, path, mode="w"): """ Save the corpus to a text file in the original format. Arguments: ---------- path : str, where to save the corpus. mode : str, how to open the file. """ with open(path, mode=mode) as f: for tree in self: for label, line in tree.to_labeled_lines(): f.write(line + "\n")
[ "def", "to_file", "(", "self", ",", "path", ",", "mode", "=", "\"w\"", ")", ":", "with", "open", "(", "path", ",", "mode", "=", "mode", ")", "as", "f", ":", "for", "tree", "in", "self", ":", "for", "label", ",", "line", "in", "tree", ".", "to_labeled_lines", "(", ")", ":", "f", ".", "write", "(", "line", "+", "\"\\n\"", ")" ]
Save the corpus to a text file in the original format. Arguments: ---------- path : str, where to save the corpus. mode : str, how to open the file.
[ "Save", "the", "corpus", "to", "a", "text", "file", "in", "the", "original", "format", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/parse.py#L127-L140
16,901
JonathanRaiman/pytreebank
pytreebank/treelstm.py
import_tree_corpus
def import_tree_corpus(labels_path, parents_path, texts_path): """ Import dataset from the TreeLSTM data generation scrips. Arguments: ---------- labels_path : str, where are labels are stored (should be in data/sst/labels.txt). parents_path : str, where the parent relationships are stored (should be in data/sst/parents.txt). texts_path : str, where are strings for each tree are stored (should be in data/sst/sents.txt). Returns: -------- list<LabeledTree> : loaded example trees. """ with codecs.open(labels_path, "r", "UTF-8") as f: label_lines = f.readlines() with codecs.open(parents_path, "r", "UTF-8") as f: parent_lines = f.readlines() with codecs.open(texts_path, "r", "UTF-8") as f: word_lines = f.readlines() assert len(label_lines) == len(parent_lines) assert len(label_lines) == len(word_lines) trees = [] for labels, parents, words in zip(label_lines, parent_lines, word_lines): labels = [int(l) + 2 for l in labels.strip().split(" ")] parents = [int(l) for l in parents.strip().split(" ")] words = words.strip().split(" ") assert len(labels) == len(parents) trees.append(read_tree(parents, labels, words)) return trees
python
def import_tree_corpus(labels_path, parents_path, texts_path): """ Import dataset from the TreeLSTM data generation scrips. Arguments: ---------- labels_path : str, where are labels are stored (should be in data/sst/labels.txt). parents_path : str, where the parent relationships are stored (should be in data/sst/parents.txt). texts_path : str, where are strings for each tree are stored (should be in data/sst/sents.txt). Returns: -------- list<LabeledTree> : loaded example trees. """ with codecs.open(labels_path, "r", "UTF-8") as f: label_lines = f.readlines() with codecs.open(parents_path, "r", "UTF-8") as f: parent_lines = f.readlines() with codecs.open(texts_path, "r", "UTF-8") as f: word_lines = f.readlines() assert len(label_lines) == len(parent_lines) assert len(label_lines) == len(word_lines) trees = [] for labels, parents, words in zip(label_lines, parent_lines, word_lines): labels = [int(l) + 2 for l in labels.strip().split(" ")] parents = [int(l) for l in parents.strip().split(" ")] words = words.strip().split(" ") assert len(labels) == len(parents) trees.append(read_tree(parents, labels, words)) return trees
[ "def", "import_tree_corpus", "(", "labels_path", ",", "parents_path", ",", "texts_path", ")", ":", "with", "codecs", ".", "open", "(", "labels_path", ",", "\"r\"", ",", "\"UTF-8\"", ")", "as", "f", ":", "label_lines", "=", "f", ".", "readlines", "(", ")", "with", "codecs", ".", "open", "(", "parents_path", ",", "\"r\"", ",", "\"UTF-8\"", ")", "as", "f", ":", "parent_lines", "=", "f", ".", "readlines", "(", ")", "with", "codecs", ".", "open", "(", "texts_path", ",", "\"r\"", ",", "\"UTF-8\"", ")", "as", "f", ":", "word_lines", "=", "f", ".", "readlines", "(", ")", "assert", "len", "(", "label_lines", ")", "==", "len", "(", "parent_lines", ")", "assert", "len", "(", "label_lines", ")", "==", "len", "(", "word_lines", ")", "trees", "=", "[", "]", "for", "labels", ",", "parents", ",", "words", "in", "zip", "(", "label_lines", ",", "parent_lines", ",", "word_lines", ")", ":", "labels", "=", "[", "int", "(", "l", ")", "+", "2", "for", "l", "in", "labels", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", "]", "parents", "=", "[", "int", "(", "l", ")", "for", "l", "in", "parents", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", "]", "words", "=", "words", ".", "strip", "(", ")", ".", "split", "(", "\" \"", ")", "assert", "len", "(", "labels", ")", "==", "len", "(", "parents", ")", "trees", ".", "append", "(", "read_tree", "(", "parents", ",", "labels", ",", "words", ")", ")", "return", "trees" ]
Import dataset from the TreeLSTM data generation scrips. Arguments: ---------- labels_path : str, where are labels are stored (should be in data/sst/labels.txt). parents_path : str, where the parent relationships are stored (should be in data/sst/parents.txt). texts_path : str, where are strings for each tree are stored (should be in data/sst/sents.txt). Returns: -------- list<LabeledTree> : loaded example trees.
[ "Import", "dataset", "from", "the", "TreeLSTM", "data", "generation", "scrips", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L8-L42
16,902
JonathanRaiman/pytreebank
pytreebank/treelstm.py
assign_texts
def assign_texts(node, words, next_idx=0): """ Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order. """ if len(node.children) == 0: node.text = words[next_idx] return next_idx + 1 else: for child in node.children: next_idx = assign_texts(child, words, next_idx) return next_idx
python
def assign_texts(node, words, next_idx=0): """ Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order. """ if len(node.children) == 0: node.text = words[next_idx] return next_idx + 1 else: for child in node.children: next_idx = assign_texts(child, words, next_idx) return next_idx
[ "def", "assign_texts", "(", "node", ",", "words", ",", "next_idx", "=", "0", ")", ":", "if", "len", "(", "node", ".", "children", ")", "==", "0", ":", "node", ".", "text", "=", "words", "[", "next_idx", "]", "return", "next_idx", "+", "1", "else", ":", "for", "child", "in", "node", ".", "children", ":", "next_idx", "=", "assign_texts", "(", "child", ",", "words", ",", "next_idx", ")", "return", "next_idx" ]
Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order.
[ "Recursively", "assign", "the", "words", "to", "nodes", "by", "finding", "and", "assigning", "strings", "to", "the", "leaves", "of", "a", "tree", "in", "left", "to", "right", "order", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L44-L56
16,903
JonathanRaiman/pytreebank
pytreebank/treelstm.py
read_tree
def read_tree(parents, labels, words): """ Take as input a list of integers for parents and labels, along with a list of words, and reconstruct a LabeledTree. """ trees = {} root = None for i in range(1, len(parents) + 1): if not i in trees and parents[i - 1] != - 1: idx = i prev = None while True: parent = parents[idx - 1] if parent == -1: break tree = LabeledTree() if prev is not None: tree.add_child(prev) trees[idx] = tree tree.label = labels[idx - 1] if trees.get(parent) is not None: trees[parent].add_child(tree) break elif parent == 0: root = tree break else: prev = tree idx = parent assert assign_texts(root, words) == len(words) return root
python
def read_tree(parents, labels, words): """ Take as input a list of integers for parents and labels, along with a list of words, and reconstruct a LabeledTree. """ trees = {} root = None for i in range(1, len(parents) + 1): if not i in trees and parents[i - 1] != - 1: idx = i prev = None while True: parent = parents[idx - 1] if parent == -1: break tree = LabeledTree() if prev is not None: tree.add_child(prev) trees[idx] = tree tree.label = labels[idx - 1] if trees.get(parent) is not None: trees[parent].add_child(tree) break elif parent == 0: root = tree break else: prev = tree idx = parent assert assign_texts(root, words) == len(words) return root
[ "def", "read_tree", "(", "parents", ",", "labels", ",", "words", ")", ":", "trees", "=", "{", "}", "root", "=", "None", "for", "i", "in", "range", "(", "1", ",", "len", "(", "parents", ")", "+", "1", ")", ":", "if", "not", "i", "in", "trees", "and", "parents", "[", "i", "-", "1", "]", "!=", "-", "1", ":", "idx", "=", "i", "prev", "=", "None", "while", "True", ":", "parent", "=", "parents", "[", "idx", "-", "1", "]", "if", "parent", "==", "-", "1", ":", "break", "tree", "=", "LabeledTree", "(", ")", "if", "prev", "is", "not", "None", ":", "tree", ".", "add_child", "(", "prev", ")", "trees", "[", "idx", "]", "=", "tree", "tree", ".", "label", "=", "labels", "[", "idx", "-", "1", "]", "if", "trees", ".", "get", "(", "parent", ")", "is", "not", "None", ":", "trees", "[", "parent", "]", ".", "add_child", "(", "tree", ")", "break", "elif", "parent", "==", "0", ":", "root", "=", "tree", "break", "else", ":", "prev", "=", "tree", "idx", "=", "parent", "assert", "assign_texts", "(", "root", ",", "words", ")", "==", "len", "(", "words", ")", "return", "root" ]
Take as input a list of integers for parents and labels, along with a list of words, and reconstruct a LabeledTree.
[ "Take", "as", "input", "a", "list", "of", "integers", "for", "parents", "and", "labels", "along", "with", "a", "list", "of", "words", "and", "reconstruct", "a", "LabeledTree", "." ]
7b4c671d3dff661cc3677e54db817e50c5a1c666
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L58-L89
16,904
GiulioRossetti/ndlib
ndlib/models/opinions/CognitiveOpDynModel.py
CognitiveOpDynModel.set_initial_status
def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. Generates random node profiles. """ super(CognitiveOpDynModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = np.random.random_sample() self.initial_status = self.status.copy() # set new node parameters self.params['nodes']['cognitive'] = {} # first correct the input model parameters and retreive T_range, B_range and R_distribution T_range = (self.params['model']['T_range_min'], self.params['model']['T_range_max']) if self.params['model']['T_range_min'] > self.params['model']['T_range_max']: T_range = (self.params['model']['T_range_max'], self.params['model']['T_range_min']) B_range = (self.params['model']['B_range_min'], self.params['model']['B_range_max']) if self.params['model']['B_range_min'] > self.params['model']['B_range_max']: B_range = (self.params['model']['B_range_max'], self.params['model']['B_range_min']) s = float(self.params['model']['R_fraction_negative'] + self.params['model']['R_fraction_neutral'] + self.params['model']['R_fraction_positive']) R_distribution = (self.params['model']['R_fraction_negative']/s, self.params['model']['R_fraction_neutral']/s, self.params['model']['R_fraction_positive']/s) # then sample parameters from the ranges and distribution for node in self.graph.nodes(): R_prob = np.random.random_sample() if R_prob < R_distribution[0]: R = -1 elif R_prob < (R_distribution[0] + R_distribution[1]): R = 0 else: R = 1 # R, B and T parameters in a tuple self.params['nodes']['cognitive'][node] = (R, B_range[0] + (B_range[1] - B_range[0])*np.random.random_sample(), T_range[0] + (T_range[1] - T_range[0])*np.random.random_sample())
python
def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. Generates random node profiles. """ super(CognitiveOpDynModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = np.random.random_sample() self.initial_status = self.status.copy() # set new node parameters self.params['nodes']['cognitive'] = {} # first correct the input model parameters and retreive T_range, B_range and R_distribution T_range = (self.params['model']['T_range_min'], self.params['model']['T_range_max']) if self.params['model']['T_range_min'] > self.params['model']['T_range_max']: T_range = (self.params['model']['T_range_max'], self.params['model']['T_range_min']) B_range = (self.params['model']['B_range_min'], self.params['model']['B_range_max']) if self.params['model']['B_range_min'] > self.params['model']['B_range_max']: B_range = (self.params['model']['B_range_max'], self.params['model']['B_range_min']) s = float(self.params['model']['R_fraction_negative'] + self.params['model']['R_fraction_neutral'] + self.params['model']['R_fraction_positive']) R_distribution = (self.params['model']['R_fraction_negative']/s, self.params['model']['R_fraction_neutral']/s, self.params['model']['R_fraction_positive']/s) # then sample parameters from the ranges and distribution for node in self.graph.nodes(): R_prob = np.random.random_sample() if R_prob < R_distribution[0]: R = -1 elif R_prob < (R_distribution[0] + R_distribution[1]): R = 0 else: R = 1 # R, B and T parameters in a tuple self.params['nodes']['cognitive'][node] = (R, B_range[0] + (B_range[1] - B_range[0])*np.random.random_sample(), T_range[0] + (T_range[1] - T_range[0])*np.random.random_sample())
[ "def", "set_initial_status", "(", "self", ",", "configuration", "=", "None", ")", ":", "super", "(", "CognitiveOpDynModel", ",", "self", ")", ".", "set_initial_status", "(", "configuration", ")", "# set node status", "for", "node", "in", "self", ".", "status", ":", "self", ".", "status", "[", "node", "]", "=", "np", ".", "random", ".", "random_sample", "(", ")", "self", ".", "initial_status", "=", "self", ".", "status", ".", "copy", "(", ")", "# set new node parameters", "self", ".", "params", "[", "'nodes'", "]", "[", "'cognitive'", "]", "=", "{", "}", "# first correct the input model parameters and retreive T_range, B_range and R_distribution", "T_range", "=", "(", "self", ".", "params", "[", "'model'", "]", "[", "'T_range_min'", "]", ",", "self", ".", "params", "[", "'model'", "]", "[", "'T_range_max'", "]", ")", "if", "self", ".", "params", "[", "'model'", "]", "[", "'T_range_min'", "]", ">", "self", ".", "params", "[", "'model'", "]", "[", "'T_range_max'", "]", ":", "T_range", "=", "(", "self", ".", "params", "[", "'model'", "]", "[", "'T_range_max'", "]", ",", "self", ".", "params", "[", "'model'", "]", "[", "'T_range_min'", "]", ")", "B_range", "=", "(", "self", ".", "params", "[", "'model'", "]", "[", "'B_range_min'", "]", ",", "self", ".", "params", "[", "'model'", "]", "[", "'B_range_max'", "]", ")", "if", "self", ".", "params", "[", "'model'", "]", "[", "'B_range_min'", "]", ">", "self", ".", "params", "[", "'model'", "]", "[", "'B_range_max'", "]", ":", "B_range", "=", "(", "self", ".", "params", "[", "'model'", "]", "[", "'B_range_max'", "]", ",", "self", ".", "params", "[", "'model'", "]", "[", "'B_range_min'", "]", ")", "s", "=", "float", "(", "self", ".", "params", "[", "'model'", "]", "[", "'R_fraction_negative'", "]", "+", "self", ".", "params", "[", "'model'", "]", "[", "'R_fraction_neutral'", "]", "+", "self", ".", "params", "[", "'model'", "]", "[", "'R_fraction_positive'", "]", ")", "R_distribution", "=", "(", "self", ".", "params", "[", "'model'", "]", "[", "'R_fraction_negative'", "]", "/", "s", ",", "self", ".", "params", "[", "'model'", "]", "[", "'R_fraction_neutral'", "]", "/", "s", ",", "self", ".", "params", "[", "'model'", "]", "[", "'R_fraction_positive'", "]", "/", "s", ")", "# then sample parameters from the ranges and distribution", "for", "node", "in", "self", ".", "graph", ".", "nodes", "(", ")", ":", "R_prob", "=", "np", ".", "random", ".", "random_sample", "(", ")", "if", "R_prob", "<", "R_distribution", "[", "0", "]", ":", "R", "=", "-", "1", "elif", "R_prob", "<", "(", "R_distribution", "[", "0", "]", "+", "R_distribution", "[", "1", "]", ")", ":", "R", "=", "0", "else", ":", "R", "=", "1", "# R, B and T parameters in a tuple", "self", ".", "params", "[", "'nodes'", "]", "[", "'cognitive'", "]", "[", "node", "]", "=", "(", "R", ",", "B_range", "[", "0", "]", "+", "(", "B_range", "[", "1", "]", "-", "B_range", "[", "0", "]", ")", "*", "np", ".", "random", ".", "random_sample", "(", ")", ",", "T_range", "[", "0", "]", "+", "(", "T_range", "[", "1", "]", "-", "T_range", "[", "0", "]", ")", "*", "np", ".", "random", ".", "random_sample", "(", ")", ")" ]
Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. Generates random node profiles.
[ "Override", "behaviour", "of", "methods", "in", "class", "DiffusionModel", ".", "Overwrites", "initial", "status", "using", "random", "real", "values", ".", "Generates", "random", "node", "profiles", "." ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/CognitiveOpDynModel.py#L92-L133
16,905
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_node_configuration
def add_node_configuration(self, param_name, node_id, param_value): """ Set a parameter for a given node :param param_name: parameter identifier (as specified by the chosen model) :param node_id: node identifier :param param_value: parameter value """ if param_name not in self.config['nodes']: self.config['nodes'][param_name] = {node_id: param_value} else: self.config['nodes'][param_name][node_id] = param_value
python
def add_node_configuration(self, param_name, node_id, param_value): """ Set a parameter for a given node :param param_name: parameter identifier (as specified by the chosen model) :param node_id: node identifier :param param_value: parameter value """ if param_name not in self.config['nodes']: self.config['nodes'][param_name] = {node_id: param_value} else: self.config['nodes'][param_name][node_id] = param_value
[ "def", "add_node_configuration", "(", "self", ",", "param_name", ",", "node_id", ",", "param_value", ")", ":", "if", "param_name", "not", "in", "self", ".", "config", "[", "'nodes'", "]", ":", "self", ".", "config", "[", "'nodes'", "]", "[", "param_name", "]", "=", "{", "node_id", ":", "param_value", "}", "else", ":", "self", ".", "config", "[", "'nodes'", "]", "[", "param_name", "]", "[", "node_id", "]", "=", "param_value" ]
Set a parameter for a given node :param param_name: parameter identifier (as specified by the chosen model) :param node_id: node identifier :param param_value: parameter value
[ "Set", "a", "parameter", "for", "a", "given", "node" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L72-L83
16,906
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_node_set_configuration
def add_node_set_configuration(self, param_name, node_to_value): """ Set Nodes parameter :param param_name: parameter identifier (as specified by the chosen model) :param node_to_value: dictionary mapping each node a parameter value """ for nid, val in future.utils.iteritems(node_to_value): self.add_node_configuration(param_name, nid, val)
python
def add_node_set_configuration(self, param_name, node_to_value): """ Set Nodes parameter :param param_name: parameter identifier (as specified by the chosen model) :param node_to_value: dictionary mapping each node a parameter value """ for nid, val in future.utils.iteritems(node_to_value): self.add_node_configuration(param_name, nid, val)
[ "def", "add_node_set_configuration", "(", "self", ",", "param_name", ",", "node_to_value", ")", ":", "for", "nid", ",", "val", "in", "future", ".", "utils", ".", "iteritems", "(", "node_to_value", ")", ":", "self", ".", "add_node_configuration", "(", "param_name", ",", "nid", ",", "val", ")" ]
Set Nodes parameter :param param_name: parameter identifier (as specified by the chosen model) :param node_to_value: dictionary mapping each node a parameter value
[ "Set", "Nodes", "parameter" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L85-L93
16,907
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_edge_configuration
def add_edge_configuration(self, param_name, edge, param_value): """ Set a parameter for a given edge :param param_name: parameter identifier (as specified by the chosen model) :param edge: edge identifier :param param_value: parameter value """ if param_name not in self.config['edges']: self.config['edges'][param_name] = {edge: param_value} else: self.config['edges'][param_name][edge] = param_value
python
def add_edge_configuration(self, param_name, edge, param_value): """ Set a parameter for a given edge :param param_name: parameter identifier (as specified by the chosen model) :param edge: edge identifier :param param_value: parameter value """ if param_name not in self.config['edges']: self.config['edges'][param_name] = {edge: param_value} else: self.config['edges'][param_name][edge] = param_value
[ "def", "add_edge_configuration", "(", "self", ",", "param_name", ",", "edge", ",", "param_value", ")", ":", "if", "param_name", "not", "in", "self", ".", "config", "[", "'edges'", "]", ":", "self", ".", "config", "[", "'edges'", "]", "[", "param_name", "]", "=", "{", "edge", ":", "param_value", "}", "else", ":", "self", ".", "config", "[", "'edges'", "]", "[", "param_name", "]", "[", "edge", "]", "=", "param_value" ]
Set a parameter for a given edge :param param_name: parameter identifier (as specified by the chosen model) :param edge: edge identifier :param param_value: parameter value
[ "Set", "a", "parameter", "for", "a", "given", "edge" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L95-L106
16,908
GiulioRossetti/ndlib
ndlib/models/ModelConfig.py
Configuration.add_edge_set_configuration
def add_edge_set_configuration(self, param_name, edge_to_value): """ Set Edges parameter :param param_name: parameter identifier (as specified by the chosen model) :param edge_to_value: dictionary mapping each edge a parameter value """ for edge, val in future.utils.iteritems(edge_to_value): self.add_edge_configuration(param_name, edge, val)
python
def add_edge_set_configuration(self, param_name, edge_to_value): """ Set Edges parameter :param param_name: parameter identifier (as specified by the chosen model) :param edge_to_value: dictionary mapping each edge a parameter value """ for edge, val in future.utils.iteritems(edge_to_value): self.add_edge_configuration(param_name, edge, val)
[ "def", "add_edge_set_configuration", "(", "self", ",", "param_name", ",", "edge_to_value", ")", ":", "for", "edge", ",", "val", "in", "future", ".", "utils", ".", "iteritems", "(", "edge_to_value", ")", ":", "self", ".", "add_edge_configuration", "(", "param_name", ",", "edge", ",", "val", ")" ]
Set Edges parameter :param param_name: parameter identifier (as specified by the chosen model) :param edge_to_value: dictionary mapping each edge a parameter value
[ "Set", "Edges", "parameter" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/ModelConfig.py#L108-L116
16,909
GiulioRossetti/ndlib
ndlib/utils.py
multi_runs
def multi_runs(model, execution_number=1, iteration_number=50, infection_sets=None, nprocesses=multiprocessing.cpu_count()): """ Multiple executions of a given model varying the initial set of infected nodes :param model: a configured diffusion model :param execution_number: number of instantiations :param iteration_number: number of iterations per execution :param infection_sets: predefined set of infected nodes sets :param nprocesses: number of processes. Default values cpu number. :return: resulting trends for all the executions """ if nprocesses > multiprocessing.cpu_count(): nprocesses = multiprocessing.cpu_count() executions = [] if infection_sets is not None: if len(infection_sets) != execution_number: raise InitializationException( {"message": "Number of infection sets provided does not match the number of executions required"}) for x in past.builtins.xrange(0, execution_number, nprocesses): with closing(multiprocessing.Pool(processes=nprocesses, maxtasksperchild=10)) as pool: tasks = [copy.copy(model).reset(infection_sets[i]) for i in past.builtins.xrange(x, min(x + nprocesses, execution_number))] results = [pool.apply_async(__execute, (t, iteration_number)) for t in tasks] for result in results: executions.append(result.get()) else: for x in past.builtins.xrange(0, execution_number, nprocesses): with closing(multiprocessing.Pool(processes=nprocesses, maxtasksperchild=10)) as pool: tasks = [copy.deepcopy(model).reset() for _ in past.builtins.xrange(x, min(x + nprocesses, execution_number))] results = [pool.apply_async(__execute, (t, iteration_number)) for t in tasks] for result in results: executions.append(result.get()) return executions
python
def multi_runs(model, execution_number=1, iteration_number=50, infection_sets=None, nprocesses=multiprocessing.cpu_count()): """ Multiple executions of a given model varying the initial set of infected nodes :param model: a configured diffusion model :param execution_number: number of instantiations :param iteration_number: number of iterations per execution :param infection_sets: predefined set of infected nodes sets :param nprocesses: number of processes. Default values cpu number. :return: resulting trends for all the executions """ if nprocesses > multiprocessing.cpu_count(): nprocesses = multiprocessing.cpu_count() executions = [] if infection_sets is not None: if len(infection_sets) != execution_number: raise InitializationException( {"message": "Number of infection sets provided does not match the number of executions required"}) for x in past.builtins.xrange(0, execution_number, nprocesses): with closing(multiprocessing.Pool(processes=nprocesses, maxtasksperchild=10)) as pool: tasks = [copy.copy(model).reset(infection_sets[i]) for i in past.builtins.xrange(x, min(x + nprocesses, execution_number))] results = [pool.apply_async(__execute, (t, iteration_number)) for t in tasks] for result in results: executions.append(result.get()) else: for x in past.builtins.xrange(0, execution_number, nprocesses): with closing(multiprocessing.Pool(processes=nprocesses, maxtasksperchild=10)) as pool: tasks = [copy.deepcopy(model).reset() for _ in past.builtins.xrange(x, min(x + nprocesses, execution_number))] results = [pool.apply_async(__execute, (t, iteration_number)) for t in tasks] for result in results: executions.append(result.get()) return executions
[ "def", "multi_runs", "(", "model", ",", "execution_number", "=", "1", ",", "iteration_number", "=", "50", ",", "infection_sets", "=", "None", ",", "nprocesses", "=", "multiprocessing", ".", "cpu_count", "(", ")", ")", ":", "if", "nprocesses", ">", "multiprocessing", ".", "cpu_count", "(", ")", ":", "nprocesses", "=", "multiprocessing", ".", "cpu_count", "(", ")", "executions", "=", "[", "]", "if", "infection_sets", "is", "not", "None", ":", "if", "len", "(", "infection_sets", ")", "!=", "execution_number", ":", "raise", "InitializationException", "(", "{", "\"message\"", ":", "\"Number of infection sets provided does not match the number of executions required\"", "}", ")", "for", "x", "in", "past", ".", "builtins", ".", "xrange", "(", "0", ",", "execution_number", ",", "nprocesses", ")", ":", "with", "closing", "(", "multiprocessing", ".", "Pool", "(", "processes", "=", "nprocesses", ",", "maxtasksperchild", "=", "10", ")", ")", "as", "pool", ":", "tasks", "=", "[", "copy", ".", "copy", "(", "model", ")", ".", "reset", "(", "infection_sets", "[", "i", "]", ")", "for", "i", "in", "past", ".", "builtins", ".", "xrange", "(", "x", ",", "min", "(", "x", "+", "nprocesses", ",", "execution_number", ")", ")", "]", "results", "=", "[", "pool", ".", "apply_async", "(", "__execute", ",", "(", "t", ",", "iteration_number", ")", ")", "for", "t", "in", "tasks", "]", "for", "result", "in", "results", ":", "executions", ".", "append", "(", "result", ".", "get", "(", ")", ")", "else", ":", "for", "x", "in", "past", ".", "builtins", ".", "xrange", "(", "0", ",", "execution_number", ",", "nprocesses", ")", ":", "with", "closing", "(", "multiprocessing", ".", "Pool", "(", "processes", "=", "nprocesses", ",", "maxtasksperchild", "=", "10", ")", ")", "as", "pool", ":", "tasks", "=", "[", "copy", ".", "deepcopy", "(", "model", ")", ".", "reset", "(", ")", "for", "_", "in", "past", ".", "builtins", ".", "xrange", "(", "x", ",", "min", "(", "x", "+", "nprocesses", ",", "execution_number", ")", ")", "]", "results", "=", "[", "pool", ".", "apply_async", "(", "__execute", ",", "(", "t", ",", "iteration_number", ")", ")", "for", "t", "in", "tasks", "]", "for", "result", "in", "results", ":", "executions", ".", "append", "(", "result", ".", "get", "(", ")", ")", "return", "executions" ]
Multiple executions of a given model varying the initial set of infected nodes :param model: a configured diffusion model :param execution_number: number of instantiations :param iteration_number: number of iterations per execution :param infection_sets: predefined set of infected nodes sets :param nprocesses: number of processes. Default values cpu number. :return: resulting trends for all the executions
[ "Multiple", "executions", "of", "a", "given", "model", "varying", "the", "initial", "set", "of", "infected", "nodes" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/utils.py#L15-L58
16,910
GiulioRossetti/ndlib
ndlib/utils.py
__execute
def __execute(model, iteration_number): """ Execute a simulation model :param model: a configured diffusion model :param iteration_number: number of iterations :return: computed trends """ iterations = model.iteration_bunch(iteration_number, False) trends = model.build_trends(iterations)[0] del iterations del model return trends
python
def __execute(model, iteration_number): """ Execute a simulation model :param model: a configured diffusion model :param iteration_number: number of iterations :return: computed trends """ iterations = model.iteration_bunch(iteration_number, False) trends = model.build_trends(iterations)[0] del iterations del model return trends
[ "def", "__execute", "(", "model", ",", "iteration_number", ")", ":", "iterations", "=", "model", ".", "iteration_bunch", "(", "iteration_number", ",", "False", ")", "trends", "=", "model", ".", "build_trends", "(", "iterations", ")", "[", "0", "]", "del", "iterations", "del", "model", "return", "trends" ]
Execute a simulation model :param model: a configured diffusion model :param iteration_number: number of iterations :return: computed trends
[ "Execute", "a", "simulation", "model" ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/utils.py#L61-L73
16,911
GiulioRossetti/ndlib
ndlib/models/opinions/AlgorithmicBiasModel.py
AlgorithmicBiasModel.set_initial_status
def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. """ super(AlgorithmicBiasModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = np.random.random_sample() self.initial_status = self.status.copy()
python
def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. """ super(AlgorithmicBiasModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = np.random.random_sample() self.initial_status = self.status.copy()
[ "def", "set_initial_status", "(", "self", ",", "configuration", "=", "None", ")", ":", "super", "(", "AlgorithmicBiasModel", ",", "self", ")", ".", "set_initial_status", "(", "configuration", ")", "# set node status", "for", "node", "in", "self", ".", "status", ":", "self", ".", "status", "[", "node", "]", "=", "np", ".", "random", ".", "random_sample", "(", ")", "self", ".", "initial_status", "=", "self", ".", "status", ".", "copy", "(", ")" ]
Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values.
[ "Override", "behaviour", "of", "methods", "in", "class", "DiffusionModel", ".", "Overwrites", "initial", "status", "using", "random", "real", "values", "." ]
23ecf50c0f76ff2714471071ab9ecb600f4a9832
https://github.com/GiulioRossetti/ndlib/blob/23ecf50c0f76ff2714471071ab9ecb600f4a9832/ndlib/models/opinions/AlgorithmicBiasModel.py#L54-L64
16,912
HearthSim/python-hearthstone
hearthstone/entities.py
Player.names
def names(self): """ Returns the player's name and real name. Returns two empty strings if the player is unknown. AI real name is always an empty string. """ if self.name == self.UNKNOWN_HUMAN_PLAYER: return "", "" if not self.is_ai and " " in self.name: return "", self.name return self.name, ""
python
def names(self): """ Returns the player's name and real name. Returns two empty strings if the player is unknown. AI real name is always an empty string. """ if self.name == self.UNKNOWN_HUMAN_PLAYER: return "", "" if not self.is_ai and " " in self.name: return "", self.name return self.name, ""
[ "def", "names", "(", "self", ")", ":", "if", "self", ".", "name", "==", "self", ".", "UNKNOWN_HUMAN_PLAYER", ":", "return", "\"\"", ",", "\"\"", "if", "not", "self", ".", "is_ai", "and", "\" \"", "in", "self", ".", "name", ":", "return", "\"\"", ",", "self", ".", "name", "return", "self", ".", "name", ",", "\"\"" ]
Returns the player's name and real name. Returns two empty strings if the player is unknown. AI real name is always an empty string.
[ "Returns", "the", "player", "s", "name", "and", "real", "name", ".", "Returns", "two", "empty", "strings", "if", "the", "player", "is", "unknown", ".", "AI", "real", "name", "is", "always", "an", "empty", "string", "." ]
3690b714248b578dcbba8a492bf228ff09a6aeaf
https://github.com/HearthSim/python-hearthstone/blob/3690b714248b578dcbba8a492bf228ff09a6aeaf/hearthstone/entities.py#L147-L159
16,913
scikit-hep/root_pandas
root_pandas/readwrite.py
_getgroup
def _getgroup(string, depth): """ Get a group from the string, where group is a list of all the comma separated substrings up to the next '}' char or the brace enclosed substring if there is no comma """ out, comma = [], False while string: items, string = _getitem(string, depth) if not string: break out += items if string[0] == '}': if comma: return out, string[1:] return ['{' + a + '}' for a in out], string[1:] if string[0] == ',': comma, string = True, string[1:] return None
python
def _getgroup(string, depth): """ Get a group from the string, where group is a list of all the comma separated substrings up to the next '}' char or the brace enclosed substring if there is no comma """ out, comma = [], False while string: items, string = _getitem(string, depth) if not string: break out += items if string[0] == '}': if comma: return out, string[1:] return ['{' + a + '}' for a in out], string[1:] if string[0] == ',': comma, string = True, string[1:] return None
[ "def", "_getgroup", "(", "string", ",", "depth", ")", ":", "out", ",", "comma", "=", "[", "]", ",", "False", "while", "string", ":", "items", ",", "string", "=", "_getitem", "(", "string", ",", "depth", ")", "if", "not", "string", ":", "break", "out", "+=", "items", "if", "string", "[", "0", "]", "==", "'}'", ":", "if", "comma", ":", "return", "out", ",", "string", "[", "1", ":", "]", "return", "[", "'{'", "+", "a", "+", "'}'", "for", "a", "in", "out", "]", ",", "string", "[", "1", ":", "]", "if", "string", "[", "0", "]", "==", "','", ":", "comma", ",", "string", "=", "True", ",", "string", "[", "1", ":", "]", "return", "None" ]
Get a group from the string, where group is a list of all the comma separated substrings up to the next '}' char or the brace enclosed substring if there is no comma
[ "Get", "a", "group", "from", "the", "string", "where", "group", "is", "a", "list", "of", "all", "the", "comma", "separated", "substrings", "up", "to", "the", "next", "}", "char", "or", "the", "brace", "enclosed", "substring", "if", "there", "is", "no", "comma" ]
57991a4feaeb9213575cfba7a369fc05cc0d846b
https://github.com/scikit-hep/root_pandas/blob/57991a4feaeb9213575cfba7a369fc05cc0d846b/root_pandas/readwrite.py#L55-L77
16,914
scikit-hep/root_pandas
root_pandas/readwrite.py
filter_noexpand_columns
def filter_noexpand_columns(columns): """Return columns not containing and containing the noexpand prefix. Parameters ---------- columns: sequence of str A sequence of strings to be split Returns ------- Two lists, the first containing strings without the noexpand prefix, the second containing those that do with the prefix filtered out. """ prefix_len = len(NOEXPAND_PREFIX) noexpand = [c[prefix_len:] for c in columns if c.startswith(NOEXPAND_PREFIX)] other = [c for c in columns if not c.startswith(NOEXPAND_PREFIX)] return other, noexpand
python
def filter_noexpand_columns(columns): """Return columns not containing and containing the noexpand prefix. Parameters ---------- columns: sequence of str A sequence of strings to be split Returns ------- Two lists, the first containing strings without the noexpand prefix, the second containing those that do with the prefix filtered out. """ prefix_len = len(NOEXPAND_PREFIX) noexpand = [c[prefix_len:] for c in columns if c.startswith(NOEXPAND_PREFIX)] other = [c for c in columns if not c.startswith(NOEXPAND_PREFIX)] return other, noexpand
[ "def", "filter_noexpand_columns", "(", "columns", ")", ":", "prefix_len", "=", "len", "(", "NOEXPAND_PREFIX", ")", "noexpand", "=", "[", "c", "[", "prefix_len", ":", "]", "for", "c", "in", "columns", "if", "c", ".", "startswith", "(", "NOEXPAND_PREFIX", ")", "]", "other", "=", "[", "c", "for", "c", "in", "columns", "if", "not", "c", ".", "startswith", "(", "NOEXPAND_PREFIX", ")", "]", "return", "other", ",", "noexpand" ]
Return columns not containing and containing the noexpand prefix. Parameters ---------- columns: sequence of str A sequence of strings to be split Returns ------- Two lists, the first containing strings without the noexpand prefix, the second containing those that do with the prefix filtered out.
[ "Return", "columns", "not", "containing", "and", "containing", "the", "noexpand", "prefix", "." ]
57991a4feaeb9213575cfba7a369fc05cc0d846b
https://github.com/scikit-hep/root_pandas/blob/57991a4feaeb9213575cfba7a369fc05cc0d846b/root_pandas/readwrite.py#L117-L133
16,915
scikit-hep/root_pandas
root_pandas/readwrite.py
to_root
def to_root(df, path, key='my_ttree', mode='w', store_index=True, *args, **kwargs): """ Write DataFrame to a ROOT file. Parameters ---------- path: string File path to new ROOT file (will be overwritten) key: string Name of tree that the DataFrame will be saved as mode: string, {'w', 'a'} Mode that the file should be opened in (default: 'w') store_index: bool (optional, default: True) Whether the index of the DataFrame should be stored as an __index__* branch in the tree Notes ----- Further *args and *kwargs are passed to root_numpy's array2root. >>> df = DataFrame({'x': [1,2,3], 'y': [4,5,6]}) >>> df.to_root('test.root') The DataFrame index will be saved as a branch called '__index__*', where * is the name of the index in the original DataFrame """ if mode == 'a': mode = 'update' elif mode == 'w': mode = 'recreate' else: raise ValueError('Unknown mode: {}. Must be "a" or "w".'.format(mode)) from root_numpy import array2tree # We don't want to modify the user's DataFrame here, so we make a shallow copy df_ = df.copy(deep=False) if store_index: name = df_.index.name if name is None: # Handle the case where the index has no name name = '' df_['__index__' + name] = df_.index # Convert categorical columns into something root_numpy can serialise for col in df_.select_dtypes(['category']).columns: name_components = ['__rpCaT', col, str(df_[col].cat.ordered)] name_components.extend(df_[col].cat.categories) if ['*' not in c for c in name_components]: sep = '*' else: raise ValueError('Unable to find suitable separator for columns') df_[col] = df_[col].cat.codes df_.rename(index=str, columns={col: sep.join(name_components)}, inplace=True) arr = df_.to_records(index=False) root_file = ROOT.TFile.Open(path, mode) if not root_file: raise IOError("cannot open file {0}".format(path)) if not root_file.IsWritable(): raise IOError("file {0} is not writable".format(path)) # Navigate to the requested directory open_dirs = [root_file] for dir_name in key.split('/')[:-1]: current_dir = open_dirs[-1].Get(dir_name) if not current_dir: current_dir = open_dirs[-1].mkdir(dir_name) current_dir.cd() open_dirs.append(current_dir) # The key is now just the top component key = key.split('/')[-1] # If a tree with that name exists, we want to update it tree = open_dirs[-1].Get(key) if not tree: tree = None tree = array2tree(arr, name=key, tree=tree) tree.Write(key, ROOT.TFile.kOverwrite) root_file.Close()
python
def to_root(df, path, key='my_ttree', mode='w', store_index=True, *args, **kwargs): """ Write DataFrame to a ROOT file. Parameters ---------- path: string File path to new ROOT file (will be overwritten) key: string Name of tree that the DataFrame will be saved as mode: string, {'w', 'a'} Mode that the file should be opened in (default: 'w') store_index: bool (optional, default: True) Whether the index of the DataFrame should be stored as an __index__* branch in the tree Notes ----- Further *args and *kwargs are passed to root_numpy's array2root. >>> df = DataFrame({'x': [1,2,3], 'y': [4,5,6]}) >>> df.to_root('test.root') The DataFrame index will be saved as a branch called '__index__*', where * is the name of the index in the original DataFrame """ if mode == 'a': mode = 'update' elif mode == 'w': mode = 'recreate' else: raise ValueError('Unknown mode: {}. Must be "a" or "w".'.format(mode)) from root_numpy import array2tree # We don't want to modify the user's DataFrame here, so we make a shallow copy df_ = df.copy(deep=False) if store_index: name = df_.index.name if name is None: # Handle the case where the index has no name name = '' df_['__index__' + name] = df_.index # Convert categorical columns into something root_numpy can serialise for col in df_.select_dtypes(['category']).columns: name_components = ['__rpCaT', col, str(df_[col].cat.ordered)] name_components.extend(df_[col].cat.categories) if ['*' not in c for c in name_components]: sep = '*' else: raise ValueError('Unable to find suitable separator for columns') df_[col] = df_[col].cat.codes df_.rename(index=str, columns={col: sep.join(name_components)}, inplace=True) arr = df_.to_records(index=False) root_file = ROOT.TFile.Open(path, mode) if not root_file: raise IOError("cannot open file {0}".format(path)) if not root_file.IsWritable(): raise IOError("file {0} is not writable".format(path)) # Navigate to the requested directory open_dirs = [root_file] for dir_name in key.split('/')[:-1]: current_dir = open_dirs[-1].Get(dir_name) if not current_dir: current_dir = open_dirs[-1].mkdir(dir_name) current_dir.cd() open_dirs.append(current_dir) # The key is now just the top component key = key.split('/')[-1] # If a tree with that name exists, we want to update it tree = open_dirs[-1].Get(key) if not tree: tree = None tree = array2tree(arr, name=key, tree=tree) tree.Write(key, ROOT.TFile.kOverwrite) root_file.Close()
[ "def", "to_root", "(", "df", ",", "path", ",", "key", "=", "'my_ttree'", ",", "mode", "=", "'w'", ",", "store_index", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "==", "'a'", ":", "mode", "=", "'update'", "elif", "mode", "==", "'w'", ":", "mode", "=", "'recreate'", "else", ":", "raise", "ValueError", "(", "'Unknown mode: {}. Must be \"a\" or \"w\".'", ".", "format", "(", "mode", ")", ")", "from", "root_numpy", "import", "array2tree", "# We don't want to modify the user's DataFrame here, so we make a shallow copy", "df_", "=", "df", ".", "copy", "(", "deep", "=", "False", ")", "if", "store_index", ":", "name", "=", "df_", ".", "index", ".", "name", "if", "name", "is", "None", ":", "# Handle the case where the index has no name", "name", "=", "''", "df_", "[", "'__index__'", "+", "name", "]", "=", "df_", ".", "index", "# Convert categorical columns into something root_numpy can serialise", "for", "col", "in", "df_", ".", "select_dtypes", "(", "[", "'category'", "]", ")", ".", "columns", ":", "name_components", "=", "[", "'__rpCaT'", ",", "col", ",", "str", "(", "df_", "[", "col", "]", ".", "cat", ".", "ordered", ")", "]", "name_components", ".", "extend", "(", "df_", "[", "col", "]", ".", "cat", ".", "categories", ")", "if", "[", "'*'", "not", "in", "c", "for", "c", "in", "name_components", "]", ":", "sep", "=", "'*'", "else", ":", "raise", "ValueError", "(", "'Unable to find suitable separator for columns'", ")", "df_", "[", "col", "]", "=", "df_", "[", "col", "]", ".", "cat", ".", "codes", "df_", ".", "rename", "(", "index", "=", "str", ",", "columns", "=", "{", "col", ":", "sep", ".", "join", "(", "name_components", ")", "}", ",", "inplace", "=", "True", ")", "arr", "=", "df_", ".", "to_records", "(", "index", "=", "False", ")", "root_file", "=", "ROOT", ".", "TFile", ".", "Open", "(", "path", ",", "mode", ")", "if", "not", "root_file", ":", "raise", "IOError", "(", "\"cannot open file {0}\"", ".", "format", "(", "path", ")", ")", "if", "not", "root_file", ".", "IsWritable", "(", ")", ":", "raise", "IOError", "(", "\"file {0} is not writable\"", ".", "format", "(", "path", ")", ")", "# Navigate to the requested directory", "open_dirs", "=", "[", "root_file", "]", "for", "dir_name", "in", "key", ".", "split", "(", "'/'", ")", "[", ":", "-", "1", "]", ":", "current_dir", "=", "open_dirs", "[", "-", "1", "]", ".", "Get", "(", "dir_name", ")", "if", "not", "current_dir", ":", "current_dir", "=", "open_dirs", "[", "-", "1", "]", ".", "mkdir", "(", "dir_name", ")", "current_dir", ".", "cd", "(", ")", "open_dirs", ".", "append", "(", "current_dir", ")", "# The key is now just the top component", "key", "=", "key", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "# If a tree with that name exists, we want to update it", "tree", "=", "open_dirs", "[", "-", "1", "]", ".", "Get", "(", "key", ")", "if", "not", "tree", ":", "tree", "=", "None", "tree", "=", "array2tree", "(", "arr", ",", "name", "=", "key", ",", "tree", "=", "tree", ")", "tree", ".", "Write", "(", "key", ",", "ROOT", ".", "TFile", ".", "kOverwrite", ")", "root_file", ".", "Close", "(", ")" ]
Write DataFrame to a ROOT file. Parameters ---------- path: string File path to new ROOT file (will be overwritten) key: string Name of tree that the DataFrame will be saved as mode: string, {'w', 'a'} Mode that the file should be opened in (default: 'w') store_index: bool (optional, default: True) Whether the index of the DataFrame should be stored as an __index__* branch in the tree Notes ----- Further *args and *kwargs are passed to root_numpy's array2root. >>> df = DataFrame({'x': [1,2,3], 'y': [4,5,6]}) >>> df.to_root('test.root') The DataFrame index will be saved as a branch called '__index__*', where * is the name of the index in the original DataFrame
[ "Write", "DataFrame", "to", "a", "ROOT", "file", "." ]
57991a4feaeb9213575cfba7a369fc05cc0d846b
https://github.com/scikit-hep/root_pandas/blob/57991a4feaeb9213575cfba7a369fc05cc0d846b/root_pandas/readwrite.py#L334-L417
16,916
MisterY/gnucash-portfolio
gnucash_portfolio/reports/security_info.py
SecurityInfoReport.run
def run(self, symbol: str) -> SecurityDetailsViewModel: """ Loads the model for security details """ from pydatum import Datum svc = self._svc sec_agg = svc.securities.get_aggregate_for_symbol(symbol) model = SecurityDetailsViewModel() model.symbol = sec_agg.security.namespace + ":" + sec_agg.security.mnemonic model.security = sec_agg.security # Quantity model.quantity = sec_agg.get_quantity() model.value = sec_agg.get_value() currency = sec_agg.get_currency() if currency: assert isinstance(currency, str) model.currency = currency model.price = sec_agg.get_last_available_price() model.average_price = sec_agg.get_avg_price() # Here we take only the amount paid for the remaining stock. model.total_paid = sec_agg.get_total_paid_for_remaining_stock() # Profit/loss model.profit_loss = model.value - model.total_paid if model.total_paid: model.profit_loss_perc = abs(model.profit_loss) * 100 / model.total_paid else: model.profit_loss_perc = 0 if abs(model.value) < abs(model.total_paid): model.profit_loss_perc *= -1 # Income model.income = sec_agg.get_income_total() if model.total_paid: model.income_perc = model.income * 100 / model.total_paid else: model.income_perc = 0 # income in the last 12 months start = Datum() start.subtract_months(12) end = Datum() model.income_last_12m = sec_agg.get_income_in_period(start, end) if model.total_paid == 0: model.income_perc_last_12m = 0 else: model.income_perc_last_12m = model.income_last_12m * 100 / model.total_paid # Return of Capital roc = sec_agg.get_return_of_capital() model.return_of_capital = roc # total return model.total_return = model.profit_loss + model.income if model.total_paid: model.total_return_perc = model.total_return * 100 / model.total_paid else: model.total_return_perc = 0 # load all holding accounts model.accounts = sec_agg.accounts # Income accounts model.income_accounts = sec_agg.get_income_accounts() # Load asset classes to which this security belongs. # todo load asset allocation, find the parents for this symbol # svc.asset_allocation.load_config_only(svc.currencies.default_currency) # stocks = svc.asset_allocation.get_stock(model.symbol) # # for stock in stocks: # model.asset_classes.append(stock.asset_class) from asset_allocation import AppAggregate aa = AppAggregate() aa.open_session() aa.get_asset_classes_for_security(None, model.symbol) return model
python
def run(self, symbol: str) -> SecurityDetailsViewModel: """ Loads the model for security details """ from pydatum import Datum svc = self._svc sec_agg = svc.securities.get_aggregate_for_symbol(symbol) model = SecurityDetailsViewModel() model.symbol = sec_agg.security.namespace + ":" + sec_agg.security.mnemonic model.security = sec_agg.security # Quantity model.quantity = sec_agg.get_quantity() model.value = sec_agg.get_value() currency = sec_agg.get_currency() if currency: assert isinstance(currency, str) model.currency = currency model.price = sec_agg.get_last_available_price() model.average_price = sec_agg.get_avg_price() # Here we take only the amount paid for the remaining stock. model.total_paid = sec_agg.get_total_paid_for_remaining_stock() # Profit/loss model.profit_loss = model.value - model.total_paid if model.total_paid: model.profit_loss_perc = abs(model.profit_loss) * 100 / model.total_paid else: model.profit_loss_perc = 0 if abs(model.value) < abs(model.total_paid): model.profit_loss_perc *= -1 # Income model.income = sec_agg.get_income_total() if model.total_paid: model.income_perc = model.income * 100 / model.total_paid else: model.income_perc = 0 # income in the last 12 months start = Datum() start.subtract_months(12) end = Datum() model.income_last_12m = sec_agg.get_income_in_period(start, end) if model.total_paid == 0: model.income_perc_last_12m = 0 else: model.income_perc_last_12m = model.income_last_12m * 100 / model.total_paid # Return of Capital roc = sec_agg.get_return_of_capital() model.return_of_capital = roc # total return model.total_return = model.profit_loss + model.income if model.total_paid: model.total_return_perc = model.total_return * 100 / model.total_paid else: model.total_return_perc = 0 # load all holding accounts model.accounts = sec_agg.accounts # Income accounts model.income_accounts = sec_agg.get_income_accounts() # Load asset classes to which this security belongs. # todo load asset allocation, find the parents for this symbol # svc.asset_allocation.load_config_only(svc.currencies.default_currency) # stocks = svc.asset_allocation.get_stock(model.symbol) # # for stock in stocks: # model.asset_classes.append(stock.asset_class) from asset_allocation import AppAggregate aa = AppAggregate() aa.open_session() aa.get_asset_classes_for_security(None, model.symbol) return model
[ "def", "run", "(", "self", ",", "symbol", ":", "str", ")", "->", "SecurityDetailsViewModel", ":", "from", "pydatum", "import", "Datum", "svc", "=", "self", ".", "_svc", "sec_agg", "=", "svc", ".", "securities", ".", "get_aggregate_for_symbol", "(", "symbol", ")", "model", "=", "SecurityDetailsViewModel", "(", ")", "model", ".", "symbol", "=", "sec_agg", ".", "security", ".", "namespace", "+", "\":\"", "+", "sec_agg", ".", "security", ".", "mnemonic", "model", ".", "security", "=", "sec_agg", ".", "security", "# Quantity", "model", ".", "quantity", "=", "sec_agg", ".", "get_quantity", "(", ")", "model", ".", "value", "=", "sec_agg", ".", "get_value", "(", ")", "currency", "=", "sec_agg", ".", "get_currency", "(", ")", "if", "currency", ":", "assert", "isinstance", "(", "currency", ",", "str", ")", "model", ".", "currency", "=", "currency", "model", ".", "price", "=", "sec_agg", ".", "get_last_available_price", "(", ")", "model", ".", "average_price", "=", "sec_agg", ".", "get_avg_price", "(", ")", "# Here we take only the amount paid for the remaining stock.", "model", ".", "total_paid", "=", "sec_agg", ".", "get_total_paid_for_remaining_stock", "(", ")", "# Profit/loss", "model", ".", "profit_loss", "=", "model", ".", "value", "-", "model", ".", "total_paid", "if", "model", ".", "total_paid", ":", "model", ".", "profit_loss_perc", "=", "abs", "(", "model", ".", "profit_loss", ")", "*", "100", "/", "model", ".", "total_paid", "else", ":", "model", ".", "profit_loss_perc", "=", "0", "if", "abs", "(", "model", ".", "value", ")", "<", "abs", "(", "model", ".", "total_paid", ")", ":", "model", ".", "profit_loss_perc", "*=", "-", "1", "# Income", "model", ".", "income", "=", "sec_agg", ".", "get_income_total", "(", ")", "if", "model", ".", "total_paid", ":", "model", ".", "income_perc", "=", "model", ".", "income", "*", "100", "/", "model", ".", "total_paid", "else", ":", "model", ".", "income_perc", "=", "0", "# income in the last 12 months", "start", "=", "Datum", "(", ")", "start", ".", "subtract_months", "(", "12", ")", "end", "=", "Datum", "(", ")", "model", ".", "income_last_12m", "=", "sec_agg", ".", "get_income_in_period", "(", "start", ",", "end", ")", "if", "model", ".", "total_paid", "==", "0", ":", "model", ".", "income_perc_last_12m", "=", "0", "else", ":", "model", ".", "income_perc_last_12m", "=", "model", ".", "income_last_12m", "*", "100", "/", "model", ".", "total_paid", "# Return of Capital", "roc", "=", "sec_agg", ".", "get_return_of_capital", "(", ")", "model", ".", "return_of_capital", "=", "roc", "# total return", "model", ".", "total_return", "=", "model", ".", "profit_loss", "+", "model", ".", "income", "if", "model", ".", "total_paid", ":", "model", ".", "total_return_perc", "=", "model", ".", "total_return", "*", "100", "/", "model", ".", "total_paid", "else", ":", "model", ".", "total_return_perc", "=", "0", "# load all holding accounts", "model", ".", "accounts", "=", "sec_agg", ".", "accounts", "# Income accounts", "model", ".", "income_accounts", "=", "sec_agg", ".", "get_income_accounts", "(", ")", "# Load asset classes to which this security belongs.", "# todo load asset allocation, find the parents for this symbol", "# svc.asset_allocation.load_config_only(svc.currencies.default_currency)", "# stocks = svc.asset_allocation.get_stock(model.symbol)", "#", "# for stock in stocks:", "# model.asset_classes.append(stock.asset_class)", "from", "asset_allocation", "import", "AppAggregate", "aa", "=", "AppAggregate", "(", ")", "aa", ".", "open_session", "(", ")", "aa", ".", "get_asset_classes_for_security", "(", "None", ",", "model", ".", "symbol", ")", "return", "model" ]
Loads the model for security details
[ "Loads", "the", "model", "for", "security", "details" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/reports/security_info.py#L15-L93
16,917
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
handle_friday
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum): """ Extracted the calculation for when the next_day is Friday """ assert isinstance(next_date, Datum) assert isinstance(start_date, Datum) # Starting from line 220. tmp_sat = next_date.clone() tmp_sat.add_days(1) tmp_sun = next_date.clone() tmp_sun.add_days(2) if period == RecurrencePeriod.END_OF_MONTH.value: if (next_date.is_end_of_month() or tmp_sat.is_end_of_month() or tmp_sun.is_end_of_month()): next_date.add_months(1) else: next_date.add_months(mult - 1) else: if tmp_sat.get_day_name() == start_date.get_day_name(): next_date.add_days(1) next_date.add_months(mult) elif tmp_sun.get_day_name() == start_date.get_day_name(): next_date.add_days(2) next_date.add_months(mult) elif next_date.get_day() >= start_date.get_day(): next_date.add_months(mult) elif next_date.is_end_of_month(): next_date.add_months(mult) elif tmp_sat.is_end_of_month(): next_date.add_days(1) next_date.add_months(mult) elif tmp_sun.is_end_of_month(): next_date.add_days(2) next_date.add_months(mult) else: # /* one fewer month fwd because of the occurrence in this month */ next_date.subtract_months(1) return next_date
python
def handle_friday(next_date: Datum, period: str, mult: int, start_date: Datum): """ Extracted the calculation for when the next_day is Friday """ assert isinstance(next_date, Datum) assert isinstance(start_date, Datum) # Starting from line 220. tmp_sat = next_date.clone() tmp_sat.add_days(1) tmp_sun = next_date.clone() tmp_sun.add_days(2) if period == RecurrencePeriod.END_OF_MONTH.value: if (next_date.is_end_of_month() or tmp_sat.is_end_of_month() or tmp_sun.is_end_of_month()): next_date.add_months(1) else: next_date.add_months(mult - 1) else: if tmp_sat.get_day_name() == start_date.get_day_name(): next_date.add_days(1) next_date.add_months(mult) elif tmp_sun.get_day_name() == start_date.get_day_name(): next_date.add_days(2) next_date.add_months(mult) elif next_date.get_day() >= start_date.get_day(): next_date.add_months(mult) elif next_date.is_end_of_month(): next_date.add_months(mult) elif tmp_sat.is_end_of_month(): next_date.add_days(1) next_date.add_months(mult) elif tmp_sun.is_end_of_month(): next_date.add_days(2) next_date.add_months(mult) else: # /* one fewer month fwd because of the occurrence in this month */ next_date.subtract_months(1) return next_date
[ "def", "handle_friday", "(", "next_date", ":", "Datum", ",", "period", ":", "str", ",", "mult", ":", "int", ",", "start_date", ":", "Datum", ")", ":", "assert", "isinstance", "(", "next_date", ",", "Datum", ")", "assert", "isinstance", "(", "start_date", ",", "Datum", ")", "# Starting from line 220.", "tmp_sat", "=", "next_date", ".", "clone", "(", ")", "tmp_sat", ".", "add_days", "(", "1", ")", "tmp_sun", "=", "next_date", ".", "clone", "(", ")", "tmp_sun", ".", "add_days", "(", "2", ")", "if", "period", "==", "RecurrencePeriod", ".", "END_OF_MONTH", ".", "value", ":", "if", "(", "next_date", ".", "is_end_of_month", "(", ")", "or", "tmp_sat", ".", "is_end_of_month", "(", ")", "or", "tmp_sun", ".", "is_end_of_month", "(", ")", ")", ":", "next_date", ".", "add_months", "(", "1", ")", "else", ":", "next_date", ".", "add_months", "(", "mult", "-", "1", ")", "else", ":", "if", "tmp_sat", ".", "get_day_name", "(", ")", "==", "start_date", ".", "get_day_name", "(", ")", ":", "next_date", ".", "add_days", "(", "1", ")", "next_date", ".", "add_months", "(", "mult", ")", "elif", "tmp_sun", ".", "get_day_name", "(", ")", "==", "start_date", ".", "get_day_name", "(", ")", ":", "next_date", ".", "add_days", "(", "2", ")", "next_date", ".", "add_months", "(", "mult", ")", "elif", "next_date", ".", "get_day", "(", ")", ">=", "start_date", ".", "get_day", "(", ")", ":", "next_date", ".", "add_months", "(", "mult", ")", "elif", "next_date", ".", "is_end_of_month", "(", ")", ":", "next_date", ".", "add_months", "(", "mult", ")", "elif", "tmp_sat", ".", "is_end_of_month", "(", ")", ":", "next_date", ".", "add_days", "(", "1", ")", "next_date", ".", "add_months", "(", "mult", ")", "elif", "tmp_sun", ".", "is_end_of_month", "(", ")", ":", "next_date", ".", "add_days", "(", "2", ")", "next_date", ".", "add_months", "(", "mult", ")", "else", ":", "# /* one fewer month fwd because of the occurrence in this month */", "next_date", ".", "subtract_months", "(", "1", ")", "return", "next_date" ]
Extracted the calculation for when the next_day is Friday
[ "Extracted", "the", "calculation", "for", "when", "the", "next_day", "is", "Friday" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L173-L212
16,918
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
ScheduledTxAggregate.get_next_occurrence
def get_next_occurrence(self) -> date: """ Returns the next occurrence date for transaction """ result = get_next_occurrence(self.transaction) assert isinstance(result, date) return result
python
def get_next_occurrence(self) -> date: """ Returns the next occurrence date for transaction """ result = get_next_occurrence(self.transaction) assert isinstance(result, date) return result
[ "def", "get_next_occurrence", "(", "self", ")", "->", "date", ":", "result", "=", "get_next_occurrence", "(", "self", ".", "transaction", ")", "assert", "isinstance", "(", "result", ",", "date", ")", "return", "result" ]
Returns the next occurrence date for transaction
[ "Returns", "the", "next", "occurrence", "date", "for", "transaction" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L222-L226
16,919
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
ScheduledTxsAggregate.get_enabled
def get_enabled(self) -> List[ScheduledTransaction]: """ Returns only enabled scheduled transactions """ query = ( self.query .filter(ScheduledTransaction.enabled == True) ) return query.all()
python
def get_enabled(self) -> List[ScheduledTransaction]: """ Returns only enabled scheduled transactions """ query = ( self.query .filter(ScheduledTransaction.enabled == True) ) return query.all()
[ "def", "get_enabled", "(", "self", ")", "->", "List", "[", "ScheduledTransaction", "]", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "ScheduledTransaction", ".", "enabled", "==", "True", ")", ")", "return", "query", ".", "all", "(", ")" ]
Returns only enabled scheduled transactions
[ "Returns", "only", "enabled", "scheduled", "transactions" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L254-L260
16,920
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
ScheduledTxsAggregate.get_by_id
def get_by_id(self, tx_id: str) -> ScheduledTransaction: """ Fetches a tx by id """ return self.query.filter(ScheduledTransaction.guid == tx_id).first()
python
def get_by_id(self, tx_id: str) -> ScheduledTransaction: """ Fetches a tx by id """ return self.query.filter(ScheduledTransaction.guid == tx_id).first()
[ "def", "get_by_id", "(", "self", ",", "tx_id", ":", "str", ")", "->", "ScheduledTransaction", ":", "return", "self", ".", "query", ".", "filter", "(", "ScheduledTransaction", ".", "guid", "==", "tx_id", ")", ".", "first", "(", ")" ]
Fetches a tx by id
[ "Fetches", "a", "tx", "by", "id" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L262-L264
16,921
MisterY/gnucash-portfolio
gnucash_portfolio/scheduledtxaggregate.py
ScheduledTxsAggregate.get_aggregate_by_id
def get_aggregate_by_id(self, tx_id: str) -> ScheduledTxAggregate: """ Creates an aggregate for single entity """ tran = self.get_by_id(tx_id) return self.get_aggregate_for(tran)
python
def get_aggregate_by_id(self, tx_id: str) -> ScheduledTxAggregate: """ Creates an aggregate for single entity """ tran = self.get_by_id(tx_id) return self.get_aggregate_for(tran)
[ "def", "get_aggregate_by_id", "(", "self", ",", "tx_id", ":", "str", ")", "->", "ScheduledTxAggregate", ":", "tran", "=", "self", ".", "get_by_id", "(", "tx_id", ")", "return", "self", ".", "get_aggregate_for", "(", "tran", ")" ]
Creates an aggregate for single entity
[ "Creates", "an", "aggregate", "for", "single", "entity" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/scheduledtxaggregate.py#L270-L273
16,922
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_avg_price_stat
def get_avg_price_stat(self) -> Decimal: """ Calculates the statistical average price for the security, by averaging only the prices paid. Very simple first implementation. """ avg_price = Decimal(0) price_total = Decimal(0) price_count = 0 for account in self.security.accounts: # Ignore trading accounts. if account.type == AccountType.TRADING.name: continue for split in account.splits: # Don't count the non-transactions. if split.quantity == 0: continue price = split.value / split.quantity price_count += 1 price_total += price if price_count: avg_price = price_total / price_count return avg_price
python
def get_avg_price_stat(self) -> Decimal: """ Calculates the statistical average price for the security, by averaging only the prices paid. Very simple first implementation. """ avg_price = Decimal(0) price_total = Decimal(0) price_count = 0 for account in self.security.accounts: # Ignore trading accounts. if account.type == AccountType.TRADING.name: continue for split in account.splits: # Don't count the non-transactions. if split.quantity == 0: continue price = split.value / split.quantity price_count += 1 price_total += price if price_count: avg_price = price_total / price_count return avg_price
[ "def", "get_avg_price_stat", "(", "self", ")", "->", "Decimal", ":", "avg_price", "=", "Decimal", "(", "0", ")", "price_total", "=", "Decimal", "(", "0", ")", "price_count", "=", "0", "for", "account", "in", "self", ".", "security", ".", "accounts", ":", "# Ignore trading accounts.", "if", "account", ".", "type", "==", "AccountType", ".", "TRADING", ".", "name", ":", "continue", "for", "split", "in", "account", ".", "splits", ":", "# Don't count the non-transactions.", "if", "split", ".", "quantity", "==", "0", ":", "continue", "price", "=", "split", ".", "value", "/", "split", ".", "quantity", "price_count", "+=", "1", "price_total", "+=", "price", "if", "price_count", ":", "avg_price", "=", "price_total", "/", "price_count", "return", "avg_price" ]
Calculates the statistical average price for the security, by averaging only the prices paid. Very simple first implementation.
[ "Calculates", "the", "statistical", "average", "price", "for", "the", "security", "by", "averaging", "only", "the", "prices", "paid", ".", "Very", "simple", "first", "implementation", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L41-L67
16,923
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_avg_price_fifo
def get_avg_price_fifo(self) -> Decimal: """ Calculates the average price paid for the security. security = Commodity Returns Decimal value. """ balance = self.get_quantity() if not balance: return Decimal(0) paid = Decimal(0) accounts = self.get_holding_accounts() # get unused splits (quantity and total paid) per account. for account in accounts: splits = self.get_available_splits_for_account(account) for split in splits: paid += split.value avg_price = paid / balance return avg_price
python
def get_avg_price_fifo(self) -> Decimal: """ Calculates the average price paid for the security. security = Commodity Returns Decimal value. """ balance = self.get_quantity() if not balance: return Decimal(0) paid = Decimal(0) accounts = self.get_holding_accounts() # get unused splits (quantity and total paid) per account. for account in accounts: splits = self.get_available_splits_for_account(account) for split in splits: paid += split.value avg_price = paid / balance return avg_price
[ "def", "get_avg_price_fifo", "(", "self", ")", "->", "Decimal", ":", "balance", "=", "self", ".", "get_quantity", "(", ")", "if", "not", "balance", ":", "return", "Decimal", "(", "0", ")", "paid", "=", "Decimal", "(", "0", ")", "accounts", "=", "self", ".", "get_holding_accounts", "(", ")", "# get unused splits (quantity and total paid) per account.", "for", "account", "in", "accounts", ":", "splits", "=", "self", ".", "get_available_splits_for_account", "(", "account", ")", "for", "split", "in", "splits", ":", "paid", "+=", "split", ".", "value", "avg_price", "=", "paid", "/", "balance", "return", "avg_price" ]
Calculates the average price paid for the security. security = Commodity Returns Decimal value.
[ "Calculates", "the", "average", "price", "paid", "for", "the", "security", ".", "security", "=", "Commodity", "Returns", "Decimal", "value", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L69-L89
16,924
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_available_splits_for_account
def get_available_splits_for_account(self, account: Account) -> List[Split]: """ Returns all unused splits in the account. Used for the calculation of avg.price. The split that has been partially used will have its quantity reduced to available quantity only. """ available_splits = [] # get all purchase splits in the account query = ( self.get_splits_query() .filter(Split.account == account) ) buy_splits = ( query.filter(Split.quantity > 0) .join(Transaction) .order_by(desc(Transaction.post_date)) ).all() buy_q = sum(split.quantity for split in buy_splits) sell_splits = query.filter(Split.quantity < 0).all() sell_q = sum(split.quantity for split in sell_splits) balance = buy_q + sell_q if balance == 0: return available_splits for real_split in buy_splits: split = splitmapper.map_split(real_split, SplitModel()) if split.quantity < balance: # take this split and reduce the balance. balance -= split.quantity else: # This is the last split. price = split.value / split.quantity # Take only the remaining quantity. split.quantity -= balance # Also adjust the value for easier calculation elsewhere. split.value = balance * price # The remaining balance is now distributed into splits. balance = 0 # add to the collection. available_splits.append(split) if balance == 0: break return available_splits
python
def get_available_splits_for_account(self, account: Account) -> List[Split]: """ Returns all unused splits in the account. Used for the calculation of avg.price. The split that has been partially used will have its quantity reduced to available quantity only. """ available_splits = [] # get all purchase splits in the account query = ( self.get_splits_query() .filter(Split.account == account) ) buy_splits = ( query.filter(Split.quantity > 0) .join(Transaction) .order_by(desc(Transaction.post_date)) ).all() buy_q = sum(split.quantity for split in buy_splits) sell_splits = query.filter(Split.quantity < 0).all() sell_q = sum(split.quantity for split in sell_splits) balance = buy_q + sell_q if balance == 0: return available_splits for real_split in buy_splits: split = splitmapper.map_split(real_split, SplitModel()) if split.quantity < balance: # take this split and reduce the balance. balance -= split.quantity else: # This is the last split. price = split.value / split.quantity # Take only the remaining quantity. split.quantity -= balance # Also adjust the value for easier calculation elsewhere. split.value = balance * price # The remaining balance is now distributed into splits. balance = 0 # add to the collection. available_splits.append(split) if balance == 0: break return available_splits
[ "def", "get_available_splits_for_account", "(", "self", ",", "account", ":", "Account", ")", "->", "List", "[", "Split", "]", ":", "available_splits", "=", "[", "]", "# get all purchase splits in the account", "query", "=", "(", "self", ".", "get_splits_query", "(", ")", ".", "filter", "(", "Split", ".", "account", "==", "account", ")", ")", "buy_splits", "=", "(", "query", ".", "filter", "(", "Split", ".", "quantity", ">", "0", ")", ".", "join", "(", "Transaction", ")", ".", "order_by", "(", "desc", "(", "Transaction", ".", "post_date", ")", ")", ")", ".", "all", "(", ")", "buy_q", "=", "sum", "(", "split", ".", "quantity", "for", "split", "in", "buy_splits", ")", "sell_splits", "=", "query", ".", "filter", "(", "Split", ".", "quantity", "<", "0", ")", ".", "all", "(", ")", "sell_q", "=", "sum", "(", "split", ".", "quantity", "for", "split", "in", "sell_splits", ")", "balance", "=", "buy_q", "+", "sell_q", "if", "balance", "==", "0", ":", "return", "available_splits", "for", "real_split", "in", "buy_splits", ":", "split", "=", "splitmapper", ".", "map_split", "(", "real_split", ",", "SplitModel", "(", ")", ")", "if", "split", ".", "quantity", "<", "balance", ":", "# take this split and reduce the balance.", "balance", "-=", "split", ".", "quantity", "else", ":", "# This is the last split.", "price", "=", "split", ".", "value", "/", "split", ".", "quantity", "# Take only the remaining quantity.", "split", ".", "quantity", "-=", "balance", "# Also adjust the value for easier calculation elsewhere.", "split", ".", "value", "=", "balance", "*", "price", "# The remaining balance is now distributed into splits.", "balance", "=", "0", "# add to the collection.", "available_splits", ".", "append", "(", "split", ")", "if", "balance", "==", "0", ":", "break", "return", "available_splits" ]
Returns all unused splits in the account. Used for the calculation of avg.price. The split that has been partially used will have its quantity reduced to available quantity only.
[ "Returns", "all", "unused", "splits", "in", "the", "account", ".", "Used", "for", "the", "calculation", "of", "avg", ".", "price", ".", "The", "split", "that", "has", "been", "partially", "used", "will", "have", "its", "quantity", "reduced", "to", "available", "quantity", "only", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L91-L133
16,925
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_num_shares
def get_num_shares(self) -> Decimal: """ Returns the number of shares at this time """ from pydatum import Datum today = Datum().today() return self.get_num_shares_on(today)
python
def get_num_shares(self) -> Decimal: """ Returns the number of shares at this time """ from pydatum import Datum today = Datum().today() return self.get_num_shares_on(today)
[ "def", "get_num_shares", "(", "self", ")", "->", "Decimal", ":", "from", "pydatum", "import", "Datum", "today", "=", "Datum", "(", ")", ".", "today", "(", ")", "return", "self", ".", "get_num_shares_on", "(", "today", ")" ]
Returns the number of shares at this time
[ "Returns", "the", "number", "of", "shares", "at", "this", "time" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L135-L139
16,926
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_last_available_price
def get_last_available_price(self) -> PriceModel: """ Finds the last available price for security. Uses PriceDb. """ price_db = PriceDbApplication() symbol = SecuritySymbol(self.security.namespace, self.security.mnemonic) result = price_db.get_latest_price(symbol) return result
python
def get_last_available_price(self) -> PriceModel: """ Finds the last available price for security. Uses PriceDb. """ price_db = PriceDbApplication() symbol = SecuritySymbol(self.security.namespace, self.security.mnemonic) result = price_db.get_latest_price(symbol) return result
[ "def", "get_last_available_price", "(", "self", ")", "->", "PriceModel", ":", "price_db", "=", "PriceDbApplication", "(", ")", "symbol", "=", "SecuritySymbol", "(", "self", ".", "security", ".", "namespace", ",", "self", ".", "security", ".", "mnemonic", ")", "result", "=", "price_db", ".", "get_latest_price", "(", "symbol", ")", "return", "result" ]
Finds the last available price for security. Uses PriceDb.
[ "Finds", "the", "last", "available", "price", "for", "security", ".", "Uses", "PriceDb", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L154-L159
16,927
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.__get_holding_accounts_query
def __get_holding_accounts_query(self): """ Returns all holding accounts, except Trading accounts. """ query = ( self.book.session.query(Account) .filter(Account.commodity == self.security) .filter(Account.type != AccountType.trading.value) ) # generic.print_sql(query) return query
python
def __get_holding_accounts_query(self): """ Returns all holding accounts, except Trading accounts. """ query = ( self.book.session.query(Account) .filter(Account.commodity == self.security) .filter(Account.type != AccountType.trading.value) ) # generic.print_sql(query) return query
[ "def", "__get_holding_accounts_query", "(", "self", ")", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Account", ")", ".", "filter", "(", "Account", ".", "commodity", "==", "self", ".", "security", ")", ".", "filter", "(", "Account", ".", "type", "!=", "AccountType", ".", "trading", ".", "value", ")", ")", "# generic.print_sql(query)", "return", "query" ]
Returns all holding accounts, except Trading accounts.
[ "Returns", "all", "holding", "accounts", "except", "Trading", "accounts", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L180-L188
16,928
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_income_accounts
def get_income_accounts(self) -> List[Account]: """ Returns all income accounts for this security. Income accounts are accounts not under Trading, expressed in currency, and having the same name as the mnemonic. They should be under Assets but this requires a recursive SQL query. """ # trading = self.book.trading_account(self.security) # log(DEBUG, "trading account = %s, %s", trading.fullname, trading.guid) # Example on how to self-link, i.e. parent account, using alias. # parent_alias = aliased(Account) # .join(parent_alias, Account.parent) # parent_alias.parent_guid != trading.guid query = ( self.book.session.query(Account) .join(Commodity) .filter(Account.name == self.security.mnemonic) .filter(Commodity.namespace == "CURRENCY") # .filter(Account.type != "TRADING") .filter(Account.type == AccountType.income.value) ) # generic.print_sql(query) return query.all()
python
def get_income_accounts(self) -> List[Account]: """ Returns all income accounts for this security. Income accounts are accounts not under Trading, expressed in currency, and having the same name as the mnemonic. They should be under Assets but this requires a recursive SQL query. """ # trading = self.book.trading_account(self.security) # log(DEBUG, "trading account = %s, %s", trading.fullname, trading.guid) # Example on how to self-link, i.e. parent account, using alias. # parent_alias = aliased(Account) # .join(parent_alias, Account.parent) # parent_alias.parent_guid != trading.guid query = ( self.book.session.query(Account) .join(Commodity) .filter(Account.name == self.security.mnemonic) .filter(Commodity.namespace == "CURRENCY") # .filter(Account.type != "TRADING") .filter(Account.type == AccountType.income.value) ) # generic.print_sql(query) return query.all()
[ "def", "get_income_accounts", "(", "self", ")", "->", "List", "[", "Account", "]", ":", "# trading = self.book.trading_account(self.security)", "# log(DEBUG, \"trading account = %s, %s\", trading.fullname, trading.guid)", "# Example on how to self-link, i.e. parent account, using alias.", "# parent_alias = aliased(Account)", "# .join(parent_alias, Account.parent)", "# parent_alias.parent_guid != trading.guid", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Account", ")", ".", "join", "(", "Commodity", ")", ".", "filter", "(", "Account", ".", "name", "==", "self", ".", "security", ".", "mnemonic", ")", ".", "filter", "(", "Commodity", ".", "namespace", "==", "\"CURRENCY\"", ")", "# .filter(Account.type != \"TRADING\")", ".", "filter", "(", "Account", ".", "type", "==", "AccountType", ".", "income", ".", "value", ")", ")", "# generic.print_sql(query)", "return", "query", ".", "all", "(", ")" ]
Returns all income accounts for this security. Income accounts are accounts not under Trading, expressed in currency, and having the same name as the mnemonic. They should be under Assets but this requires a recursive SQL query.
[ "Returns", "all", "income", "accounts", "for", "this", "security", ".", "Income", "accounts", "are", "accounts", "not", "under", "Trading", "expressed", "in", "currency", "and", "having", "the", "same", "name", "as", "the", "mnemonic", ".", "They", "should", "be", "under", "Assets", "but", "this", "requires", "a", "recursive", "SQL", "query", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L190-L214
16,929
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_income_total
def get_income_total(self) -> Decimal: """ Sum of all income = sum of balances of all income accounts. """ accounts = self.get_income_accounts() # log(DEBUG, "income accounts: %s", accounts) income = Decimal(0) for acct in accounts: income += acct.get_balance() return income
python
def get_income_total(self) -> Decimal: """ Sum of all income = sum of balances of all income accounts. """ accounts = self.get_income_accounts() # log(DEBUG, "income accounts: %s", accounts) income = Decimal(0) for acct in accounts: income += acct.get_balance() return income
[ "def", "get_income_total", "(", "self", ")", "->", "Decimal", ":", "accounts", "=", "self", ".", "get_income_accounts", "(", ")", "# log(DEBUG, \"income accounts: %s\", accounts)", "income", "=", "Decimal", "(", "0", ")", "for", "acct", "in", "accounts", ":", "income", "+=", "acct", ".", "get_balance", "(", ")", "return", "income" ]
Sum of all income = sum of balances of all income accounts.
[ "Sum", "of", "all", "income", "=", "sum", "of", "balances", "of", "all", "income", "accounts", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L216-L223
16,930
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_income_in_period
def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: """ Returns all income in the given period """ accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg.get_balance_in_period(start, end) income += acc_bal return income
python
def get_income_in_period(self, start: datetime, end: datetime) -> Decimal: """ Returns all income in the given period """ accounts = self.get_income_accounts() income = Decimal(0) for acct in accounts: acc_agg = AccountAggregate(self.book, acct) acc_bal = acc_agg.get_balance_in_period(start, end) income += acc_bal return income
[ "def", "get_income_in_period", "(", "self", ",", "start", ":", "datetime", ",", "end", ":", "datetime", ")", "->", "Decimal", ":", "accounts", "=", "self", ".", "get_income_accounts", "(", ")", "income", "=", "Decimal", "(", "0", ")", "for", "acct", "in", "accounts", ":", "acc_agg", "=", "AccountAggregate", "(", "self", ".", "book", ",", "acct", ")", "acc_bal", "=", "acc_agg", ".", "get_balance_in_period", "(", "start", ",", "end", ")", "income", "+=", "acc_bal", "return", "income" ]
Returns all income in the given period
[ "Returns", "all", "income", "in", "the", "given", "period" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L225-L234
16,931
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_prices
def get_prices(self) -> List[PriceModel]: """ Returns all available prices for security """ # return self.security.prices.order_by(Price.date) from pricedb.dal import Price pricedb = PriceDbApplication() repo = pricedb.get_price_repository() query = (repo.query(Price) .filter(Price.namespace == self.security.namespace) .filter(Price.symbol == self.security.mnemonic) .orderby_desc(Price.date) ) return query.all()
python
def get_prices(self) -> List[PriceModel]: """ Returns all available prices for security """ # return self.security.prices.order_by(Price.date) from pricedb.dal import Price pricedb = PriceDbApplication() repo = pricedb.get_price_repository() query = (repo.query(Price) .filter(Price.namespace == self.security.namespace) .filter(Price.symbol == self.security.mnemonic) .orderby_desc(Price.date) ) return query.all()
[ "def", "get_prices", "(", "self", ")", "->", "List", "[", "PriceModel", "]", ":", "# return self.security.prices.order_by(Price.date)", "from", "pricedb", ".", "dal", "import", "Price", "pricedb", "=", "PriceDbApplication", "(", ")", "repo", "=", "pricedb", ".", "get_price_repository", "(", ")", "query", "=", "(", "repo", ".", "query", "(", "Price", ")", ".", "filter", "(", "Price", ".", "namespace", "==", "self", ".", "security", ".", "namespace", ")", ".", "filter", "(", "Price", ".", "symbol", "==", "self", ".", "security", ".", "mnemonic", ")", ".", "orderby_desc", "(", "Price", ".", "date", ")", ")", "return", "query", ".", "all", "(", ")" ]
Returns all available prices for security
[ "Returns", "all", "available", "prices", "for", "security" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L236-L248
16,932
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_quantity
def get_quantity(self) -> Decimal: """ Returns the number of shares for the given security. It gets the number from all the accounts in the book. """ from pydatum import Datum # Use today's date but reset hour and lower. today = Datum() today.today() today.end_of_day() return self.get_num_shares_on(today.value)
python
def get_quantity(self) -> Decimal: """ Returns the number of shares for the given security. It gets the number from all the accounts in the book. """ from pydatum import Datum # Use today's date but reset hour and lower. today = Datum() today.today() today.end_of_day() return self.get_num_shares_on(today.value)
[ "def", "get_quantity", "(", "self", ")", "->", "Decimal", ":", "from", "pydatum", "import", "Datum", "# Use today's date but reset hour and lower.", "today", "=", "Datum", "(", ")", "today", ".", "today", "(", ")", "today", ".", "end_of_day", "(", ")", "return", "self", ".", "get_num_shares_on", "(", "today", ".", "value", ")" ]
Returns the number of shares for the given security. It gets the number from all the accounts in the book.
[ "Returns", "the", "number", "of", "shares", "for", "the", "given", "security", ".", "It", "gets", "the", "number", "from", "all", "the", "accounts", "in", "the", "book", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L250-L260
16,933
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_splits_query
def get_splits_query(self): """ Returns the query for all splits for this security """ query = ( self.book.session.query(Split) .join(Account) .filter(Account.type != AccountType.trading.value) .filter(Account.commodity_guid == self.security.guid) ) return query
python
def get_splits_query(self): """ Returns the query for all splits for this security """ query = ( self.book.session.query(Split) .join(Account) .filter(Account.type != AccountType.trading.value) .filter(Account.commodity_guid == self.security.guid) ) return query
[ "def", "get_splits_query", "(", "self", ")", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Split", ")", ".", "join", "(", "Account", ")", ".", "filter", "(", "Account", ".", "type", "!=", "AccountType", ".", "trading", ".", "value", ")", ".", "filter", "(", "Account", ".", "commodity_guid", "==", "self", ".", "security", ".", "guid", ")", ")", "return", "query" ]
Returns the query for all splits for this security
[ "Returns", "the", "query", "for", "all", "splits", "for", "this", "security" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L262-L270
16,934
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_total_paid
def get_total_paid(self) -> Decimal: """ Returns the total amount paid, in currency, for the stocks owned """ query = ( self.get_splits_query() ) splits = query.all() total = Decimal(0) for split in splits: total += split.value return total
python
def get_total_paid(self) -> Decimal: """ Returns the total amount paid, in currency, for the stocks owned """ query = ( self.get_splits_query() ) splits = query.all() total = Decimal(0) for split in splits: total += split.value return total
[ "def", "get_total_paid", "(", "self", ")", "->", "Decimal", ":", "query", "=", "(", "self", ".", "get_splits_query", "(", ")", ")", "splits", "=", "query", ".", "all", "(", ")", "total", "=", "Decimal", "(", "0", ")", "for", "split", "in", "splits", ":", "total", "+=", "split", ".", "value", "return", "total" ]
Returns the total amount paid, in currency, for the stocks owned
[ "Returns", "the", "total", "amount", "paid", "in", "currency", "for", "the", "stocks", "owned" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L272-L283
16,935
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_total_paid_for_remaining_stock
def get_total_paid_for_remaining_stock(self) -> Decimal: """ Returns the amount paid only for the remaining stock """ paid = Decimal(0) accounts = self.get_holding_accounts() for acc in accounts: splits = self.get_available_splits_for_account(acc) paid += sum(split.value for split in splits) return paid
python
def get_total_paid_for_remaining_stock(self) -> Decimal: """ Returns the amount paid only for the remaining stock """ paid = Decimal(0) accounts = self.get_holding_accounts() for acc in accounts: splits = self.get_available_splits_for_account(acc) paid += sum(split.value for split in splits) return paid
[ "def", "get_total_paid_for_remaining_stock", "(", "self", ")", "->", "Decimal", ":", "paid", "=", "Decimal", "(", "0", ")", "accounts", "=", "self", ".", "get_holding_accounts", "(", ")", "for", "acc", "in", "accounts", ":", "splits", "=", "self", ".", "get_available_splits_for_account", "(", "acc", ")", "paid", "+=", "sum", "(", "split", ".", "value", "for", "split", "in", "splits", ")", "return", "paid" ]
Returns the amount paid only for the remaining stock
[ "Returns", "the", "amount", "paid", "only", "for", "the", "remaining", "stock" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L285-L293
16,936
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_value
def get_value(self) -> Decimal: """ Returns the current value of stocks """ quantity = self.get_quantity() price = self.get_last_available_price() if not price: # raise ValueError("no price found for", self.full_symbol) return Decimal(0) value = quantity * price.value return value
python
def get_value(self) -> Decimal: """ Returns the current value of stocks """ quantity = self.get_quantity() price = self.get_last_available_price() if not price: # raise ValueError("no price found for", self.full_symbol) return Decimal(0) value = quantity * price.value return value
[ "def", "get_value", "(", "self", ")", "->", "Decimal", ":", "quantity", "=", "self", ".", "get_quantity", "(", ")", "price", "=", "self", ".", "get_last_available_price", "(", ")", "if", "not", "price", ":", "# raise ValueError(\"no price found for\", self.full_symbol)", "return", "Decimal", "(", "0", ")", "value", "=", "quantity", "*", "price", ".", "value", "return", "value" ]
Returns the current value of stocks
[ "Returns", "the", "current", "value", "of", "stocks" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L295-L304
16,937
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.get_value_in_base_currency
def get_value_in_base_currency(self) -> Decimal: """ Calculates the value of security holdings in base currency """ # check if the currency is the base currency. amt_orig = self.get_value() # Security currency sec_cur = self.get_currency() #base_cur = self.book.default_currency cur_svc = CurrenciesAggregate(self.book) base_cur = cur_svc.get_default_currency() if sec_cur == base_cur: return amt_orig # otherwise recalculate single_svc = cur_svc.get_currency_aggregate(sec_cur) rate = single_svc.get_latest_rate(base_cur) result = amt_orig * rate.value return result
python
def get_value_in_base_currency(self) -> Decimal: """ Calculates the value of security holdings in base currency """ # check if the currency is the base currency. amt_orig = self.get_value() # Security currency sec_cur = self.get_currency() #base_cur = self.book.default_currency cur_svc = CurrenciesAggregate(self.book) base_cur = cur_svc.get_default_currency() if sec_cur == base_cur: return amt_orig # otherwise recalculate single_svc = cur_svc.get_currency_aggregate(sec_cur) rate = single_svc.get_latest_rate(base_cur) result = amt_orig * rate.value return result
[ "def", "get_value_in_base_currency", "(", "self", ")", "->", "Decimal", ":", "# check if the currency is the base currency.", "amt_orig", "=", "self", ".", "get_value", "(", ")", "# Security currency", "sec_cur", "=", "self", ".", "get_currency", "(", ")", "#base_cur = self.book.default_currency", "cur_svc", "=", "CurrenciesAggregate", "(", "self", ".", "book", ")", "base_cur", "=", "cur_svc", ".", "get_default_currency", "(", ")", "if", "sec_cur", "==", "base_cur", ":", "return", "amt_orig", "# otherwise recalculate", "single_svc", "=", "cur_svc", ".", "get_currency_aggregate", "(", "sec_cur", ")", "rate", "=", "single_svc", ".", "get_latest_rate", "(", "base_cur", ")", "result", "=", "amt_orig", "*", "rate", ".", "value", "return", "result" ]
Calculates the value of security holdings in base currency
[ "Calculates", "the", "value", "of", "security", "holdings", "in", "base", "currency" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L306-L324
16,938
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecurityAggregate.accounts
def accounts(self) -> List[Account]: """ Returns the asset accounts in which the security is held """ # use only Assets sub-accounts result = ( [acct for acct in self.security.accounts if acct.fullname.startswith('Assets')] ) return result
python
def accounts(self) -> List[Account]: """ Returns the asset accounts in which the security is held """ # use only Assets sub-accounts result = ( [acct for acct in self.security.accounts if acct.fullname.startswith('Assets')] ) return result
[ "def", "accounts", "(", "self", ")", "->", "List", "[", "Account", "]", ":", "# use only Assets sub-accounts", "result", "=", "(", "[", "acct", "for", "acct", "in", "self", ".", "security", ".", "accounts", "if", "acct", ".", "fullname", ".", "startswith", "(", "'Assets'", ")", "]", ")", "return", "result" ]
Returns the asset accounts in which the security is held
[ "Returns", "the", "asset", "accounts", "in", "which", "the", "security", "is", "held" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L348-L354
16,939
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.find
def find(self, search_term: str) -> List[Commodity]: """ Searches for security by part of the name """ query = ( self.query .filter(Commodity.mnemonic.like('%' + search_term + '%') | Commodity.fullname.like('%' + search_term + '%')) ) return query.all()
python
def find(self, search_term: str) -> List[Commodity]: """ Searches for security by part of the name """ query = ( self.query .filter(Commodity.mnemonic.like('%' + search_term + '%') | Commodity.fullname.like('%' + search_term + '%')) ) return query.all()
[ "def", "find", "(", "self", ",", "search_term", ":", "str", ")", "->", "List", "[", "Commodity", "]", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Commodity", ".", "mnemonic", ".", "like", "(", "'%'", "+", "search_term", "+", "'%'", ")", "|", "Commodity", ".", "fullname", ".", "like", "(", "'%'", "+", "search_term", "+", "'%'", ")", ")", ")", "return", "query", ".", "all", "(", ")" ]
Searches for security by part of the name
[ "Searches", "for", "security", "by", "part", "of", "the", "name" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L370-L377
16,940
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.get_all
def get_all(self) -> List[Commodity]: """ Loads all non-currency commodities, assuming they are stocks. """ query = ( self.query .order_by(Commodity.namespace, Commodity.mnemonic) ) return query.all()
python
def get_all(self) -> List[Commodity]: """ Loads all non-currency commodities, assuming they are stocks. """ query = ( self.query .order_by(Commodity.namespace, Commodity.mnemonic) ) return query.all()
[ "def", "get_all", "(", "self", ")", "->", "List", "[", "Commodity", "]", ":", "query", "=", "(", "self", ".", "query", ".", "order_by", "(", "Commodity", ".", "namespace", ",", "Commodity", ".", "mnemonic", ")", ")", "return", "query", ".", "all", "(", ")" ]
Loads all non-currency commodities, assuming they are stocks.
[ "Loads", "all", "non", "-", "currency", "commodities", "assuming", "they", "are", "stocks", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L379-L385
16,941
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.get_by_symbol
def get_by_symbol(self, symbol: str) -> Commodity: """ Returns the commodity with the given symbol. If more are found, an exception will be thrown. """ # handle namespace. Accept GnuCash and Yahoo-style symbols. full_symbol = self.__parse_gc_symbol(symbol) query = ( self.query .filter(Commodity.mnemonic == full_symbol["mnemonic"]) ) if full_symbol["namespace"]: query = query.filter(Commodity.namespace == full_symbol["namespace"]) return query.first()
python
def get_by_symbol(self, symbol: str) -> Commodity: """ Returns the commodity with the given symbol. If more are found, an exception will be thrown. """ # handle namespace. Accept GnuCash and Yahoo-style symbols. full_symbol = self.__parse_gc_symbol(symbol) query = ( self.query .filter(Commodity.mnemonic == full_symbol["mnemonic"]) ) if full_symbol["namespace"]: query = query.filter(Commodity.namespace == full_symbol["namespace"]) return query.first()
[ "def", "get_by_symbol", "(", "self", ",", "symbol", ":", "str", ")", "->", "Commodity", ":", "# handle namespace. Accept GnuCash and Yahoo-style symbols.", "full_symbol", "=", "self", ".", "__parse_gc_symbol", "(", "symbol", ")", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Commodity", ".", "mnemonic", "==", "full_symbol", "[", "\"mnemonic\"", "]", ")", ")", "if", "full_symbol", "[", "\"namespace\"", "]", ":", "query", "=", "query", ".", "filter", "(", "Commodity", ".", "namespace", "==", "full_symbol", "[", "\"namespace\"", "]", ")", "return", "query", ".", "first", "(", ")" ]
Returns the commodity with the given symbol. If more are found, an exception will be thrown.
[ "Returns", "the", "commodity", "with", "the", "given", "symbol", ".", "If", "more", "are", "found", "an", "exception", "will", "be", "thrown", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L387-L402
16,942
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.get_stocks
def get_stocks(self, symbols: List[str]) -> List[Commodity]: """ loads stocks by symbol """ query = ( self.query .filter(Commodity.mnemonic.in_(symbols)) ).order_by(Commodity.namespace, Commodity.mnemonic) return query.all()
python
def get_stocks(self, symbols: List[str]) -> List[Commodity]: """ loads stocks by symbol """ query = ( self.query .filter(Commodity.mnemonic.in_(symbols)) ).order_by(Commodity.namespace, Commodity.mnemonic) return query.all()
[ "def", "get_stocks", "(", "self", ",", "symbols", ":", "List", "[", "str", "]", ")", "->", "List", "[", "Commodity", "]", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Commodity", ".", "mnemonic", ".", "in_", "(", "symbols", ")", ")", ")", ".", "order_by", "(", "Commodity", ".", "namespace", ",", "Commodity", ".", "mnemonic", ")", "return", "query", ".", "all", "(", ")" ]
loads stocks by symbol
[ "loads", "stocks", "by", "symbol" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L420-L426
16,943
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.get_aggregate
def get_aggregate(self, security: Commodity) -> SecurityAggregate: """ Returns the aggregate for the entity """ assert security is not None assert isinstance(security, Commodity) return SecurityAggregate(self.book, security)
python
def get_aggregate(self, security: Commodity) -> SecurityAggregate: """ Returns the aggregate for the entity """ assert security is not None assert isinstance(security, Commodity) return SecurityAggregate(self.book, security)
[ "def", "get_aggregate", "(", "self", ",", "security", ":", "Commodity", ")", "->", "SecurityAggregate", ":", "assert", "security", "is", "not", "None", "assert", "isinstance", "(", "security", ",", "Commodity", ")", "return", "SecurityAggregate", "(", "self", ".", "book", ",", "security", ")" ]
Returns the aggregate for the entity
[ "Returns", "the", "aggregate", "for", "the", "entity" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L428-L433
16,944
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.get_aggregate_for_symbol
def get_aggregate_for_symbol(self, symbol: str) -> SecurityAggregate: """ Returns the aggregate for the security found by full symbol """ security = self.get_by_symbol(symbol) if not security: raise ValueError(f"Security not found in GC book: {symbol}!") return self.get_aggregate(security)
python
def get_aggregate_for_symbol(self, symbol: str) -> SecurityAggregate: """ Returns the aggregate for the security found by full symbol """ security = self.get_by_symbol(symbol) if not security: raise ValueError(f"Security not found in GC book: {symbol}!") return self.get_aggregate(security)
[ "def", "get_aggregate_for_symbol", "(", "self", ",", "symbol", ":", "str", ")", "->", "SecurityAggregate", ":", "security", "=", "self", ".", "get_by_symbol", "(", "symbol", ")", "if", "not", "security", ":", "raise", "ValueError", "(", "f\"Security not found in GC book: {symbol}!\"", ")", "return", "self", ".", "get_aggregate", "(", "security", ")" ]
Returns the aggregate for the security found by full symbol
[ "Returns", "the", "aggregate", "for", "the", "security", "found", "by", "full", "symbol" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L435-L440
16,945
MisterY/gnucash-portfolio
gnucash_portfolio/securitiesaggregate.py
SecuritiesAggregate.query
def query(self): """ Returns the base query which filters out data for all queries. """ query = ( self.book.session.query(Commodity) .filter(Commodity.namespace != "CURRENCY", Commodity.namespace != "template") ) return query
python
def query(self): """ Returns the base query which filters out data for all queries. """ query = ( self.book.session.query(Commodity) .filter(Commodity.namespace != "CURRENCY", Commodity.namespace != "template") ) return query
[ "def", "query", "(", "self", ")", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Commodity", ")", ".", "filter", "(", "Commodity", ".", "namespace", "!=", "\"CURRENCY\"", ",", "Commodity", ".", "namespace", "!=", "\"template\"", ")", ")", "return", "query" ]
Returns the base query which filters out data for all queries.
[ "Returns", "the", "base", "query", "which", "filters", "out", "data", "for", "all", "queries", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/securitiesaggregate.py#L443-L450
16,946
MisterY/gnucash-portfolio
gnucash_portfolio/bookaggregate.py
BookAggregate.book
def book(self) -> Book: """ GnuCash Book. Opens the book or creates an database, based on settings. """ if not self.__book: # Create/open the book. book_uri = self.settings.database_path self.__book = Database(book_uri).open_book( for_writing=self.__for_writing) return self.__book
python
def book(self) -> Book: """ GnuCash Book. Opens the book or creates an database, based on settings. """ if not self.__book: # Create/open the book. book_uri = self.settings.database_path self.__book = Database(book_uri).open_book( for_writing=self.__for_writing) return self.__book
[ "def", "book", "(", "self", ")", "->", "Book", ":", "if", "not", "self", ".", "__book", ":", "# Create/open the book.", "book_uri", "=", "self", ".", "settings", ".", "database_path", "self", ".", "__book", "=", "Database", "(", "book_uri", ")", ".", "open_book", "(", "for_writing", "=", "self", ".", "__for_writing", ")", "return", "self", ".", "__book" ]
GnuCash Book. Opens the book or creates an database, based on settings.
[ "GnuCash", "Book", ".", "Opens", "the", "book", "or", "creates", "an", "database", "based", "on", "settings", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L54-L62
16,947
MisterY/gnucash-portfolio
gnucash_portfolio/bookaggregate.py
BookAggregate.accounts
def accounts(self) -> AccountsAggregate: """ Returns the Accounts aggregate """ if not self.__accounts_aggregate: self.__accounts_aggregate = AccountsAggregate(self.book) return self.__accounts_aggregate
python
def accounts(self) -> AccountsAggregate: """ Returns the Accounts aggregate """ if not self.__accounts_aggregate: self.__accounts_aggregate = AccountsAggregate(self.book) return self.__accounts_aggregate
[ "def", "accounts", "(", "self", ")", "->", "AccountsAggregate", ":", "if", "not", "self", ".", "__accounts_aggregate", ":", "self", ".", "__accounts_aggregate", "=", "AccountsAggregate", "(", "self", ".", "book", ")", "return", "self", ".", "__accounts_aggregate" ]
Returns the Accounts aggregate
[ "Returns", "the", "Accounts", "aggregate" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L83-L87
16,948
MisterY/gnucash-portfolio
gnucash_portfolio/bookaggregate.py
BookAggregate.currencies
def currencies(self) -> CurrenciesAggregate: """ Returns the Currencies aggregate """ if not self.__currencies_aggregate: self.__currencies_aggregate = CurrenciesAggregate(self.book) return self.__currencies_aggregate
python
def currencies(self) -> CurrenciesAggregate: """ Returns the Currencies aggregate """ if not self.__currencies_aggregate: self.__currencies_aggregate = CurrenciesAggregate(self.book) return self.__currencies_aggregate
[ "def", "currencies", "(", "self", ")", "->", "CurrenciesAggregate", ":", "if", "not", "self", ".", "__currencies_aggregate", ":", "self", ".", "__currencies_aggregate", "=", "CurrenciesAggregate", "(", "self", ".", "book", ")", "return", "self", ".", "__currencies_aggregate" ]
Returns the Currencies aggregate
[ "Returns", "the", "Currencies", "aggregate" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L90-L94
16,949
MisterY/gnucash-portfolio
gnucash_portfolio/bookaggregate.py
BookAggregate.securities
def securities(self): """ Returns securities aggregate """ if not self.__securities_aggregate: self.__securities_aggregate = SecuritiesAggregate(self.book) return self.__securities_aggregate
python
def securities(self): """ Returns securities aggregate """ if not self.__securities_aggregate: self.__securities_aggregate = SecuritiesAggregate(self.book) return self.__securities_aggregate
[ "def", "securities", "(", "self", ")", ":", "if", "not", "self", ".", "__securities_aggregate", ":", "self", ".", "__securities_aggregate", "=", "SecuritiesAggregate", "(", "self", ".", "book", ")", "return", "self", ".", "__securities_aggregate" ]
Returns securities aggregate
[ "Returns", "securities", "aggregate" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L111-L115
16,950
MisterY/gnucash-portfolio
gnucash_portfolio/bookaggregate.py
BookAggregate.get_currency_symbols
def get_currency_symbols(self) -> List[str]: """ Returns the used currencies' symbols as an array """ result = [] currencies = self.currencies.get_book_currencies() for cur in currencies: result.append(cur.mnemonic) return result
python
def get_currency_symbols(self) -> List[str]: """ Returns the used currencies' symbols as an array """ result = [] currencies = self.currencies.get_book_currencies() for cur in currencies: result.append(cur.mnemonic) return result
[ "def", "get_currency_symbols", "(", "self", ")", "->", "List", "[", "str", "]", ":", "result", "=", "[", "]", "currencies", "=", "self", ".", "currencies", ".", "get_book_currencies", "(", ")", "for", "cur", "in", "currencies", ":", "result", ".", "append", "(", "cur", ".", "mnemonic", ")", "return", "result" ]
Returns the used currencies' symbols as an array
[ "Returns", "the", "used", "currencies", "symbols", "as", "an", "array" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/bookaggregate.py#L139-L145
16,951
MisterY/gnucash-portfolio
gnucash_portfolio/lib/templates.py
load_jinja_template
def load_jinja_template(file_name): """ Loads the jinja2 HTML template from the given file. Assumes that the file is in the same directory as the script. """ original_script_path = sys.argv[0] #script_path = os.path.dirname(os.path.realpath(__file__)) script_dir = os.path.dirname(original_script_path) # file_path = os.path.join(script_path, file_name) # with open(file_path, 'r') as template_file: # return template_file.read() from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader(script_dir)) template = env.get_template(file_name) return template
python
def load_jinja_template(file_name): """ Loads the jinja2 HTML template from the given file. Assumes that the file is in the same directory as the script. """ original_script_path = sys.argv[0] #script_path = os.path.dirname(os.path.realpath(__file__)) script_dir = os.path.dirname(original_script_path) # file_path = os.path.join(script_path, file_name) # with open(file_path, 'r') as template_file: # return template_file.read() from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader(script_dir)) template = env.get_template(file_name) return template
[ "def", "load_jinja_template", "(", "file_name", ")", ":", "original_script_path", "=", "sys", ".", "argv", "[", "0", "]", "#script_path = os.path.dirname(os.path.realpath(__file__))", "script_dir", "=", "os", ".", "path", ".", "dirname", "(", "original_script_path", ")", "# file_path = os.path.join(script_path, file_name)", "# with open(file_path, 'r') as template_file:", "# return template_file.read()", "from", "jinja2", "import", "Environment", ",", "FileSystemLoader", "env", "=", "Environment", "(", "loader", "=", "FileSystemLoader", "(", "script_dir", ")", ")", "template", "=", "env", ".", "get_template", "(", "file_name", ")", "return", "template" ]
Loads the jinja2 HTML template from the given file. Assumes that the file is in the same directory as the script.
[ "Loads", "the", "jinja2", "HTML", "template", "from", "the", "given", "file", ".", "Assumes", "that", "the", "file", "is", "in", "the", "same", "directory", "as", "the", "script", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/templates.py#L7-L23
16,952
MisterY/gnucash-portfolio
gnucash_portfolio/lib/datetimeutils.py
get_days_in_month
def get_days_in_month(year: int, month: int) -> int: """ Returns number of days in the given month. 1-based numbers as arguments. i.e. November = 11 """ month_range = calendar.monthrange(year, month) return month_range[1]
python
def get_days_in_month(year: int, month: int) -> int: """ Returns number of days in the given month. 1-based numbers as arguments. i.e. November = 11 """ month_range = calendar.monthrange(year, month) return month_range[1]
[ "def", "get_days_in_month", "(", "year", ":", "int", ",", "month", ":", "int", ")", "->", "int", ":", "month_range", "=", "calendar", ".", "monthrange", "(", "year", ",", "month", ")", "return", "month_range", "[", "1", "]" ]
Returns number of days in the given month. 1-based numbers as arguments. i.e. November = 11
[ "Returns", "number", "of", "days", "in", "the", "given", "month", ".", "1", "-", "based", "numbers", "as", "arguments", ".", "i", ".", "e", ".", "November", "=", "11" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L8-L12
16,953
MisterY/gnucash-portfolio
gnucash_portfolio/lib/datetimeutils.py
get_from_gnucash26_date
def get_from_gnucash26_date(date_str: str) -> date: """ Creates a datetime from GnuCash 2.6 date string """ date_format = "%Y%m%d" result = datetime.strptime(date_str, date_format).date() return result
python
def get_from_gnucash26_date(date_str: str) -> date: """ Creates a datetime from GnuCash 2.6 date string """ date_format = "%Y%m%d" result = datetime.strptime(date_str, date_format).date() return result
[ "def", "get_from_gnucash26_date", "(", "date_str", ":", "str", ")", "->", "date", ":", "date_format", "=", "\"%Y%m%d\"", "result", "=", "datetime", ".", "strptime", "(", "date_str", ",", "date_format", ")", ".", "date", "(", ")", "return", "result" ]
Creates a datetime from GnuCash 2.6 date string
[ "Creates", "a", "datetime", "from", "GnuCash", "2", ".", "6", "date", "string" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L15-L19
16,954
MisterY/gnucash-portfolio
gnucash_portfolio/lib/datetimeutils.py
parse_period
def parse_period(period: str): """ parses period from date range picker. The received values are full ISO date """ period = period.split(" - ") date_from = Datum() if len(period[0]) == 10: date_from.from_iso_date_string(period[0]) else: date_from.from_iso_long_date(period[0]) date_from.start_of_day() date_to = Datum() if len(period[1]) == 10: date_to.from_iso_date_string(period[1]) else: date_to.from_iso_long_date(period[1]) date_to.end_of_day() return date_from.value, date_to.value
python
def parse_period(period: str): """ parses period from date range picker. The received values are full ISO date """ period = period.split(" - ") date_from = Datum() if len(period[0]) == 10: date_from.from_iso_date_string(period[0]) else: date_from.from_iso_long_date(period[0]) date_from.start_of_day() date_to = Datum() if len(period[1]) == 10: date_to.from_iso_date_string(period[1]) else: date_to.from_iso_long_date(period[1]) date_to.end_of_day() return date_from.value, date_to.value
[ "def", "parse_period", "(", "period", ":", "str", ")", ":", "period", "=", "period", ".", "split", "(", "\" - \"", ")", "date_from", "=", "Datum", "(", ")", "if", "len", "(", "period", "[", "0", "]", ")", "==", "10", ":", "date_from", ".", "from_iso_date_string", "(", "period", "[", "0", "]", ")", "else", ":", "date_from", ".", "from_iso_long_date", "(", "period", "[", "0", "]", ")", "date_from", ".", "start_of_day", "(", ")", "date_to", "=", "Datum", "(", ")", "if", "len", "(", "period", "[", "1", "]", ")", "==", "10", ":", "date_to", ".", "from_iso_date_string", "(", "period", "[", "1", "]", ")", "else", ":", "date_to", ".", "from_iso_long_date", "(", "period", "[", "1", "]", ")", "date_to", ".", "end_of_day", "(", ")", "return", "date_from", ".", "value", ",", "date_to", ".", "value" ]
parses period from date range picker. The received values are full ISO date
[ "parses", "period", "from", "date", "range", "picker", ".", "The", "received", "values", "are", "full", "ISO", "date" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L34-L52
16,955
MisterY/gnucash-portfolio
gnucash_portfolio/lib/datetimeutils.py
get_period
def get_period(date_from: date, date_to: date) -> str: """ Returns the period string from the given dates """ assert isinstance(date_from, date) assert isinstance(date_to, date) str_from: str = date_from.isoformat() str_to: str = date_to.isoformat() return str_from + " - " + str_to
python
def get_period(date_from: date, date_to: date) -> str: """ Returns the period string from the given dates """ assert isinstance(date_from, date) assert isinstance(date_to, date) str_from: str = date_from.isoformat() str_to: str = date_to.isoformat() return str_from + " - " + str_to
[ "def", "get_period", "(", "date_from", ":", "date", ",", "date_to", ":", "date", ")", "->", "str", ":", "assert", "isinstance", "(", "date_from", ",", "date", ")", "assert", "isinstance", "(", "date_to", ",", "date", ")", "str_from", ":", "str", "=", "date_from", ".", "isoformat", "(", ")", "str_to", ":", "str", "=", "date_to", ".", "isoformat", "(", ")", "return", "str_from", "+", "\" - \"", "+", "str_to" ]
Returns the period string from the given dates
[ "Returns", "the", "period", "string", "from", "the", "given", "dates" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/datetimeutils.py#L60-L68
16,956
MisterY/gnucash-portfolio
gnucash_portfolio/lib/generic.py
load_json_file_contents
def load_json_file_contents(path: str) -> str: """ Loads contents from a json file """ assert isinstance(path, str) content = None file_path = os.path.abspath(path) content = fileutils.read_text_from_file(file_path) json_object = json.loads(content) content = json.dumps(json_object, sort_keys=True, indent=4) return content
python
def load_json_file_contents(path: str) -> str: """ Loads contents from a json file """ assert isinstance(path, str) content = None file_path = os.path.abspath(path) content = fileutils.read_text_from_file(file_path) json_object = json.loads(content) content = json.dumps(json_object, sort_keys=True, indent=4) return content
[ "def", "load_json_file_contents", "(", "path", ":", "str", ")", "->", "str", ":", "assert", "isinstance", "(", "path", ",", "str", ")", "content", "=", "None", "file_path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "content", "=", "fileutils", ".", "read_text_from_file", "(", "file_path", ")", "json_object", "=", "json", ".", "loads", "(", "content", ")", "content", "=", "json", ".", "dumps", "(", "json_object", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", "return", "content" ]
Loads contents from a json file
[ "Loads", "contents", "from", "a", "json", "file" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L16-L26
16,957
MisterY/gnucash-portfolio
gnucash_portfolio/lib/generic.py
validate_json
def validate_json(data: str): """ Validate JSON by parsing string data. Returns the json dict. """ result = None try: result = json.loads(data) except ValueError as error: log(ERROR, "invalid json: %s", error) return result
python
def validate_json(data: str): """ Validate JSON by parsing string data. Returns the json dict. """ result = None try: result = json.loads(data) except ValueError as error: log(ERROR, "invalid json: %s", error) return result
[ "def", "validate_json", "(", "data", ":", "str", ")", ":", "result", "=", "None", "try", ":", "result", "=", "json", ".", "loads", "(", "data", ")", "except", "ValueError", "as", "error", ":", "log", "(", "ERROR", ",", "\"invalid json: %s\"", ",", "error", ")", "return", "result" ]
Validate JSON by parsing string data. Returns the json dict.
[ "Validate", "JSON", "by", "parsing", "string", "data", ".", "Returns", "the", "json", "dict", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L28-L36
16,958
MisterY/gnucash-portfolio
gnucash_portfolio/lib/generic.py
get_sql
def get_sql(query): """ Returns the sql query """ sql = str(query.statement.compile(dialect=sqlite.dialect(), compile_kwargs={"literal_binds": True})) return sql
python
def get_sql(query): """ Returns the sql query """ sql = str(query.statement.compile(dialect=sqlite.dialect(), compile_kwargs={"literal_binds": True})) return sql
[ "def", "get_sql", "(", "query", ")", ":", "sql", "=", "str", "(", "query", ".", "statement", ".", "compile", "(", "dialect", "=", "sqlite", ".", "dialect", "(", ")", ",", "compile_kwargs", "=", "{", "\"literal_binds\"", ":", "True", "}", ")", ")", "return", "sql" ]
Returns the sql query
[ "Returns", "the", "sql", "query" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L43-L47
16,959
MisterY/gnucash-portfolio
gnucash_portfolio/lib/generic.py
save_to_temp
def save_to_temp(content, file_name=None): """Save the contents into a temp file.""" #output = "results.html" temp_dir = tempfile.gettempdir() #tempfile.TemporaryDirectory() #tempfile.NamedTemporaryFile(mode='w+t') as f: out_file = os.path.join(temp_dir, file_name) #if os.path.exists(output) and os.path.isfile(output): file = open(out_file, 'w') file.write(content) file.close() #print("results saved in results.html file.") #return output #output = str(pathlib.Path(f.name)) return out_file
python
def save_to_temp(content, file_name=None): """Save the contents into a temp file.""" #output = "results.html" temp_dir = tempfile.gettempdir() #tempfile.TemporaryDirectory() #tempfile.NamedTemporaryFile(mode='w+t') as f: out_file = os.path.join(temp_dir, file_name) #if os.path.exists(output) and os.path.isfile(output): file = open(out_file, 'w') file.write(content) file.close() #print("results saved in results.html file.") #return output #output = str(pathlib.Path(f.name)) return out_file
[ "def", "save_to_temp", "(", "content", ",", "file_name", "=", "None", ")", ":", "#output = \"results.html\"", "temp_dir", "=", "tempfile", ".", "gettempdir", "(", ")", "#tempfile.TemporaryDirectory()", "#tempfile.NamedTemporaryFile(mode='w+t') as f:", "out_file", "=", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "file_name", ")", "#if os.path.exists(output) and os.path.isfile(output):", "file", "=", "open", "(", "out_file", ",", "'w'", ")", "file", ".", "write", "(", "content", ")", "file", ".", "close", "(", ")", "#print(\"results saved in results.html file.\")", "#return output", "#output = str(pathlib.Path(f.name))", "return", "out_file" ]
Save the contents into a temp file.
[ "Save", "the", "contents", "into", "a", "temp", "file", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L49-L64
16,960
MisterY/gnucash-portfolio
gnucash_portfolio/lib/generic.py
read_book_uri_from_console
def read_book_uri_from_console(): """ Prompts the user to enter book url in console """ db_path: str = input("Enter book_url or leave blank for the default settings value: ") if db_path: # sqlite if db_path.startswith("sqlite://"): db_path_uri = db_path else: # TODO: check if file exists. db_path_uri = "file:///" + db_path else: cfg = settings.Settings() db_path_uri = cfg.database_uri return db_path_uri
python
def read_book_uri_from_console(): """ Prompts the user to enter book url in console """ db_path: str = input("Enter book_url or leave blank for the default settings value: ") if db_path: # sqlite if db_path.startswith("sqlite://"): db_path_uri = db_path else: # TODO: check if file exists. db_path_uri = "file:///" + db_path else: cfg = settings.Settings() db_path_uri = cfg.database_uri return db_path_uri
[ "def", "read_book_uri_from_console", "(", ")", ":", "db_path", ":", "str", "=", "input", "(", "\"Enter book_url or leave blank for the default settings value: \"", ")", "if", "db_path", ":", "# sqlite", "if", "db_path", ".", "startswith", "(", "\"sqlite://\"", ")", ":", "db_path_uri", "=", "db_path", "else", ":", "# TODO: check if file exists.", "db_path_uri", "=", "\"file:///\"", "+", "db_path", "else", ":", "cfg", "=", "settings", ".", "Settings", "(", ")", "db_path_uri", "=", "cfg", ".", "database_uri", "return", "db_path_uri" ]
Prompts the user to enter book url in console
[ "Prompts", "the", "user", "to", "enter", "book", "url", "in", "console" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L66-L80
16,961
MisterY/gnucash-portfolio
gnucash_portfolio/lib/generic.py
run_report_from_console
def run_report_from_console(output_file_name, callback): """ Runs the report from the command line. Receives the book url from the console. """ print("The report uses a read-only access to the book.") print("Now enter the data or ^Z to continue:") #report_method = kwargs["report_method"] result = callback() #output_file_name = kwargs["output_file_name"] output = save_to_temp(result, output_file_name) webbrowser.open(output)
python
def run_report_from_console(output_file_name, callback): """ Runs the report from the command line. Receives the book url from the console. """ print("The report uses a read-only access to the book.") print("Now enter the data or ^Z to continue:") #report_method = kwargs["report_method"] result = callback() #output_file_name = kwargs["output_file_name"] output = save_to_temp(result, output_file_name) webbrowser.open(output)
[ "def", "run_report_from_console", "(", "output_file_name", ",", "callback", ")", ":", "print", "(", "\"The report uses a read-only access to the book.\"", ")", "print", "(", "\"Now enter the data or ^Z to continue:\"", ")", "#report_method = kwargs[\"report_method\"]", "result", "=", "callback", "(", ")", "#output_file_name = kwargs[\"output_file_name\"]", "output", "=", "save_to_temp", "(", "result", ",", "output_file_name", ")", "webbrowser", ".", "open", "(", "output", ")" ]
Runs the report from the command line. Receives the book url from the console.
[ "Runs", "the", "report", "from", "the", "command", "line", ".", "Receives", "the", "book", "url", "from", "the", "console", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/generic.py#L82-L94
16,962
MisterY/gnucash-portfolio
gnucash_portfolio/actions/symbol_dividends.py
get_dividend_sum_for_symbol
def get_dividend_sum_for_symbol(book: Book, symbol: str): """ Calculates all income for a symbol """ svc = SecuritiesAggregate(book) security = svc.get_by_symbol(symbol) sec_svc = SecurityAggregate(book, security) accounts = sec_svc.get_income_accounts() total = Decimal(0) for account in accounts: # get all dividends. income = get_dividend_sum(book, account) total += income return total
python
def get_dividend_sum_for_symbol(book: Book, symbol: str): """ Calculates all income for a symbol """ svc = SecuritiesAggregate(book) security = svc.get_by_symbol(symbol) sec_svc = SecurityAggregate(book, security) accounts = sec_svc.get_income_accounts() total = Decimal(0) for account in accounts: # get all dividends. income = get_dividend_sum(book, account) total += income return total
[ "def", "get_dividend_sum_for_symbol", "(", "book", ":", "Book", ",", "symbol", ":", "str", ")", ":", "svc", "=", "SecuritiesAggregate", "(", "book", ")", "security", "=", "svc", ".", "get_by_symbol", "(", "symbol", ")", "sec_svc", "=", "SecurityAggregate", "(", "book", ",", "security", ")", "accounts", "=", "sec_svc", ".", "get_income_accounts", "(", ")", "total", "=", "Decimal", "(", "0", ")", "for", "account", "in", "accounts", ":", "# get all dividends.", "income", "=", "get_dividend_sum", "(", "book", ",", "account", ")", "total", "+=", "income", "return", "total" ]
Calculates all income for a symbol
[ "Calculates", "all", "income", "for", "a", "symbol" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/symbol_dividends.py#L26-L39
16,963
MisterY/gnucash-portfolio
gnucash_portfolio/actions/import_security_prices.py
import_file
def import_file(filename): """ Imports the commodity prices from the given .csv file. """ #file_path = os.path.relpath(filename) file_path = os.path.abspath(filename) log(DEBUG, "Loading prices from %s", file_path) prices = __read_prices_from_file(file_path) with BookAggregate(for_writing=True) as svc: svc.prices.import_prices(prices) print("Saving book...") svc.book.save()
python
def import_file(filename): """ Imports the commodity prices from the given .csv file. """ #file_path = os.path.relpath(filename) file_path = os.path.abspath(filename) log(DEBUG, "Loading prices from %s", file_path) prices = __read_prices_from_file(file_path) with BookAggregate(for_writing=True) as svc: svc.prices.import_prices(prices) print("Saving book...") svc.book.save()
[ "def", "import_file", "(", "filename", ")", ":", "#file_path = os.path.relpath(filename)", "file_path", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "log", "(", "DEBUG", ",", "\"Loading prices from %s\"", ",", "file_path", ")", "prices", "=", "__read_prices_from_file", "(", "file_path", ")", "with", "BookAggregate", "(", "for_writing", "=", "True", ")", "as", "svc", ":", "svc", ".", "prices", ".", "import_prices", "(", "prices", ")", "print", "(", "\"Saving book...\"", ")", "svc", ".", "book", ".", "save", "(", ")" ]
Imports the commodity prices from the given .csv file.
[ "Imports", "the", "commodity", "prices", "from", "the", "given", ".", "csv", "file", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/import_security_prices.py#L18-L31
16,964
MisterY/gnucash-portfolio
reports/report_portfolio_value/report_portfolio_value.py
generate_report
def generate_report(book_url): # commodity: CommodityOption( # section="Commodity", # sort_tag="a", # documentation_string="This is a stock", # default_value="VTIP"), # commodity_list: CommodityListOption( # section="Commodity", # sort_tag="a", # documentation_string="This is a stock", # default_value="VTIP") #): """ Generates an HTML report content. """ # Report variables shares_no = None avg_price = None stock_template = templates.load_jinja_template("stock_template.html") stock_rows = "" with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book: # get all commodities that are not currencies. all_stocks = portfoliovalue.get_all_stocks(book) for stock in all_stocks: for_date = datetime.today().date model = portfoliovalue.get_stock_model_from(book, stock, for_date) stock_rows += stock_template.render(model) # Load HTML template file. template = templates.load_jinja_template("template.html") # Render the full report. #return template.format(**locals()) result = template.render(**locals()) return result
python
def generate_report(book_url): # commodity: CommodityOption( # section="Commodity", # sort_tag="a", # documentation_string="This is a stock", # default_value="VTIP"), # commodity_list: CommodityListOption( # section="Commodity", # sort_tag="a", # documentation_string="This is a stock", # default_value="VTIP") #): """ Generates an HTML report content. """ # Report variables shares_no = None avg_price = None stock_template = templates.load_jinja_template("stock_template.html") stock_rows = "" with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book: # get all commodities that are not currencies. all_stocks = portfoliovalue.get_all_stocks(book) for stock in all_stocks: for_date = datetime.today().date model = portfoliovalue.get_stock_model_from(book, stock, for_date) stock_rows += stock_template.render(model) # Load HTML template file. template = templates.load_jinja_template("template.html") # Render the full report. #return template.format(**locals()) result = template.render(**locals()) return result
[ "def", "generate_report", "(", "book_url", ")", ":", "# commodity: CommodityOption(", "# section=\"Commodity\",", "# sort_tag=\"a\",", "# documentation_string=\"This is a stock\",", "# default_value=\"VTIP\"),", "# commodity_list: CommodityListOption(", "# section=\"Commodity\",", "# sort_tag=\"a\",", "# documentation_string=\"This is a stock\",", "# default_value=\"VTIP\")", "#):", "# Report variables", "shares_no", "=", "None", "avg_price", "=", "None", "stock_template", "=", "templates", ".", "load_jinja_template", "(", "\"stock_template.html\"", ")", "stock_rows", "=", "\"\"", "with", "piecash", ".", "open_book", "(", "book_url", ",", "readonly", "=", "True", ",", "open_if_lock", "=", "True", ")", "as", "book", ":", "# get all commodities that are not currencies.", "all_stocks", "=", "portfoliovalue", ".", "get_all_stocks", "(", "book", ")", "for", "stock", "in", "all_stocks", ":", "for_date", "=", "datetime", ".", "today", "(", ")", ".", "date", "model", "=", "portfoliovalue", ".", "get_stock_model_from", "(", "book", ",", "stock", ",", "for_date", ")", "stock_rows", "+=", "stock_template", ".", "render", "(", "model", ")", "# Load HTML template file.", "template", "=", "templates", ".", "load_jinja_template", "(", "\"template.html\"", ")", "# Render the full report.", "#return template.format(**locals())", "result", "=", "template", ".", "render", "(", "*", "*", "locals", "(", ")", ")", "return", "result" ]
Generates an HTML report content.
[ "Generates", "an", "HTML", "report", "content", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/reports/report_portfolio_value/report_portfolio_value.py#L23-L58
16,965
MisterY/gnucash-portfolio
gnucash_portfolio/actions/security_analysis.py
main
def main(symbol: str): """ Displays the balance for the security symbol. """ print("Displaying the balance for", symbol) with BookAggregate() as svc: security = svc.book.get(Commodity, mnemonic=symbol) #security.transactions, security.prices sec_svc = SecurityAggregate(svc.book, security) # Display number of shares shares_no = sec_svc.get_quantity() print("Quantity:", shares_no) # Calculate average price. avg_price = sec_svc.get_avg_price() print("Average price:", avg_price)
python
def main(symbol: str): """ Displays the balance for the security symbol. """ print("Displaying the balance for", symbol) with BookAggregate() as svc: security = svc.book.get(Commodity, mnemonic=symbol) #security.transactions, security.prices sec_svc = SecurityAggregate(svc.book, security) # Display number of shares shares_no = sec_svc.get_quantity() print("Quantity:", shares_no) # Calculate average price. avg_price = sec_svc.get_avg_price() print("Average price:", avg_price)
[ "def", "main", "(", "symbol", ":", "str", ")", ":", "print", "(", "\"Displaying the balance for\"", ",", "symbol", ")", "with", "BookAggregate", "(", ")", "as", "svc", ":", "security", "=", "svc", ".", "book", ".", "get", "(", "Commodity", ",", "mnemonic", "=", "symbol", ")", "#security.transactions, security.prices", "sec_svc", "=", "SecurityAggregate", "(", "svc", ".", "book", ",", "security", ")", "# Display number of shares", "shares_no", "=", "sec_svc", ".", "get_quantity", "(", ")", "print", "(", "\"Quantity:\"", ",", "shares_no", ")", "# Calculate average price.", "avg_price", "=", "sec_svc", ".", "get_avg_price", "(", ")", "print", "(", "\"Average price:\"", ",", "avg_price", ")" ]
Displays the balance for the security symbol.
[ "Displays", "the", "balance", "for", "the", "security", "symbol", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/security_analysis.py#L12-L30
16,966
MisterY/gnucash-portfolio
examples/report_book.py
generate_report
def generate_report(book_url): """ Generates the report HTML. """ with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book: accounts = [acc.fullname for acc in book.accounts] return f"""<html> <body> Hello world from python !<br> Book : {book_url}<br> List of accounts : {accounts} </body> </html>"""
python
def generate_report(book_url): """ Generates the report HTML. """ with piecash.open_book(book_url, readonly=True, open_if_lock=True) as book: accounts = [acc.fullname for acc in book.accounts] return f"""<html> <body> Hello world from python !<br> Book : {book_url}<br> List of accounts : {accounts} </body> </html>"""
[ "def", "generate_report", "(", "book_url", ")", ":", "with", "piecash", ".", "open_book", "(", "book_url", ",", "readonly", "=", "True", ",", "open_if_lock", "=", "True", ")", "as", "book", ":", "accounts", "=", "[", "acc", ".", "fullname", "for", "acc", "in", "book", ".", "accounts", "]", "return", "f\"\"\"<html>\n <body>\n Hello world from python !<br>\n Book : {book_url}<br>\n List of accounts : {accounts}\n </body>\n </html>\"\"\"" ]
Generates the report HTML.
[ "Generates", "the", "report", "HTML", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/examples/report_book.py#L18-L31
16,967
MisterY/gnucash-portfolio
setup.alt.py
get_project_files
def get_project_files(): """Retrieve a list of project files, ignoring hidden files. :return: sorted list of project files :rtype: :class:`list` """ if is_git_project(): return get_git_project_files() project_files = [] for top, subdirs, files in os.walk('.'): for subdir in subdirs: if subdir.startswith('.'): subdirs.remove(subdir) for f in files: if f.startswith('.'): continue project_files.append(os.path.join(top, f)) return project_files
python
def get_project_files(): """Retrieve a list of project files, ignoring hidden files. :return: sorted list of project files :rtype: :class:`list` """ if is_git_project(): return get_git_project_files() project_files = [] for top, subdirs, files in os.walk('.'): for subdir in subdirs: if subdir.startswith('.'): subdirs.remove(subdir) for f in files: if f.startswith('.'): continue project_files.append(os.path.join(top, f)) return project_files
[ "def", "get_project_files", "(", ")", ":", "if", "is_git_project", "(", ")", ":", "return", "get_git_project_files", "(", ")", "project_files", "=", "[", "]", "for", "top", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "'.'", ")", ":", "for", "subdir", "in", "subdirs", ":", "if", "subdir", ".", "startswith", "(", "'.'", ")", ":", "subdirs", ".", "remove", "(", "subdir", ")", "for", "f", "in", "files", ":", "if", "f", ".", "startswith", "(", "'.'", ")", ":", "continue", "project_files", ".", "append", "(", "os", ".", "path", ".", "join", "(", "top", ",", "f", ")", ")", "return", "project_files" ]
Retrieve a list of project files, ignoring hidden files. :return: sorted list of project files :rtype: :class:`list`
[ "Retrieve", "a", "list", "of", "project", "files", "ignoring", "hidden", "files", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/setup.alt.py#L67-L87
16,968
MisterY/gnucash-portfolio
setup.alt.py
print_success_message
def print_success_message(message): """Print a message indicating success in green color to STDOUT. :param message: the message to print :type message: :class:`str` """ try: import colorama print(colorama.Fore.GREEN + message + colorama.Fore.RESET) except ImportError: print(message)
python
def print_success_message(message): """Print a message indicating success in green color to STDOUT. :param message: the message to print :type message: :class:`str` """ try: import colorama print(colorama.Fore.GREEN + message + colorama.Fore.RESET) except ImportError: print(message)
[ "def", "print_success_message", "(", "message", ")", ":", "try", ":", "import", "colorama", "print", "(", "colorama", ".", "Fore", ".", "GREEN", "+", "message", "+", "colorama", ".", "Fore", ".", "RESET", ")", "except", "ImportError", ":", "print", "(", "message", ")" ]
Print a message indicating success in green color to STDOUT. :param message: the message to print :type message: :class:`str`
[ "Print", "a", "message", "indicating", "success", "in", "green", "color", "to", "STDOUT", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/setup.alt.py#L125-L136
16,969
MisterY/gnucash-portfolio
setup.alt.py
print_failure_message
def print_failure_message(message): """Print a message indicating failure in red color to STDERR. :param message: the message to print :type message: :class:`str` """ try: import colorama print(colorama.Fore.RED + message + colorama.Fore.RESET, file=sys.stderr) except ImportError: print(message, file=sys.stderr)
python
def print_failure_message(message): """Print a message indicating failure in red color to STDERR. :param message: the message to print :type message: :class:`str` """ try: import colorama print(colorama.Fore.RED + message + colorama.Fore.RESET, file=sys.stderr) except ImportError: print(message, file=sys.stderr)
[ "def", "print_failure_message", "(", "message", ")", ":", "try", ":", "import", "colorama", "print", "(", "colorama", ".", "Fore", ".", "RED", "+", "message", "+", "colorama", ".", "Fore", ".", "RESET", ",", "file", "=", "sys", ".", "stderr", ")", "except", "ImportError", ":", "print", "(", "message", ",", "file", "=", "sys", ".", "stderr", ")" ]
Print a message indicating failure in red color to STDERR. :param message: the message to print :type message: :class:`str`
[ "Print", "a", "message", "indicating", "failure", "in", "red", "color", "to", "STDERR", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/setup.alt.py#L139-L151
16,970
MisterY/gnucash-portfolio
gnucash_portfolio/actions/import_exchange_rates.py
main
def main(): """ Default entry point """ importer = ExchangeRatesImporter() print("####################################") latest_rates_json = importer.get_latest_rates() # translate into an array of PriceModels # TODO mapper = currencyrates.FixerioModelMapper() mapper = None rates = mapper.map_to_model(latest_rates_json) print("####################################") print("importing rates into gnucash...") # For writing, use True below. with BookAggregate(for_writing=False) as svc: svc.currencies.import_fx_rates(rates) print("####################################") print("displaying rates from gnucash...") importer.display_gnucash_rates()
python
def main(): """ Default entry point """ importer = ExchangeRatesImporter() print("####################################") latest_rates_json = importer.get_latest_rates() # translate into an array of PriceModels # TODO mapper = currencyrates.FixerioModelMapper() mapper = None rates = mapper.map_to_model(latest_rates_json) print("####################################") print("importing rates into gnucash...") # For writing, use True below. with BookAggregate(for_writing=False) as svc: svc.currencies.import_fx_rates(rates) print("####################################") print("displaying rates from gnucash...") importer.display_gnucash_rates()
[ "def", "main", "(", ")", ":", "importer", "=", "ExchangeRatesImporter", "(", ")", "print", "(", "\"####################################\"", ")", "latest_rates_json", "=", "importer", ".", "get_latest_rates", "(", ")", "# translate into an array of PriceModels", "# TODO mapper = currencyrates.FixerioModelMapper()", "mapper", "=", "None", "rates", "=", "mapper", ".", "map_to_model", "(", "latest_rates_json", ")", "print", "(", "\"####################################\"", ")", "print", "(", "\"importing rates into gnucash...\"", ")", "# For writing, use True below.", "with", "BookAggregate", "(", "for_writing", "=", "False", ")", "as", "svc", ":", "svc", ".", "currencies", ".", "import_fx_rates", "(", "rates", ")", "print", "(", "\"####################################\"", ")", "print", "(", "\"displaying rates from gnucash...\"", ")", "importer", ".", "display_gnucash_rates", "(", ")" ]
Default entry point
[ "Default", "entry", "point" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/import_exchange_rates.py#L68-L90
16,971
MisterY/gnucash-portfolio
reports/report_asset_allocation/report_asset_allocation.py
generate_asset_allocation_report
def generate_asset_allocation_report(book_url): """ The otput is generated here. Separated from the generate_report function to allow executing from the command line. """ model = load_asset_allocation_model(book_url) # load display template template = templates.load_jinja_template("report_asset_allocation.html") # render template result = template.render(model=model) # **locals() return result
python
def generate_asset_allocation_report(book_url): """ The otput is generated here. Separated from the generate_report function to allow executing from the command line. """ model = load_asset_allocation_model(book_url) # load display template template = templates.load_jinja_template("report_asset_allocation.html") # render template result = template.render(model=model) # **locals() return result
[ "def", "generate_asset_allocation_report", "(", "book_url", ")", ":", "model", "=", "load_asset_allocation_model", "(", "book_url", ")", "# load display template", "template", "=", "templates", ".", "load_jinja_template", "(", "\"report_asset_allocation.html\"", ")", "# render template", "result", "=", "template", ".", "render", "(", "model", "=", "model", ")", "# **locals()", "return", "result" ]
The otput is generated here. Separated from the generate_report function to allow executing from the command line.
[ "The", "otput", "is", "generated", "here", ".", "Separated", "from", "the", "generate_report", "function", "to", "allow", "executing", "from", "the", "command", "line", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/reports/report_asset_allocation/report_asset_allocation.py#L28-L41
16,972
MisterY/gnucash-portfolio
gnucash_portfolio/model/price_model.py
PriceModel_Csv.parse_value
def parse_value(self, value_string: str): """ Parses the amount string. """ self.value = Decimal(value_string) return self.value
python
def parse_value(self, value_string: str): """ Parses the amount string. """ self.value = Decimal(value_string) return self.value
[ "def", "parse_value", "(", "self", ",", "value_string", ":", "str", ")", ":", "self", ".", "value", "=", "Decimal", "(", "value_string", ")", "return", "self", ".", "value" ]
Parses the amount string.
[ "Parses", "the", "amount", "string", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/model/price_model.py#L27-L32
16,973
MisterY/gnucash-portfolio
gnucash_portfolio/model/price_model.py
PriceModel_Csv.parse
def parse(self, csv_row: str): """ Parses the .csv row into own values """ self.date = self.parse_euro_date(csv_row[2]) self.symbol = csv_row[0] self.value = self.parse_value(csv_row[1]) return self
python
def parse(self, csv_row: str): """ Parses the .csv row into own values """ self.date = self.parse_euro_date(csv_row[2]) self.symbol = csv_row[0] self.value = self.parse_value(csv_row[1]) return self
[ "def", "parse", "(", "self", ",", "csv_row", ":", "str", ")", ":", "self", ".", "date", "=", "self", ".", "parse_euro_date", "(", "csv_row", "[", "2", "]", ")", "self", ".", "symbol", "=", "csv_row", "[", "0", "]", "self", ".", "value", "=", "self", ".", "parse_value", "(", "csv_row", "[", "1", "]", ")", "return", "self" ]
Parses the .csv row into own values
[ "Parses", "the", ".", "csv", "row", "into", "own", "values" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/model/price_model.py#L34-L39
16,974
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountAggregate.load_cash_balances_with_children
def load_cash_balances_with_children(self, root_account_fullname: str): """ loads data for cash balances """ assert isinstance(root_account_fullname, str) svc = AccountsAggregate(self.book) root_account = svc.get_by_fullname(root_account_fullname) if not root_account: raise ValueError("Account not found", root_account_fullname) accounts = self.__get_all_child_accounts_as_array(root_account) # read cash balances model = {} for account in accounts: if account.commodity.namespace != "CURRENCY" or account.placeholder: continue # separate per currency currency_symbol = account.commodity.mnemonic if not currency_symbol in model: # Add the currency branch. currency_record = { "name": currency_symbol, "total": 0, "rows": [] } # Append to the root. model[currency_symbol] = currency_record else: currency_record = model[currency_symbol] #acct_svc = AccountAggregate(self.book, account) balance = account.get_balance() row = { "name": account.name, "fullname": account.fullname, "currency": currency_symbol, "balance": balance } currency_record["rows"].append(row) # add to total total = Decimal(currency_record["total"]) total += balance currency_record["total"] = total return model
python
def load_cash_balances_with_children(self, root_account_fullname: str): """ loads data for cash balances """ assert isinstance(root_account_fullname, str) svc = AccountsAggregate(self.book) root_account = svc.get_by_fullname(root_account_fullname) if not root_account: raise ValueError("Account not found", root_account_fullname) accounts = self.__get_all_child_accounts_as_array(root_account) # read cash balances model = {} for account in accounts: if account.commodity.namespace != "CURRENCY" or account.placeholder: continue # separate per currency currency_symbol = account.commodity.mnemonic if not currency_symbol in model: # Add the currency branch. currency_record = { "name": currency_symbol, "total": 0, "rows": [] } # Append to the root. model[currency_symbol] = currency_record else: currency_record = model[currency_symbol] #acct_svc = AccountAggregate(self.book, account) balance = account.get_balance() row = { "name": account.name, "fullname": account.fullname, "currency": currency_symbol, "balance": balance } currency_record["rows"].append(row) # add to total total = Decimal(currency_record["total"]) total += balance currency_record["total"] = total return model
[ "def", "load_cash_balances_with_children", "(", "self", ",", "root_account_fullname", ":", "str", ")", ":", "assert", "isinstance", "(", "root_account_fullname", ",", "str", ")", "svc", "=", "AccountsAggregate", "(", "self", ".", "book", ")", "root_account", "=", "svc", ".", "get_by_fullname", "(", "root_account_fullname", ")", "if", "not", "root_account", ":", "raise", "ValueError", "(", "\"Account not found\"", ",", "root_account_fullname", ")", "accounts", "=", "self", ".", "__get_all_child_accounts_as_array", "(", "root_account", ")", "# read cash balances", "model", "=", "{", "}", "for", "account", "in", "accounts", ":", "if", "account", ".", "commodity", ".", "namespace", "!=", "\"CURRENCY\"", "or", "account", ".", "placeholder", ":", "continue", "# separate per currency", "currency_symbol", "=", "account", ".", "commodity", ".", "mnemonic", "if", "not", "currency_symbol", "in", "model", ":", "# Add the currency branch.", "currency_record", "=", "{", "\"name\"", ":", "currency_symbol", ",", "\"total\"", ":", "0", ",", "\"rows\"", ":", "[", "]", "}", "# Append to the root.", "model", "[", "currency_symbol", "]", "=", "currency_record", "else", ":", "currency_record", "=", "model", "[", "currency_symbol", "]", "#acct_svc = AccountAggregate(self.book, account)", "balance", "=", "account", ".", "get_balance", "(", ")", "row", "=", "{", "\"name\"", ":", "account", ".", "name", ",", "\"fullname\"", ":", "account", ".", "fullname", ",", "\"currency\"", ":", "currency_symbol", ",", "\"balance\"", ":", "balance", "}", "currency_record", "[", "\"rows\"", "]", ".", "append", "(", "row", ")", "# add to total", "total", "=", "Decimal", "(", "currency_record", "[", "\"total\"", "]", ")", "total", "+=", "balance", "currency_record", "[", "\"total\"", "]", "=", "total", "return", "model" ]
loads data for cash balances
[ "loads", "data", "for", "cash", "balances" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L56-L102
16,975
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountAggregate.get_balance
def get_balance(self): """ Current account balance """ on_date = Datum() on_date.today() return self.get_balance_on(on_date.value)
python
def get_balance(self): """ Current account balance """ on_date = Datum() on_date.today() return self.get_balance_on(on_date.value)
[ "def", "get_balance", "(", "self", ")", ":", "on_date", "=", "Datum", "(", ")", "on_date", ".", "today", "(", ")", "return", "self", ".", "get_balance_on", "(", "on_date", ".", "value", ")" ]
Current account balance
[ "Current", "account", "balance" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L129-L133
16,976
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountAggregate.get_splits_query
def get_splits_query(self): """ Returns all the splits in the account """ query = ( self.book.session.query(Split) .filter(Split.account == self.account) ) return query
python
def get_splits_query(self): """ Returns all the splits in the account """ query = ( self.book.session.query(Split) .filter(Split.account == self.account) ) return query
[ "def", "get_splits_query", "(", "self", ")", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Split", ")", ".", "filter", "(", "Split", ".", "account", "==", "self", ".", "account", ")", ")", "return", "query" ]
Returns all the splits in the account
[ "Returns", "all", "the", "splits", "in", "the", "account" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L164-L170
16,977
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountAggregate.get_transactions
def get_transactions(self, date_from: datetime, date_to: datetime) -> List[Transaction]: """ Returns account transactions """ assert isinstance(date_from, datetime) assert isinstance(date_to, datetime) # fix up the parameters as we need datetime dt_from = Datum() dt_from.from_datetime(date_from) dt_from.start_of_day() dt_to = Datum() dt_to.from_datetime(date_to) dt_to.end_of_day() query = ( self.book.session.query(Transaction) .join(Split) .filter(Split.account_guid == self.account.guid) .filter(Transaction.post_date >= dt_from.date, Transaction.post_date <= dt_to.date) .order_by(Transaction.post_date) ) return query.all()
python
def get_transactions(self, date_from: datetime, date_to: datetime) -> List[Transaction]: """ Returns account transactions """ assert isinstance(date_from, datetime) assert isinstance(date_to, datetime) # fix up the parameters as we need datetime dt_from = Datum() dt_from.from_datetime(date_from) dt_from.start_of_day() dt_to = Datum() dt_to.from_datetime(date_to) dt_to.end_of_day() query = ( self.book.session.query(Transaction) .join(Split) .filter(Split.account_guid == self.account.guid) .filter(Transaction.post_date >= dt_from.date, Transaction.post_date <= dt_to.date) .order_by(Transaction.post_date) ) return query.all()
[ "def", "get_transactions", "(", "self", ",", "date_from", ":", "datetime", ",", "date_to", ":", "datetime", ")", "->", "List", "[", "Transaction", "]", ":", "assert", "isinstance", "(", "date_from", ",", "datetime", ")", "assert", "isinstance", "(", "date_to", ",", "datetime", ")", "# fix up the parameters as we need datetime", "dt_from", "=", "Datum", "(", ")", "dt_from", ".", "from_datetime", "(", "date_from", ")", "dt_from", ".", "start_of_day", "(", ")", "dt_to", "=", "Datum", "(", ")", "dt_to", ".", "from_datetime", "(", "date_to", ")", "dt_to", ".", "end_of_day", "(", ")", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Transaction", ")", ".", "join", "(", "Split", ")", ".", "filter", "(", "Split", ".", "account_guid", "==", "self", ".", "account", ".", "guid", ")", ".", "filter", "(", "Transaction", ".", "post_date", ">=", "dt_from", ".", "date", ",", "Transaction", ".", "post_date", "<=", "dt_to", ".", "date", ")", ".", "order_by", "(", "Transaction", ".", "post_date", ")", ")", "return", "query", ".", "all", "(", ")" ]
Returns account transactions
[ "Returns", "account", "transactions" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L197-L217
16,978
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountAggregate.__get_all_child_accounts_as_array
def __get_all_child_accounts_as_array(self, account: Account) -> List[Account]: """ Returns the whole tree of child accounts in a list """ result = [] # ignore placeholders ? - what if a brokerage account has cash/stocks division? # if not account.placeholder: # continue result.append(account) for child in account.children: sub_accounts = self.__get_all_child_accounts_as_array(child) result += sub_accounts return result
python
def __get_all_child_accounts_as_array(self, account: Account) -> List[Account]: """ Returns the whole tree of child accounts in a list """ result = [] # ignore placeholders ? - what if a brokerage account has cash/stocks division? # if not account.placeholder: # continue result.append(account) for child in account.children: sub_accounts = self.__get_all_child_accounts_as_array(child) result += sub_accounts return result
[ "def", "__get_all_child_accounts_as_array", "(", "self", ",", "account", ":", "Account", ")", "->", "List", "[", "Account", "]", ":", "result", "=", "[", "]", "# ignore placeholders ? - what if a brokerage account has cash/stocks division?", "# if not account.placeholder:", "# continue", "result", ".", "append", "(", "account", ")", "for", "child", "in", "account", ".", "children", ":", "sub_accounts", "=", "self", ".", "__get_all_child_accounts_as_array", "(", "child", ")", "result", "+=", "sub_accounts", "return", "result" ]
Returns the whole tree of child accounts in a list
[ "Returns", "the", "whole", "tree", "of", "child", "accounts", "in", "a", "list" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L222-L234
16,979
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.find_by_name
def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]: """ Search for account by part of the name """ query = ( self.query .filter(Account.name.like('%' + term + '%')) .order_by(Account.name) ) # Exclude placeholder accounts? if not include_placeholders: query = query.filter(Account.placeholder == 0) # print(generic.get_sql(query)) return query.all()
python
def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]: """ Search for account by part of the name """ query = ( self.query .filter(Account.name.like('%' + term + '%')) .order_by(Account.name) ) # Exclude placeholder accounts? if not include_placeholders: query = query.filter(Account.placeholder == 0) # print(generic.get_sql(query)) return query.all()
[ "def", "find_by_name", "(", "self", ",", "term", ":", "str", ",", "include_placeholders", ":", "bool", "=", "False", ")", "->", "List", "[", "Account", "]", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Account", ".", "name", ".", "like", "(", "'%'", "+", "term", "+", "'%'", ")", ")", ".", "order_by", "(", "Account", ".", "name", ")", ")", "# Exclude placeholder accounts?", "if", "not", "include_placeholders", ":", "query", "=", "query", ".", "filter", "(", "Account", ".", "placeholder", "==", "0", ")", "# print(generic.get_sql(query))", "return", "query", ".", "all", "(", ")" ]
Search for account by part of the name
[ "Search", "for", "account", "by", "part", "of", "the", "name" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L244-L256
16,980
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_aggregate_by_id
def get_aggregate_by_id(self, account_id: str) -> AccountAggregate: """ Returns the aggregate for the given id """ account = self.get_by_id(account_id) return self.get_account_aggregate(account)
python
def get_aggregate_by_id(self, account_id: str) -> AccountAggregate: """ Returns the aggregate for the given id """ account = self.get_by_id(account_id) return self.get_account_aggregate(account)
[ "def", "get_aggregate_by_id", "(", "self", ",", "account_id", ":", "str", ")", "->", "AccountAggregate", ":", "account", "=", "self", ".", "get_by_id", "(", "account_id", ")", "return", "self", ".", "get_account_aggregate", "(", "account", ")" ]
Returns the aggregate for the given id
[ "Returns", "the", "aggregate", "for", "the", "given", "id" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L258-L261
16,981
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_by_fullname
def get_by_fullname(self, fullname: str) -> Account: """ Loads account by full name """ # get all accounts and iterate, comparing the fullname. :S query = ( self.book.session.query(Account) ) # generic.get_sql() # print(sql) all_accounts = query.all() for account in all_accounts: if account.fullname == fullname: return account # else return None
python
def get_by_fullname(self, fullname: str) -> Account: """ Loads account by full name """ # get all accounts and iterate, comparing the fullname. :S query = ( self.book.session.query(Account) ) # generic.get_sql() # print(sql) all_accounts = query.all() for account in all_accounts: if account.fullname == fullname: return account # else return None
[ "def", "get_by_fullname", "(", "self", ",", "fullname", ":", "str", ")", "->", "Account", ":", "# get all accounts and iterate, comparing the fullname. :S", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Account", ")", ")", "# generic.get_sql()", "# print(sql)", "all_accounts", "=", "query", ".", "all", "(", ")", "for", "account", "in", "all_accounts", ":", "if", "account", ".", "fullname", "==", "fullname", ":", "return", "account", "# else", "return", "None" ]
Loads account by full name
[ "Loads", "account", "by", "full", "name" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L263-L276
16,982
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_account_id_by_fullname
def get_account_id_by_fullname(self, fullname: str) -> str: """ Locates the account by fullname """ account = self.get_by_fullname(fullname) return account.guid
python
def get_account_id_by_fullname(self, fullname: str) -> str: """ Locates the account by fullname """ account = self.get_by_fullname(fullname) return account.guid
[ "def", "get_account_id_by_fullname", "(", "self", ",", "fullname", ":", "str", ")", "->", "str", ":", "account", "=", "self", ".", "get_by_fullname", "(", "fullname", ")", "return", "account", ".", "guid" ]
Locates the account by fullname
[ "Locates", "the", "account", "by", "fullname" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L278-L281
16,983
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_all_children
def get_all_children(self, fullname: str) -> List[Account]: """ Returns the whole child account tree for the account with the given full name """ # find the account by fullname root_acct = self.get_by_fullname(fullname) if not root_acct: raise NameError("Account not found in book!") acct_agg = self.get_account_aggregate(root_acct) result = acct_agg.get_all_child_accounts_as_array() # for child in root_acct.children: # log(DEBUG, "found child %s", child.fullname) return result
python
def get_all_children(self, fullname: str) -> List[Account]: """ Returns the whole child account tree for the account with the given full name """ # find the account by fullname root_acct = self.get_by_fullname(fullname) if not root_acct: raise NameError("Account not found in book!") acct_agg = self.get_account_aggregate(root_acct) result = acct_agg.get_all_child_accounts_as_array() # for child in root_acct.children: # log(DEBUG, "found child %s", child.fullname) return result
[ "def", "get_all_children", "(", "self", ",", "fullname", ":", "str", ")", "->", "List", "[", "Account", "]", ":", "# find the account by fullname", "root_acct", "=", "self", ".", "get_by_fullname", "(", "fullname", ")", "if", "not", "root_acct", ":", "raise", "NameError", "(", "\"Account not found in book!\"", ")", "acct_agg", "=", "self", ".", "get_account_aggregate", "(", "root_acct", ")", "result", "=", "acct_agg", ".", "get_all_child_accounts_as_array", "(", ")", "# for child in root_acct.children:", "# log(DEBUG, \"found child %s\", child.fullname)", "return", "result" ]
Returns the whole child account tree for the account with the given full name
[ "Returns", "the", "whole", "child", "account", "tree", "for", "the", "account", "with", "the", "given", "full", "name" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L283-L294
16,984
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_all
def get_all(self) -> List[Account]: """ Returns all book accounts as a list, excluding templates. """ return [account for account in self.book.accounts if account.parent.name != "Template Root"]
python
def get_all(self) -> List[Account]: """ Returns all book accounts as a list, excluding templates. """ return [account for account in self.book.accounts if account.parent.name != "Template Root"]
[ "def", "get_all", "(", "self", ")", "->", "List", "[", "Account", "]", ":", "return", "[", "account", "for", "account", "in", "self", ".", "book", ".", "accounts", "if", "account", ".", "parent", ".", "name", "!=", "\"Template Root\"", "]" ]
Returns all book accounts as a list, excluding templates.
[ "Returns", "all", "book", "accounts", "as", "a", "list", "excluding", "templates", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L296-L298
16,985
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_favourite_accounts
def get_favourite_accounts(self) -> List[Account]: """ Provides a list of favourite accounts """ from gnucash_portfolio.lib.settings import Settings settings = Settings() favourite_accts = settings.favourite_accounts accounts = self.get_list(favourite_accts) return accounts
python
def get_favourite_accounts(self) -> List[Account]: """ Provides a list of favourite accounts """ from gnucash_portfolio.lib.settings import Settings settings = Settings() favourite_accts = settings.favourite_accounts accounts = self.get_list(favourite_accts) return accounts
[ "def", "get_favourite_accounts", "(", "self", ")", "->", "List", "[", "Account", "]", ":", "from", "gnucash_portfolio", ".", "lib", ".", "settings", "import", "Settings", "settings", "=", "Settings", "(", ")", "favourite_accts", "=", "settings", ".", "favourite_accounts", "accounts", "=", "self", ".", "get_list", "(", "favourite_accts", ")", "return", "accounts" ]
Provides a list of favourite accounts
[ "Provides", "a", "list", "of", "favourite", "accounts" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L304-L311
16,986
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_favourite_account_aggregates
def get_favourite_account_aggregates(self) -> List[AccountAggregate]: """ Returns the list of aggregates for favourite accounts """ accounts = self.get_favourite_accounts() aggregates = [] for account in accounts: aggregate = self.get_account_aggregate(account) aggregates.append(aggregate) return aggregates
python
def get_favourite_account_aggregates(self) -> List[AccountAggregate]: """ Returns the list of aggregates for favourite accounts """ accounts = self.get_favourite_accounts() aggregates = [] for account in accounts: aggregate = self.get_account_aggregate(account) aggregates.append(aggregate) return aggregates
[ "def", "get_favourite_account_aggregates", "(", "self", ")", "->", "List", "[", "AccountAggregate", "]", ":", "accounts", "=", "self", ".", "get_favourite_accounts", "(", ")", "aggregates", "=", "[", "]", "for", "account", "in", "accounts", ":", "aggregate", "=", "self", ".", "get_account_aggregate", "(", "account", ")", "aggregates", ".", "append", "(", "aggregate", ")", "return", "aggregates" ]
Returns the list of aggregates for favourite accounts
[ "Returns", "the", "list", "of", "aggregates", "for", "favourite", "accounts" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L313-L321
16,987
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_by_id
def get_by_id(self, acct_id) -> Account: """ Loads an account entity """ return self.book.get(Account, guid=acct_id)
python
def get_by_id(self, acct_id) -> Account: """ Loads an account entity """ return self.book.get(Account, guid=acct_id)
[ "def", "get_by_id", "(", "self", ",", "acct_id", ")", "->", "Account", ":", "return", "self", ".", "book", ".", "get", "(", "Account", ",", "guid", "=", "acct_id", ")" ]
Loads an account entity
[ "Loads", "an", "account", "entity" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L323-L325
16,988
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_by_name
def get_by_name(self, name: str) -> List[Account]: """ Searches accounts by name """ # return self.query.filter(Account.name == name).all() return self.get_by_name_from(self.book.root, name)
python
def get_by_name(self, name: str) -> List[Account]: """ Searches accounts by name """ # return self.query.filter(Account.name == name).all() return self.get_by_name_from(self.book.root, name)
[ "def", "get_by_name", "(", "self", ",", "name", ":", "str", ")", "->", "List", "[", "Account", "]", ":", "# return self.query.filter(Account.name == name).all()", "return", "self", ".", "get_by_name_from", "(", "self", ".", "book", ".", "root", ",", "name", ")" ]
Searches accounts by name
[ "Searches", "accounts", "by", "name" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L327-L330
16,989
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_by_name_from
def get_by_name_from(self, root: Account, name: str) -> List[Account]: """ Searches child accounts by name, starting from the given account """ result = [] if root.name == name: result.append(root) for child in root.children: child_results = self.get_by_name_from(child, name) result += child_results return result
python
def get_by_name_from(self, root: Account, name: str) -> List[Account]: """ Searches child accounts by name, starting from the given account """ result = [] if root.name == name: result.append(root) for child in root.children: child_results = self.get_by_name_from(child, name) result += child_results return result
[ "def", "get_by_name_from", "(", "self", ",", "root", ":", "Account", ",", "name", ":", "str", ")", "->", "List", "[", "Account", "]", ":", "result", "=", "[", "]", "if", "root", ".", "name", "==", "name", ":", "result", ".", "append", "(", "root", ")", "for", "child", "in", "root", ".", "children", ":", "child_results", "=", "self", ".", "get_by_name_from", "(", "child", ",", "name", ")", "result", "+=", "child_results", "return", "result" ]
Searches child accounts by name, starting from the given account
[ "Searches", "child", "accounts", "by", "name", "starting", "from", "the", "given", "account" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L332-L343
16,990
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.get_list
def get_list(self, ids: List[str]) -> List[Account]: """ Loads accounts by the ids passed as an argument """ query = ( self.query .filter(Account.guid.in_(ids)) ) return query.all()
python
def get_list(self, ids: List[str]) -> List[Account]: """ Loads accounts by the ids passed as an argument """ query = ( self.query .filter(Account.guid.in_(ids)) ) return query.all()
[ "def", "get_list", "(", "self", ",", "ids", ":", "List", "[", "str", "]", ")", "->", "List", "[", "Account", "]", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Account", ".", "guid", ".", "in_", "(", "ids", ")", ")", ")", "return", "query", ".", "all", "(", ")" ]
Loads accounts by the ids passed as an argument
[ "Loads", "accounts", "by", "the", "ids", "passed", "as", "an", "argument" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L345-L351
16,991
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.query
def query(self): """ Main accounts query """ query = ( self.book.session.query(Account) .join(Commodity) .filter(Commodity.namespace != "template") .filter(Account.type != AccountType.root.value) ) return query
python
def query(self): """ Main accounts query """ query = ( self.book.session.query(Account) .join(Commodity) .filter(Commodity.namespace != "template") .filter(Account.type != AccountType.root.value) ) return query
[ "def", "query", "(", "self", ")", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Account", ")", ".", "join", "(", "Commodity", ")", ".", "filter", "(", "Commodity", ".", "namespace", "!=", "\"template\"", ")", ".", "filter", "(", "Account", ".", "type", "!=", "AccountType", ".", "root", ".", "value", ")", ")", "return", "query" ]
Main accounts query
[ "Main", "accounts", "query" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L354-L362
16,992
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
AccountsAggregate.search
def search(self, name: str = None, acc_type: str = None): """ Search accounts by passing parameters. name = exact name name_part = part of name parent_id = id of the parent account type = account type """ query = self.query if name is not None: query = query.filter(Account.name == name) if acc_type is not None: # account type is capitalized acc_type = acc_type.upper() query = query.filter(Account.type == acc_type) return query.all()
python
def search(self, name: str = None, acc_type: str = None): """ Search accounts by passing parameters. name = exact name name_part = part of name parent_id = id of the parent account type = account type """ query = self.query if name is not None: query = query.filter(Account.name == name) if acc_type is not None: # account type is capitalized acc_type = acc_type.upper() query = query.filter(Account.type == acc_type) return query.all()
[ "def", "search", "(", "self", ",", "name", ":", "str", "=", "None", ",", "acc_type", ":", "str", "=", "None", ")", ":", "query", "=", "self", ".", "query", "if", "name", "is", "not", "None", ":", "query", "=", "query", ".", "filter", "(", "Account", ".", "name", "==", "name", ")", "if", "acc_type", "is", "not", "None", ":", "# account type is capitalized", "acc_type", "=", "acc_type", ".", "upper", "(", ")", "query", "=", "query", ".", "filter", "(", "Account", ".", "type", "==", "acc_type", ")", "return", "query", ".", "all", "(", ")" ]
Search accounts by passing parameters. name = exact name name_part = part of name parent_id = id of the parent account type = account type
[ "Search", "accounts", "by", "passing", "parameters", ".", "name", "=", "exact", "name", "name_part", "=", "part", "of", "name", "parent_id", "=", "id", "of", "the", "parent", "account", "type", "=", "account", "type" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L364-L382
16,993
MisterY/gnucash-portfolio
gnucash_portfolio/pricesaggregate.py
PricesAggregate.get_price_as_of
def get_price_as_of(self, stock: Commodity, on_date: datetime): """ Gets the latest price on or before the given date. """ # return self.get_price_as_of_query(stock, on_date).first() prices = PriceDbApplication() prices.get_prices_on(on_date.date().isoformat(), stock.namespace, stock.mnemonic)
python
def get_price_as_of(self, stock: Commodity, on_date: datetime): """ Gets the latest price on or before the given date. """ # return self.get_price_as_of_query(stock, on_date).first() prices = PriceDbApplication() prices.get_prices_on(on_date.date().isoformat(), stock.namespace, stock.mnemonic)
[ "def", "get_price_as_of", "(", "self", ",", "stock", ":", "Commodity", ",", "on_date", ":", "datetime", ")", ":", "# return self.get_price_as_of_query(stock, on_date).first()", "prices", "=", "PriceDbApplication", "(", ")", "prices", ".", "get_prices_on", "(", "on_date", ".", "date", "(", ")", ".", "isoformat", "(", ")", ",", "stock", ".", "namespace", ",", "stock", ".", "mnemonic", ")" ]
Gets the latest price on or before the given date.
[ "Gets", "the", "latest", "price", "on", "or", "before", "the", "given", "date", "." ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/pricesaggregate.py#L36-L40
16,994
MisterY/gnucash-portfolio
gnucash_portfolio/pricesaggregate.py
PricesAggregate.import_price
def import_price(self, price: PriceModel): """ Import individual price """ # Handle yahoo-style symbols with extension. symbol = price.symbol if "." in symbol: symbol = price.symbol.split(".")[0] stock = SecuritiesAggregate(self.book).get_by_symbol(symbol) # get_aggregate_for_symbol if stock is None: logging.warning("security %s not found in book.", price.symbol) return False # check if there is already a price for the date existing_prices = stock.prices.filter(Price.date == price.datetime.date()).all() if not existing_prices: # Create new price for the commodity (symbol). self.__create_price_for(stock, price) else: logging.warning("price already exists for %s on %s", stock.mnemonic, price.datetime.strftime("%Y-%m-%d")) existing_price = existing_prices[0] # update price existing_price.value = price.value return True
python
def import_price(self, price: PriceModel): """ Import individual price """ # Handle yahoo-style symbols with extension. symbol = price.symbol if "." in symbol: symbol = price.symbol.split(".")[0] stock = SecuritiesAggregate(self.book).get_by_symbol(symbol) # get_aggregate_for_symbol if stock is None: logging.warning("security %s not found in book.", price.symbol) return False # check if there is already a price for the date existing_prices = stock.prices.filter(Price.date == price.datetime.date()).all() if not existing_prices: # Create new price for the commodity (symbol). self.__create_price_for(stock, price) else: logging.warning("price already exists for %s on %s", stock.mnemonic, price.datetime.strftime("%Y-%m-%d")) existing_price = existing_prices[0] # update price existing_price.value = price.value return True
[ "def", "import_price", "(", "self", ",", "price", ":", "PriceModel", ")", ":", "# Handle yahoo-style symbols with extension.", "symbol", "=", "price", ".", "symbol", "if", "\".\"", "in", "symbol", ":", "symbol", "=", "price", ".", "symbol", ".", "split", "(", "\".\"", ")", "[", "0", "]", "stock", "=", "SecuritiesAggregate", "(", "self", ".", "book", ")", ".", "get_by_symbol", "(", "symbol", ")", "# get_aggregate_for_symbol", "if", "stock", "is", "None", ":", "logging", ".", "warning", "(", "\"security %s not found in book.\"", ",", "price", ".", "symbol", ")", "return", "False", "# check if there is already a price for the date", "existing_prices", "=", "stock", ".", "prices", ".", "filter", "(", "Price", ".", "date", "==", "price", ".", "datetime", ".", "date", "(", ")", ")", ".", "all", "(", ")", "if", "not", "existing_prices", ":", "# Create new price for the commodity (symbol).", "self", ".", "__create_price_for", "(", "stock", ",", "price", ")", "else", ":", "logging", ".", "warning", "(", "\"price already exists for %s on %s\"", ",", "stock", ".", "mnemonic", ",", "price", ".", "datetime", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", ")", "existing_price", "=", "existing_prices", "[", "0", "]", "# update price", "existing_price", ".", "value", "=", "price", ".", "value", "return", "True" ]
Import individual price
[ "Import", "individual", "price" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/pricesaggregate.py#L55-L81
16,995
MisterY/gnucash-portfolio
gnucash_portfolio/pricesaggregate.py
PricesAggregate.__create_price_for
def __create_price_for(self, commodity: Commodity, price: PriceModel): """ Creates a new Price entry in the book, for the given commodity """ logging.info("Adding a new price for %s, %s, %s", commodity.mnemonic, price.datetime.strftime("%Y-%m-%d"), price.value) # safety check. Compare currencies. sec_svc = SecurityAggregate(self.book, commodity) currency = sec_svc.get_currency() if currency != price.currency: raise ValueError( "Requested currency does not match the currency previously used", currency, price.currency) # Description of the source field values: # https://www.gnucash.org/docs/v2.6/C/gnucash-help/tool-price.html new_price = Price(commodity, currency, price.datetime.date(), price.value, source="Finance::Quote") commodity.prices.append(new_price)
python
def __create_price_for(self, commodity: Commodity, price: PriceModel): """ Creates a new Price entry in the book, for the given commodity """ logging.info("Adding a new price for %s, %s, %s", commodity.mnemonic, price.datetime.strftime("%Y-%m-%d"), price.value) # safety check. Compare currencies. sec_svc = SecurityAggregate(self.book, commodity) currency = sec_svc.get_currency() if currency != price.currency: raise ValueError( "Requested currency does not match the currency previously used", currency, price.currency) # Description of the source field values: # https://www.gnucash.org/docs/v2.6/C/gnucash-help/tool-price.html new_price = Price(commodity, currency, price.datetime.date(), price.value, source="Finance::Quote") commodity.prices.append(new_price)
[ "def", "__create_price_for", "(", "self", ",", "commodity", ":", "Commodity", ",", "price", ":", "PriceModel", ")", ":", "logging", ".", "info", "(", "\"Adding a new price for %s, %s, %s\"", ",", "commodity", ".", "mnemonic", ",", "price", ".", "datetime", ".", "strftime", "(", "\"%Y-%m-%d\"", ")", ",", "price", ".", "value", ")", "# safety check. Compare currencies.", "sec_svc", "=", "SecurityAggregate", "(", "self", ".", "book", ",", "commodity", ")", "currency", "=", "sec_svc", ".", "get_currency", "(", ")", "if", "currency", "!=", "price", ".", "currency", ":", "raise", "ValueError", "(", "\"Requested currency does not match the currency previously used\"", ",", "currency", ",", "price", ".", "currency", ")", "# Description of the source field values:", "# https://www.gnucash.org/docs/v2.6/C/gnucash-help/tool-price.html", "new_price", "=", "Price", "(", "commodity", ",", "currency", ",", "price", ".", "datetime", ".", "date", "(", ")", ",", "price", ".", "value", ",", "source", "=", "\"Finance::Quote\"", ")", "commodity", ".", "prices", ".", "append", "(", "new_price", ")" ]
Creates a new Price entry in the book, for the given commodity
[ "Creates", "a", "new", "Price", "entry", "in", "the", "book", "for", "the", "given", "commodity" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/pricesaggregate.py#L86-L105
16,996
MisterY/gnucash-portfolio
gnucash_portfolio/transactionaggregate.py
TransactionAggregate.get_splits_query
def get_splits_query(self): """ Returns the query for related splits """ query = ( self.book.session.query(Split) # .join(Transaction) .filter(Split.transaction_guid == self.transaction.guid) ) return query
python
def get_splits_query(self): """ Returns the query for related splits """ query = ( self.book.session.query(Split) # .join(Transaction) .filter(Split.transaction_guid == self.transaction.guid) ) return query
[ "def", "get_splits_query", "(", "self", ")", ":", "query", "=", "(", "self", ".", "book", ".", "session", ".", "query", "(", "Split", ")", "# .join(Transaction)", ".", "filter", "(", "Split", ".", "transaction_guid", "==", "self", ".", "transaction", ".", "guid", ")", ")", "return", "query" ]
Returns the query for related splits
[ "Returns", "the", "query", "for", "related", "splits" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/transactionaggregate.py#L12-L19
16,997
MisterY/gnucash-portfolio
reports/report_vanguard_prices/report_vanguard_prices.py
generate_report
def generate_report( book_url, fund_ids: StringOption( section="Funds", sort_tag="c", documentation_string="Comma-separated list of fund ids.", default_value="8123,8146,8148,8147") ): """Generates the report output""" return render_report(book_url, fund_ids)
python
def generate_report( book_url, fund_ids: StringOption( section="Funds", sort_tag="c", documentation_string="Comma-separated list of fund ids.", default_value="8123,8146,8148,8147") ): """Generates the report output""" return render_report(book_url, fund_ids)
[ "def", "generate_report", "(", "book_url", ",", "fund_ids", ":", "StringOption", "(", "section", "=", "\"Funds\"", ",", "sort_tag", "=", "\"c\"", ",", "documentation_string", "=", "\"Comma-separated list of fund ids.\"", ",", "default_value", "=", "\"8123,8146,8148,8147\"", ")", ")", ":", "return", "render_report", "(", "book_url", ",", "fund_ids", ")" ]
Generates the report output
[ "Generates", "the", "report", "output" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/reports/report_vanguard_prices/report_vanguard_prices.py#L18-L27
16,998
MisterY/gnucash-portfolio
gnucash_portfolio/actions/search_for_account.py
searchAccount
def searchAccount(searchTerm, book): """Searches through account names""" print("Search results:\n") found = False # search for account in book.accounts: # print(account.fullname) # name if searchTerm.lower() in account.fullname.lower(): print(account.fullname) found = True if not found: print("Search term not found in account names.")
python
def searchAccount(searchTerm, book): """Searches through account names""" print("Search results:\n") found = False # search for account in book.accounts: # print(account.fullname) # name if searchTerm.lower() in account.fullname.lower(): print(account.fullname) found = True if not found: print("Search term not found in account names.")
[ "def", "searchAccount", "(", "searchTerm", ",", "book", ")", ":", "print", "(", "\"Search results:\\n\"", ")", "found", "=", "False", "# search", "for", "account", "in", "book", ".", "accounts", ":", "# print(account.fullname)", "# name", "if", "searchTerm", ".", "lower", "(", ")", "in", "account", ".", "fullname", ".", "lower", "(", ")", ":", "print", "(", "account", ".", "fullname", ")", "found", "=", "True", "if", "not", "found", ":", "print", "(", "\"Search term not found in account names.\"", ")" ]
Searches through account names
[ "Searches", "through", "account", "names" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/actions/search_for_account.py#L21-L36
16,999
MisterY/gnucash-portfolio
gnucash_portfolio/lib/database.py
Database.display_db_info
def display_db_info(self): """Displays some basic info about the GnuCash book""" with self.open_book() as book: default_currency = book.default_currency print("Default currency is ", default_currency.mnemonic)
python
def display_db_info(self): """Displays some basic info about the GnuCash book""" with self.open_book() as book: default_currency = book.default_currency print("Default currency is ", default_currency.mnemonic)
[ "def", "display_db_info", "(", "self", ")", ":", "with", "self", ".", "open_book", "(", ")", "as", "book", ":", "default_currency", "=", "book", ".", "default_currency", "print", "(", "\"Default currency is \"", ",", "default_currency", ".", "mnemonic", ")" ]
Displays some basic info about the GnuCash book
[ "Displays", "some", "basic", "info", "about", "the", "GnuCash", "book" ]
bfaad8345a5479d1cd111acee1939e25c2a638c2
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/lib/database.py#L31-L35