repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
j0057/github-release
github_release.py
_recursive_gh_get
def _recursive_gh_get(href, items): """Recursively get list of GitHub objects. See https://developer.github.com/v3/guides/traversing-with-pagination/ """ response = _request('GET', href) response.raise_for_status() items.extend(response.json()) if "link" not in response.headers: return links = link_header.parse(response.headers["link"]) rels = {link.rel: link.href for link in links.links} if "next" in rels: _recursive_gh_get(rels["next"], items)
python
def _recursive_gh_get(href, items): """Recursively get list of GitHub objects. See https://developer.github.com/v3/guides/traversing-with-pagination/ """ response = _request('GET', href) response.raise_for_status() items.extend(response.json()) if "link" not in response.headers: return links = link_header.parse(response.headers["link"]) rels = {link.rel: link.href for link in links.links} if "next" in rels: _recursive_gh_get(rels["next"], items)
Recursively get list of GitHub objects. See https://developer.github.com/v3/guides/traversing-with-pagination/
https://github.com/j0057/github-release/blob/5421d1ad3e49eaad50c800e548f889d55e159b9d/github_release.py#L148-L161
j0057/github-release
github_release.py
main
def main(github_token, github_api_url, progress): """A CLI to easily manage GitHub releases, assets and references.""" global progress_reporter_cls progress_reporter_cls.reportProgress = sys.stdout.isatty() and progress if progress_reporter_cls.reportProgress: progress_reporter_cls = _progress_bar global _github_token_cli_arg _github_token_cli_arg = github_token global _github_api_url _github_api_url = github_api_url
python
def main(github_token, github_api_url, progress): """A CLI to easily manage GitHub releases, assets and references.""" global progress_reporter_cls progress_reporter_cls.reportProgress = sys.stdout.isatty() and progress if progress_reporter_cls.reportProgress: progress_reporter_cls = _progress_bar global _github_token_cli_arg _github_token_cli_arg = github_token global _github_api_url _github_api_url = github_api_url
A CLI to easily manage GitHub releases, assets and references.
https://github.com/j0057/github-release/blob/5421d1ad3e49eaad50c800e548f889d55e159b9d/github_release.py#L180-L189
j0057/github-release
github_release.py
_update_release_sha
def _update_release_sha(repo_name, tag_name, new_release_sha, dry_run): """Update the commit associated with a given release tag. Since updating a tag commit is not directly possible, this function does the following steps: * set the release tag to ``<tag_name>-tmp`` and associate it with ``new_release_sha``. * delete tag ``refs/tags/<tag_name>``. * update the release tag to ``<tag_name>`` and associate it with ``new_release_sha``. """ if new_release_sha is None: return refs = get_refs(repo_name, tags=True, pattern="refs/tags/%s" % tag_name) if not refs: return assert len(refs) == 1 # If sha associated with "<tag_name>" is up-to-date, we are done. previous_release_sha = refs[0]["object"]["sha"] if previous_release_sha == new_release_sha: return tmp_tag_name = tag_name + "-tmp" # If any, remove leftover temporary tag "<tag_name>-tmp" refs = get_refs(repo_name, tags=True, pattern="refs/tags/%s" % tmp_tag_name) if refs: assert len(refs) == 1 time.sleep(0.1) gh_ref_delete(repo_name, "refs/tags/%s" % tmp_tag_name, dry_run=dry_run) # Update "<tag_name>" release by associating it with the "<tag_name>-tmp" # and "<new_release_sha>". It will create the temporary tag. time.sleep(0.1) patch_release(repo_name, tag_name, tag_name=tmp_tag_name, target_commitish=new_release_sha, dry_run=dry_run) # Now "<tag_name>-tmp" references "<new_release_sha>", remove "<tag_name>" time.sleep(0.1) gh_ref_delete(repo_name, "refs/tags/%s" % tag_name, dry_run=dry_run) # Finally, update "<tag_name>-tmp" release by associating it with the # "<tag_name>" and "<new_release_sha>". time.sleep(0.1) patch_release(repo_name, tmp_tag_name, tag_name=tag_name, target_commitish=new_release_sha, dry_run=dry_run) # ... and remove "<tag_name>-tmp" time.sleep(0.1) gh_ref_delete(repo_name, "refs/tags/%s" % tmp_tag_name, dry_run=dry_run)
python
def _update_release_sha(repo_name, tag_name, new_release_sha, dry_run): """Update the commit associated with a given release tag. Since updating a tag commit is not directly possible, this function does the following steps: * set the release tag to ``<tag_name>-tmp`` and associate it with ``new_release_sha``. * delete tag ``refs/tags/<tag_name>``. * update the release tag to ``<tag_name>`` and associate it with ``new_release_sha``. """ if new_release_sha is None: return refs = get_refs(repo_name, tags=True, pattern="refs/tags/%s" % tag_name) if not refs: return assert len(refs) == 1 # If sha associated with "<tag_name>" is up-to-date, we are done. previous_release_sha = refs[0]["object"]["sha"] if previous_release_sha == new_release_sha: return tmp_tag_name = tag_name + "-tmp" # If any, remove leftover temporary tag "<tag_name>-tmp" refs = get_refs(repo_name, tags=True, pattern="refs/tags/%s" % tmp_tag_name) if refs: assert len(refs) == 1 time.sleep(0.1) gh_ref_delete(repo_name, "refs/tags/%s" % tmp_tag_name, dry_run=dry_run) # Update "<tag_name>" release by associating it with the "<tag_name>-tmp" # and "<new_release_sha>". It will create the temporary tag. time.sleep(0.1) patch_release(repo_name, tag_name, tag_name=tmp_tag_name, target_commitish=new_release_sha, dry_run=dry_run) # Now "<tag_name>-tmp" references "<new_release_sha>", remove "<tag_name>" time.sleep(0.1) gh_ref_delete(repo_name, "refs/tags/%s" % tag_name, dry_run=dry_run) # Finally, update "<tag_name>-tmp" release by associating it with the # "<tag_name>" and "<new_release_sha>". time.sleep(0.1) patch_release(repo_name, tmp_tag_name, tag_name=tag_name, target_commitish=new_release_sha, dry_run=dry_run) # ... and remove "<tag_name>-tmp" time.sleep(0.1) gh_ref_delete(repo_name, "refs/tags/%s" % tmp_tag_name, dry_run=dry_run)
Update the commit associated with a given release tag. Since updating a tag commit is not directly possible, this function does the following steps: * set the release tag to ``<tag_name>-tmp`` and associate it with ``new_release_sha``. * delete tag ``refs/tags/<tag_name>``. * update the release tag to ``<tag_name>`` and associate it with ``new_release_sha``.
https://github.com/j0057/github-release/blob/5421d1ad3e49eaad50c800e548f889d55e159b9d/github_release.py#L287-L343
lappis-unb/salic-ml
src/salicml/metrics/finance/approved_funds.py
approved_funds
def approved_funds(pronac, dt): """ Verifica se o valor total de um projeto é um outlier em relação aos projetos do mesmo seguimento cultural Dataframes: planilha_orcamentaria """ funds_df = data.approved_funds_by_projects project = ( funds_df .loc[funds_df['PRONAC'] == pronac] ) project = project.to_dict('records')[0] info = ( data .approved_funds_agg.to_dict(orient="index") [project['idSegmento']] ) mean, std = info.values() outlier = gaussian_outlier.is_outlier(project['VlTotalAprovado'], mean, std) maximum_expected_funds = gaussian_outlier.maximum_expected_value(mean, std) return { 'is_outlier': outlier, 'total_approved_funds': project['VlTotalAprovado'], 'maximum_expected_funds': maximum_expected_funds }
python
def approved_funds(pronac, dt): """ Verifica se o valor total de um projeto é um outlier em relação aos projetos do mesmo seguimento cultural Dataframes: planilha_orcamentaria """ funds_df = data.approved_funds_by_projects project = ( funds_df .loc[funds_df['PRONAC'] == pronac] ) project = project.to_dict('records')[0] info = ( data .approved_funds_agg.to_dict(orient="index") [project['idSegmento']] ) mean, std = info.values() outlier = gaussian_outlier.is_outlier(project['VlTotalAprovado'], mean, std) maximum_expected_funds = gaussian_outlier.maximum_expected_value(mean, std) return { 'is_outlier': outlier, 'total_approved_funds': project['VlTotalAprovado'], 'maximum_expected_funds': maximum_expected_funds }
Verifica se o valor total de um projeto é um outlier em relação aos projetos do mesmo seguimento cultural Dataframes: planilha_orcamentaria
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/approved_funds.py#L28-L58
lappis-unb/salic-ml
src/salicml_api/analysis/api.py
complexidade
def complexidade(obj): """ Returns a value that indicates project health, currently FinancialIndicator is used as this value, but it can be a result of calculation with other indicators in future """ indicators = obj.indicator_set.all() if not indicators: value = 0.0 else: value = indicators.first().value return value
python
def complexidade(obj): """ Returns a value that indicates project health, currently FinancialIndicator is used as this value, but it can be a result of calculation with other indicators in future """ indicators = obj.indicator_set.all() if not indicators: value = 0.0 else: value = indicators.first().value return value
Returns a value that indicates project health, currently FinancialIndicator is used as this value, but it can be a result of calculation with other indicators in future
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml_api/analysis/api.py#L7-L18
lappis-unb/salic-ml
src/salicml_api/analysis/api.py
details
def details(project): """ Project detail endpoint, Returns project pronac, name, and indicators with details """ indicators = project.indicator_set.all() indicators_detail = [(indicator_details(i) for i in indicators)][0] if not indicators: indicators_detail = [ {'FinancialIndicator': {'valor': 0.0, 'metrics': default_metrics, }, }] indicators_detail = convert_list_into_dict(indicators_detail) return {'pronac': project.pronac, 'nome': project.nome, 'indicadores': indicators_detail, }
python
def details(project): """ Project detail endpoint, Returns project pronac, name, and indicators with details """ indicators = project.indicator_set.all() indicators_detail = [(indicator_details(i) for i in indicators)][0] if not indicators: indicators_detail = [ {'FinancialIndicator': {'valor': 0.0, 'metrics': default_metrics, }, }] indicators_detail = convert_list_into_dict(indicators_detail) return {'pronac': project.pronac, 'nome': project.nome, 'indicadores': indicators_detail, }
Project detail endpoint, Returns project pronac, name, and indicators with details
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml_api/analysis/api.py#L38-L57
lappis-unb/salic-ml
src/salicml_api/analysis/api.py
indicator_details
def indicator_details(indicator): """ Return a dictionary with all metrics in FinancialIndicator, if there aren't values for that Indicator, it is filled with default values """ metrics = format_metrics_json(indicator) metrics_list = set(indicator.metrics .filter(name__in=metrics_name_map.keys()) .values_list('name', flat=True)) null_metrics = default_metrics for keys in metrics_list: null_metrics.pop(metrics_name_map[keys], None) metrics.update(null_metrics) return {type(indicator).__name__: { 'valor': indicator.value, 'metricas': metrics, }, }
python
def indicator_details(indicator): """ Return a dictionary with all metrics in FinancialIndicator, if there aren't values for that Indicator, it is filled with default values """ metrics = format_metrics_json(indicator) metrics_list = set(indicator.metrics .filter(name__in=metrics_name_map.keys()) .values_list('name', flat=True)) null_metrics = default_metrics for keys in metrics_list: null_metrics.pop(metrics_name_map[keys], None) metrics.update(null_metrics) return {type(indicator).__name__: { 'valor': indicator.value, 'metricas': metrics, }, }
Return a dictionary with all metrics in FinancialIndicator, if there aren't values for that Indicator, it is filled with default values
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml_api/analysis/api.py#L60-L79
lappis-unb/salic-ml
src/salicml/data/query.py
Metrics.get_metric
def get_metric(self, pronac, metric): """ Get metric for the project with the given pronac number. Usage: >>> metrics.get_metric(pronac_id, 'finance.approved_funds') """ assert isinstance(metric, str) assert '.' in metric, 'metric must declare a namespace' try: func = self._metrics[metric] return func(pronac, self._data) except KeyError: raise InvalidMetricError('metric does not exist')
python
def get_metric(self, pronac, metric): """ Get metric for the project with the given pronac number. Usage: >>> metrics.get_metric(pronac_id, 'finance.approved_funds') """ assert isinstance(metric, str) assert '.' in metric, 'metric must declare a namespace' try: func = self._metrics[metric] return func(pronac, self._data) except KeyError: raise InvalidMetricError('metric does not exist')
Get metric for the project with the given pronac number. Usage: >>> metrics.get_metric(pronac_id, 'finance.approved_funds')
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/data/query.py#L75-L90
lappis-unb/salic-ml
src/salicml/data/query.py
Metrics.register
def register(self, category): """ Usage: @metrics.register('finance') def approved_funds(pronac, data): return metric_from_data_and_pronac_number(data, pronac) """ def decorator(func): name = func.__name__ key = f'{category}.{name}' self._metrics[key] = func return func return decorator
python
def register(self, category): """ Usage: @metrics.register('finance') def approved_funds(pronac, data): return metric_from_data_and_pronac_number(data, pronac) """ def decorator(func): name = func.__name__ key = f'{category}.{name}' self._metrics[key] = func return func return decorator
Usage: @metrics.register('finance') def approved_funds(pronac, data): return metric_from_data_and_pronac_number(data, pronac)
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/data/query.py#L100-L112
lappis-unb/salic-ml
src/salicml_api/analysis/models/utils.py
execute_project_models_sql_scripts
def execute_project_models_sql_scripts(force_update=False): """ Used to get project information from MinC database and convert to this application Project models. Uses bulk_create if database is clean """ # TODO: Remove except and use ignore_conflicts # on bulk_create when django 2.2. is released with open(MODEL_FILE, "r") as file_content: query = file_content.read() db = db_connector() query_result = db.execute_pandas_sql_query(query) db.close() try: projects = Project.objects.bulk_create( (Project(**vals) for vals in query_result.to_dict("records")), # ignore_conflicts=True available on django 2.2. ) indicators = [FinancialIndicator(project=p) for p in projects] FinancialIndicator.objects.bulk_create(indicators) except IntegrityError: # happens when there are duplicated projects LOG("Projects bulk_create failed, creating one by one...") with transaction.atomic(): if force_update: for item in query_result.to_dict("records"): p, _ = Project.objects.update_or_create(**item) FinancialIndicator.objects.update_or_create(project=p) else: for item in query_result.to_dict("records"): p, _ = Project.objects.get_or_create(**item) FinancialIndicator.objects.update_or_create(project=p)
python
def execute_project_models_sql_scripts(force_update=False): """ Used to get project information from MinC database and convert to this application Project models. Uses bulk_create if database is clean """ # TODO: Remove except and use ignore_conflicts # on bulk_create when django 2.2. is released with open(MODEL_FILE, "r") as file_content: query = file_content.read() db = db_connector() query_result = db.execute_pandas_sql_query(query) db.close() try: projects = Project.objects.bulk_create( (Project(**vals) for vals in query_result.to_dict("records")), # ignore_conflicts=True available on django 2.2. ) indicators = [FinancialIndicator(project=p) for p in projects] FinancialIndicator.objects.bulk_create(indicators) except IntegrityError: # happens when there are duplicated projects LOG("Projects bulk_create failed, creating one by one...") with transaction.atomic(): if force_update: for item in query_result.to_dict("records"): p, _ = Project.objects.update_or_create(**item) FinancialIndicator.objects.update_or_create(project=p) else: for item in query_result.to_dict("records"): p, _ = Project.objects.get_or_create(**item) FinancialIndicator.objects.update_or_create(project=p)
Used to get project information from MinC database and convert to this application Project models. Uses bulk_create if database is clean
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml_api/analysis/models/utils.py#L20-L52
lappis-unb/salic-ml
src/salicml_api/analysis/models/utils.py
create_finance_metrics
def create_finance_metrics(metrics: list, pronacs: list): """ Creates metrics, creating an Indicator if it doesn't already exists Metrics are created for projects that are in pronacs and saved in database. args: metrics: list of names of metrics that will be calculated pronacs: pronacs in dataset that is used to calculate those metrics """ missing = missing_metrics(metrics, pronacs) print(f"There are {len(missing)} missing metrics!") processors = mp.cpu_count() print(f"Using {processors} processors to calculate metrics!") indicators_qs = FinancialIndicator.objects.filter( project_id__in=[p for p, _ in missing] ) indicators = {i.project_id: i for i in indicators_qs} pool = mp.Pool(processors) results = [ pool.apply_async(create_metric, args=(indicators, metric_name, pronac)) for pronac, metric_name in missing ] calculated_metrics = [p.get() for p in results] if calculated_metrics: Metric.objects.bulk_create(calculated_metrics) print("Bulk completed") for indicator in indicators.values(): indicator.fetch_weighted_complexity() print("Finished update indicators!") pool.close() print("Finished metrics calculation!")
python
def create_finance_metrics(metrics: list, pronacs: list): """ Creates metrics, creating an Indicator if it doesn't already exists Metrics are created for projects that are in pronacs and saved in database. args: metrics: list of names of metrics that will be calculated pronacs: pronacs in dataset that is used to calculate those metrics """ missing = missing_metrics(metrics, pronacs) print(f"There are {len(missing)} missing metrics!") processors = mp.cpu_count() print(f"Using {processors} processors to calculate metrics!") indicators_qs = FinancialIndicator.objects.filter( project_id__in=[p for p, _ in missing] ) indicators = {i.project_id: i for i in indicators_qs} pool = mp.Pool(processors) results = [ pool.apply_async(create_metric, args=(indicators, metric_name, pronac)) for pronac, metric_name in missing ] calculated_metrics = [p.get() for p in results] if calculated_metrics: Metric.objects.bulk_create(calculated_metrics) print("Bulk completed") for indicator in indicators.values(): indicator.fetch_weighted_complexity() print("Finished update indicators!") pool.close() print("Finished metrics calculation!")
Creates metrics, creating an Indicator if it doesn't already exists Metrics are created for projects that are in pronacs and saved in database. args: metrics: list of names of metrics that will be calculated pronacs: pronacs in dataset that is used to calculate those metrics
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml_api/analysis/models/utils.py#L55-L93
lappis-unb/salic-ml
src/salicml/metrics/finance/total_receipts.py
total_receipts
def total_receipts(pronac, dt): """ This metric calculates the project total of receipts and compare it to projects in the same segment output: is_outlier: True if projects receipts is not compatible to others projects in the same segment total_receipts: absolute number of receipts maximum_expected_in_segment: maximum receipts expected in segment """ dataframe = data.planilha_comprovacao project = dataframe.loc[dataframe['PRONAC'] == pronac] segment_id = project.iloc[0]["idSegmento"] segments_cache = data.segment_projects_agg segments_cache = segments_cache.to_dict(orient="index") mean = segments_cache[segment_id]["mean"] std = segments_cache[segment_id]["<lambda>"] total_receipts = project.shape[0] is_outlier = gaussian_outlier.is_outlier(total_receipts, mean, std) maximum_expected = gaussian_outlier.maximum_expected_value(mean, std) return { "is_outlier": is_outlier, "valor": total_receipts, "maximo_esperado": maximum_expected, "minimo_esperado": 0, }
python
def total_receipts(pronac, dt): """ This metric calculates the project total of receipts and compare it to projects in the same segment output: is_outlier: True if projects receipts is not compatible to others projects in the same segment total_receipts: absolute number of receipts maximum_expected_in_segment: maximum receipts expected in segment """ dataframe = data.planilha_comprovacao project = dataframe.loc[dataframe['PRONAC'] == pronac] segment_id = project.iloc[0]["idSegmento"] segments_cache = data.segment_projects_agg segments_cache = segments_cache.to_dict(orient="index") mean = segments_cache[segment_id]["mean"] std = segments_cache[segment_id]["<lambda>"] total_receipts = project.shape[0] is_outlier = gaussian_outlier.is_outlier(total_receipts, mean, std) maximum_expected = gaussian_outlier.maximum_expected_value(mean, std) return { "is_outlier": is_outlier, "valor": total_receipts, "maximo_esperado": maximum_expected, "minimo_esperado": 0, }
This metric calculates the project total of receipts and compare it to projects in the same segment output: is_outlier: True if projects receipts is not compatible to others projects in the same segment total_receipts: absolute number of receipts maximum_expected_in_segment: maximum receipts expected in segment
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/total_receipts.py#L9-L36
lappis-unb/salic-ml
src/salicml_api/analysis/preload_data.py
load_project_metrics
def load_project_metrics(): """ Create project metrics for financial indicator Updates them if already exists """ all_metrics = FinancialIndicator.METRICS for key in all_metrics: df = getattr(data, key) pronac = 'PRONAC' if key == 'planilha_captacao': pronac = 'Pronac' pronacs = df[pronac].unique().tolist() create_finance_metrics(all_metrics[key], pronacs)
python
def load_project_metrics(): """ Create project metrics for financial indicator Updates them if already exists """ all_metrics = FinancialIndicator.METRICS for key in all_metrics: df = getattr(data, key) pronac = 'PRONAC' if key == 'planilha_captacao': pronac = 'Pronac' pronacs = df[pronac].unique().tolist() create_finance_metrics(all_metrics[key], pronacs)
Create project metrics for financial indicator Updates them if already exists
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml_api/analysis/preload_data.py#L10-L22
lappis-unb/salic-ml
src/salicml/metrics/finance/new_providers.py
new_providers
def new_providers(pronac, dt): """ Return the percentage of providers of a project that are new to the providers database. """ info = data.providers_info df = info[info['PRONAC'] == pronac] providers_count = data.providers_count.to_dict()[0] new_providers = [] segment_id = None for _, row in df.iterrows(): cnpj = row['nrCNPJCPF'] cnpj_count = providers_count.get(cnpj, 0) segment_id = row['idSegmento'] if cnpj_count <= 1: item_id = row['idPlanilhaAprovacao'] item_name = row['Item'] provider_name = row['nmFornecedor'] new_provider = { 'nome': provider_name, 'cnpj': cnpj, 'itens': { item_id: { 'nome': item_name, 'tem_comprovante': True } } } new_providers.append(new_provider) providers_amount = len(df['nrCNPJCPF'].unique()) new_providers_amount = len(new_providers) new_providers_percentage = new_providers_amount / providers_amount averages = data.average_percentage_of_new_providers.to_dict() segments_average = averages['segments_average_percentage'] all_projects_average = list(averages['all_projects_average'].values())[0] if new_providers: new_providers.sort(key=lambda provider: provider['nome']) return { 'lista_de_novos_fornecedores': new_providers, 'valor': new_providers_amount, 'new_providers_percentage': new_providers_percentage, 'is_outlier': new_providers_percentage > segments_average[segment_id], 'segment_average_percentage': segments_average[segment_id], 'all_projects_average_percentage': all_projects_average, }
python
def new_providers(pronac, dt): """ Return the percentage of providers of a project that are new to the providers database. """ info = data.providers_info df = info[info['PRONAC'] == pronac] providers_count = data.providers_count.to_dict()[0] new_providers = [] segment_id = None for _, row in df.iterrows(): cnpj = row['nrCNPJCPF'] cnpj_count = providers_count.get(cnpj, 0) segment_id = row['idSegmento'] if cnpj_count <= 1: item_id = row['idPlanilhaAprovacao'] item_name = row['Item'] provider_name = row['nmFornecedor'] new_provider = { 'nome': provider_name, 'cnpj': cnpj, 'itens': { item_id: { 'nome': item_name, 'tem_comprovante': True } } } new_providers.append(new_provider) providers_amount = len(df['nrCNPJCPF'].unique()) new_providers_amount = len(new_providers) new_providers_percentage = new_providers_amount / providers_amount averages = data.average_percentage_of_new_providers.to_dict() segments_average = averages['segments_average_percentage'] all_projects_average = list(averages['all_projects_average'].values())[0] if new_providers: new_providers.sort(key=lambda provider: provider['nome']) return { 'lista_de_novos_fornecedores': new_providers, 'valor': new_providers_amount, 'new_providers_percentage': new_providers_percentage, 'is_outlier': new_providers_percentage > segments_average[segment_id], 'segment_average_percentage': segments_average[segment_id], 'all_projects_average_percentage': all_projects_average, }
Return the percentage of providers of a project that are new to the providers database.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/new_providers.py#L9-L62
lappis-unb/salic-ml
src/salicml/metrics/finance/new_providers.py
average_percentage_of_new_providers
def average_percentage_of_new_providers(providers_info, providers_count): """ Return the average percentage of new providers per segment and the average percentage of all projects. """ segments_percentages = {} all_projects_percentages = [] providers_count = providers_count.to_dict()[0] for _, items in providers_info.groupby('PRONAC'): cnpj_array = items['nrCNPJCPF'].unique() new_providers = 0 for cnpj in cnpj_array: cnpj_count = providers_count.get(cnpj, 0) if cnpj_count <= 1: new_providers += 1 segment_id = items.iloc[0]['idSegmento'] new_providers_percent = new_providers / cnpj_array.size segments_percentages.setdefault(segment_id, []) segments_percentages[segment_id].append(new_providers_percent) all_projects_percentages.append(new_providers_percent) segments_average_percentage = {} for segment_id, percentages in segments_percentages.items(): mean = np.mean(percentages) segments_average_percentage[segment_id] = mean return pd.DataFrame.from_dict({ 'segments_average_percentage': segments_average_percentage, 'all_projects_average': np.mean(all_projects_percentages) })
python
def average_percentage_of_new_providers(providers_info, providers_count): """ Return the average percentage of new providers per segment and the average percentage of all projects. """ segments_percentages = {} all_projects_percentages = [] providers_count = providers_count.to_dict()[0] for _, items in providers_info.groupby('PRONAC'): cnpj_array = items['nrCNPJCPF'].unique() new_providers = 0 for cnpj in cnpj_array: cnpj_count = providers_count.get(cnpj, 0) if cnpj_count <= 1: new_providers += 1 segment_id = items.iloc[0]['idSegmento'] new_providers_percent = new_providers / cnpj_array.size segments_percentages.setdefault(segment_id, []) segments_percentages[segment_id].append(new_providers_percent) all_projects_percentages.append(new_providers_percent) segments_average_percentage = {} for segment_id, percentages in segments_percentages.items(): mean = np.mean(percentages) segments_average_percentage[segment_id] = mean return pd.DataFrame.from_dict({ 'segments_average_percentage': segments_average_percentage, 'all_projects_average': np.mean(all_projects_percentages) })
Return the average percentage of new providers per segment and the average percentage of all projects.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/new_providers.py#L66-L97
lappis-unb/salic-ml
src/salicml/metrics/finance/new_providers.py
providers_count
def providers_count(df): """ Returns total occurrences of each provider in the database. """ providers_count = {} cnpj_array = df.values for a in cnpj_array: cnpj = a[0] occurrences = providers_count.get(cnpj, 0) providers_count[cnpj] = occurrences + 1 return pd.DataFrame.from_dict(providers_count, orient='index')
python
def providers_count(df): """ Returns total occurrences of each provider in the database. """ providers_count = {} cnpj_array = df.values for a in cnpj_array: cnpj = a[0] occurrences = providers_count.get(cnpj, 0) providers_count[cnpj] = occurrences + 1 return pd.DataFrame.from_dict(providers_count, orient='index')
Returns total occurrences of each provider in the database.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/new_providers.py#L101-L114
lappis-unb/salic-ml
src/salicml/metrics/finance/new_providers.py
all_providers_cnpj
def all_providers_cnpj(df): """ Return CPF/CNPJ of all providers in database. """ cnpj_list = [] for _, items in df.groupby('PRONAC'): unique_cnpjs = items['nrCNPJCPF'].unique() cnpj_list += list(unique_cnpjs) return pd.DataFrame(cnpj_list)
python
def all_providers_cnpj(df): """ Return CPF/CNPJ of all providers in database. """ cnpj_list = [] for _, items in df.groupby('PRONAC'): unique_cnpjs = items['nrCNPJCPF'].unique() cnpj_list += list(unique_cnpjs) return pd.DataFrame(cnpj_list)
Return CPF/CNPJ of all providers in database.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/new_providers.py#L132-L143
lappis-unb/salic-ml
src/salicml/metrics/finance/new_providers.py
get_providers_info
def get_providers_info(pronac): """ Return all info about providers of a project with the given pronac. """ df = data.providers_info grouped = df.groupby('PRONAC') return grouped.get_group(pronac)
python
def get_providers_info(pronac): """ Return all info about providers of a project with the given pronac. """ df = data.providers_info grouped = df.groupby('PRONAC') return grouped.get_group(pronac)
Return all info about providers of a project with the given pronac.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/new_providers.py#L146-L154
lappis-unb/salic-ml
src/salicml/metrics/base.py
get_info
def get_info(df, group, info=['mean', 'std']): """ Aggregate mean and std with the given group. """ agg = df.groupby(group).agg(info) agg.columns = agg.columns.droplevel(0) return agg
python
def get_info(df, group, info=['mean', 'std']): """ Aggregate mean and std with the given group. """ agg = df.groupby(group).agg(info) agg.columns = agg.columns.droplevel(0) return agg
Aggregate mean and std with the given group.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/base.py#L5-L11
lappis-unb/salic-ml
src/salicml/metrics/base.py
get_salic_url
def get_salic_url(item, prefix, df_values=None): """ Mount a salic url for the given item. """ url_keys = { 'pronac': 'idPronac', 'uf': 'uf', 'product': 'produto', 'county': 'idmunicipio', 'item_id': 'idPlanilhaItem', 'stage': 'etapa', } if df_values: values = [item[v] for v in df_values] url_values = dict( zip(url_keys.keys(), values) ) else: url_values = { "pronac": item["idPronac"], "uf": item["UfItem"], "product": item["idProduto"], "county": item["cdCidade"], "item_id": item["idPlanilhaItens"], "stage": item["cdEtapa"], } item_data = [(value, url_values[key]) for key, value in url_keys.items()] url = prefix for k, v in item_data: url += f'/{str(k)}/{str(v)}' return url
python
def get_salic_url(item, prefix, df_values=None): """ Mount a salic url for the given item. """ url_keys = { 'pronac': 'idPronac', 'uf': 'uf', 'product': 'produto', 'county': 'idmunicipio', 'item_id': 'idPlanilhaItem', 'stage': 'etapa', } if df_values: values = [item[v] for v in df_values] url_values = dict( zip(url_keys.keys(), values) ) else: url_values = { "pronac": item["idPronac"], "uf": item["UfItem"], "product": item["idProduto"], "county": item["cdCidade"], "item_id": item["idPlanilhaItens"], "stage": item["cdEtapa"], } item_data = [(value, url_values[key]) for key, value in url_keys.items()] url = prefix for k, v in item_data: url += f'/{str(k)}/{str(v)}' return url
Mount a salic url for the given item.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/base.py#L26-L59
lappis-unb/salic-ml
src/salicml/metrics/base.py
get_cpf_cnpj_by_pronac
def get_cpf_cnpj_by_pronac(pronac): """ Return the CNPF/CNPJ of the proponent of the project with the given pronac. """ df = data.planilha_projetos cpf_cnpj = None row_df = df[df['PRONAC'].astype(str) == str(pronac)] if not row_df.empty: cpf_cnpj = row_df.iloc[0]['CgcCpf'] return str(cpf_cnpj)
python
def get_cpf_cnpj_by_pronac(pronac): """ Return the CNPF/CNPJ of the proponent of the project with the given pronac. """ df = data.planilha_projetos cpf_cnpj = None row_df = df[df['PRONAC'].astype(str) == str(pronac)] if not row_df.empty: cpf_cnpj = row_df.iloc[0]['CgcCpf'] return str(cpf_cnpj)
Return the CNPF/CNPJ of the proponent of the project with the given pronac.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/base.py#L62-L74
lappis-unb/salic-ml
src/salicml/metrics/base.py
has_receipt
def has_receipt(item): """ Verify if a item has a receipt. """ pronac_id = str(item['idPronac']) item_id = str(item["idPlanilhaItens"]) combined_id = f'{pronac_id}/{item_id}' return combined_id in data.receipt.index
python
def has_receipt(item): """ Verify if a item has a receipt. """ pronac_id = str(item['idPronac']) item_id = str(item["idPlanilhaItens"]) combined_id = f'{pronac_id}/{item_id}' return combined_id in data.receipt.index
Verify if a item has a receipt.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/base.py#L77-L86
lappis-unb/salic-ml
src/salicml/metrics/base.py
get_segment_projects
def get_segment_projects(segment_id): """ Returns all projects from a segment. """ df = data.all_items return ( df[df['idSegmento'] == str(segment_id)] .drop_duplicates(["PRONAC"]) .values )
python
def get_segment_projects(segment_id): """ Returns all projects from a segment. """ df = data.all_items return ( df[df['idSegmento'] == str(segment_id)] .drop_duplicates(["PRONAC"]) .values )
Returns all projects from a segment.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/base.py#L90-L99
lappis-unb/salic-ml
src/salicml/metrics/base.py
receipt
def receipt(df): """ Return a dataframe to verify if a item has a receipt. """ mutated_df = df[['IdPRONAC', 'idPlanilhaItem']].astype(str) mutated_df['pronac_planilha_itens'] = ( f"{mutated_df['IdPRONAC']}/{mutated_df['idPlanilhaItem']}" ) return ( mutated_df .set_index(['pronac_planilha_itens']) )
python
def receipt(df): """ Return a dataframe to verify if a item has a receipt. """ mutated_df = df[['IdPRONAC', 'idPlanilhaItem']].astype(str) mutated_df['pronac_planilha_itens'] = ( f"{mutated_df['IdPRONAC']}/{mutated_df['idPlanilhaItem']}" ) return ( mutated_df .set_index(['pronac_planilha_itens']) )
Return a dataframe to verify if a item has a receipt.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/base.py#L103-L115
lappis-unb/salic-ml
tasks.py
update_data
def update_data(ctx, models=True, pickles=False, f=False): """ Updates local django db projects and pickle files using salic database from MinC Pickles are saved in /data/raw/ from sql queries in /data/scripts/ Models are created from /data/scripts/models/ """ if pickles: save_sql_to_files(f) if models: if f: manage(ctx, 'create_models_from_sql --force True', env={}) else: manage(ctx, 'create_models_from_sql', env={})
python
def update_data(ctx, models=True, pickles=False, f=False): """ Updates local django db projects and pickle files using salic database from MinC Pickles are saved in /data/raw/ from sql queries in /data/scripts/ Models are created from /data/scripts/models/ """ if pickles: save_sql_to_files(f) if models: if f: manage(ctx, 'create_models_from_sql --force True', env={}) else: manage(ctx, 'create_models_from_sql', env={})
Updates local django db projects and pickle files using salic database from MinC Pickles are saved in /data/raw/ from sql queries in /data/scripts/ Models are created from /data/scripts/models/
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/tasks.py#L72-L85
lappis-unb/salic-ml
tasks.py
update_models
def update_models(ctx, f=False): """ Updates local django db projects models using salic database from MinC """ if f: manage(ctx, 'create_models_from_sql --force True', env={}) else: manage(ctx, 'create_models_from_sql', env={})
python
def update_models(ctx, f=False): """ Updates local django db projects models using salic database from MinC """ if f: manage(ctx, 'create_models_from_sql --force True', env={}) else: manage(ctx, 'create_models_from_sql', env={})
Updates local django db projects models using salic database from MinC
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/tasks.py#L89-L97
lappis-unb/salic-ml
src/salicml_api/analysis/models/financial.py
FinancialIndicatorManager.create_indicator
def create_indicator(self, project, is_valid, metrics_list): """ Creates FinancialIndicator object for a project, calculating metrics and indicator value """ project = Project.objects.get(pronac=project) indicator, _ = (FinancialIndicator .objects.update_or_create(project=project)) indicator.is_valid = is_valid if indicator.is_valid: p_metrics = metrics_calc.get_project(project.pronac) for metric_name in metrics_list: print("calculando a metrica ", metric_name) x = getattr(p_metrics.finance, metric_name) print("do projeto: ", project) Metric.objects.create_metric(metric_name, x, indicator) indicator.fetch_weighted_complexity() return indicator
python
def create_indicator(self, project, is_valid, metrics_list): """ Creates FinancialIndicator object for a project, calculating metrics and indicator value """ project = Project.objects.get(pronac=project) indicator, _ = (FinancialIndicator .objects.update_or_create(project=project)) indicator.is_valid = is_valid if indicator.is_valid: p_metrics = metrics_calc.get_project(project.pronac) for metric_name in metrics_list: print("calculando a metrica ", metric_name) x = getattr(p_metrics.finance, metric_name) print("do projeto: ", project) Metric.objects.create_metric(metric_name, x, indicator) indicator.fetch_weighted_complexity() return indicator
Creates FinancialIndicator object for a project, calculating metrics and indicator value
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml_api/analysis/models/financial.py#L11-L28
lappis-unb/salic-ml
src/salicml/data/db_operations.py
save_sql_to_files
def save_sql_to_files(overwrite=False): """ Executes every .sql files in /data/scripts/ using salic db vpn and then saves pickle files into /data/raw/ """ ext_size = len(SQL_EXTENSION) path = DATA_PATH / 'scripts' save_dir = DATA_PATH / "raw" for file in os.listdir(path): if file.endswith(SQL_EXTENSION): file_path = os.path.join(save_dir, file[:-ext_size] + '.' + FILE_EXTENSION) if not os.path.isfile(file_path) or overwrite: query_result = make_query(path / file) save_dataframe_as_pickle(query_result, file_path) else: print(("file {} already exists, if you would like to update" " it, use -f flag\n").format(file_path))
python
def save_sql_to_files(overwrite=False): """ Executes every .sql files in /data/scripts/ using salic db vpn and then saves pickle files into /data/raw/ """ ext_size = len(SQL_EXTENSION) path = DATA_PATH / 'scripts' save_dir = DATA_PATH / "raw" for file in os.listdir(path): if file.endswith(SQL_EXTENSION): file_path = os.path.join(save_dir, file[:-ext_size] + '.' + FILE_EXTENSION) if not os.path.isfile(file_path) or overwrite: query_result = make_query(path / file) save_dataframe_as_pickle(query_result, file_path) else: print(("file {} already exists, if you would like to update" " it, use -f flag\n").format(file_path))
Executes every .sql files in /data/scripts/ using salic db vpn and then saves pickle files into /data/raw/
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/data/db_operations.py#L31-L49
lappis-unb/salic-ml
src/salicml_api/analysis/models/base.py
Indicator.fetch_weighted_complexity
def fetch_weighted_complexity(self, recalculate_metrics=False): """ Calculates indicator value according to metrics weights Uses metrics in database args: recalculate_metrics: If true metrics values are updated before using weights """ # TODO: implment metrics recalculation max_total = sum( [self.metrics_weights[metric_name] for metric_name in self.metrics_weights] ) total = 0 if recalculate_metrics: self.calculate_indicator_metrics() for metric in self.metrics.all(): if metric.name in self.metrics_weights and metric.is_outlier: total += self.metrics_weights[metric.name] value = total / max_total final_value = "{:.1f}".format(value * 10) if final_value[-1] == "0": final_value = "{:.0f}".format(value * 10) final_value = int(final_value) else: final_value = float(final_value) self.value = float(final_value) self.is_valid = True self.updated_at = datetime.datetime.now() self.save() return final_value
python
def fetch_weighted_complexity(self, recalculate_metrics=False): """ Calculates indicator value according to metrics weights Uses metrics in database args: recalculate_metrics: If true metrics values are updated before using weights """ # TODO: implment metrics recalculation max_total = sum( [self.metrics_weights[metric_name] for metric_name in self.metrics_weights] ) total = 0 if recalculate_metrics: self.calculate_indicator_metrics() for metric in self.metrics.all(): if metric.name in self.metrics_weights and metric.is_outlier: total += self.metrics_weights[metric.name] value = total / max_total final_value = "{:.1f}".format(value * 10) if final_value[-1] == "0": final_value = "{:.0f}".format(value * 10) final_value = int(final_value) else: final_value = float(final_value) self.value = float(final_value) self.is_valid = True self.updated_at = datetime.datetime.now() self.save() return final_value
Calculates indicator value according to metrics weights Uses metrics in database args: recalculate_metrics: If true metrics values are updated before using weights
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml_api/analysis/models/base.py#L27-L59
lappis-unb/salic-ml
src/salicml/metrics/finance/item_prices.py
item_prices
def item_prices(pronac, data): """ Verify if a project is an outlier compared to the other projects in his segment, based on the price of bought items. """ threshold = 0.1 outlier_info = get_outliers_percentage(pronac) outlier_info['is_outlier'] = outlier_info['percentage'] > threshold outlier_info['maximum_expected'] = threshold * outlier_info['total_items'] return outlier_info
python
def item_prices(pronac, data): """ Verify if a project is an outlier compared to the other projects in his segment, based on the price of bought items. """ threshold = 0.1 outlier_info = get_outliers_percentage(pronac) outlier_info['is_outlier'] = outlier_info['percentage'] > threshold outlier_info['maximum_expected'] = threshold * outlier_info['total_items'] return outlier_info
Verify if a project is an outlier compared to the other projects in his segment, based on the price of bought items.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/item_prices.py#L12-L24
lappis-unb/salic-ml
src/salicml/metrics/finance/item_prices.py
is_outlier
def is_outlier(df, item_id, segment_id, price): """ Verify if a item is an outlier compared to the other occurrences of the same item, based on his price. Args: item_id: idPlanilhaItens segment_id: idSegmento price: VlUnitarioAprovado """ if (segment_id, item_id) not in df.index: return False mean = df.loc[(segment_id, item_id)]['mean'] std = df.loc[(segment_id, item_id)]['std'] return gaussian_outlier.is_outlier( x=price, mean=mean, standard_deviation=std )
python
def is_outlier(df, item_id, segment_id, price): """ Verify if a item is an outlier compared to the other occurrences of the same item, based on his price. Args: item_id: idPlanilhaItens segment_id: idSegmento price: VlUnitarioAprovado """ if (segment_id, item_id) not in df.index: return False mean = df.loc[(segment_id, item_id)]['mean'] std = df.loc[(segment_id, item_id)]['std'] return gaussian_outlier.is_outlier( x=price, mean=mean, standard_deviation=std )
Verify if a item is an outlier compared to the other occurrences of the same item, based on his price. Args: item_id: idPlanilhaItens segment_id: idSegmento price: VlUnitarioAprovado
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/item_prices.py#L27-L46
lappis-unb/salic-ml
src/salicml/metrics/finance/item_prices.py
aggregated_relevant_items
def aggregated_relevant_items(raw_df): """ Aggragation for calculate mean and std. """ df = ( raw_df[['idSegmento', 'idPlanilhaItens', 'VlUnitarioAprovado']] .groupby(by=['idSegmento', 'idPlanilhaItens']) .agg([np.mean, lambda x: np.std(x, ddof=0)]) ) df.columns = df.columns.droplevel(0) return ( df .rename(columns={'<lambda>': 'std'}) )
python
def aggregated_relevant_items(raw_df): """ Aggragation for calculate mean and std. """ df = ( raw_df[['idSegmento', 'idPlanilhaItens', 'VlUnitarioAprovado']] .groupby(by=['idSegmento', 'idPlanilhaItens']) .agg([np.mean, lambda x: np.std(x, ddof=0)]) ) df.columns = df.columns.droplevel(0) return ( df .rename(columns={'<lambda>': 'std'}) )
Aggragation for calculate mean and std.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/item_prices.py#L50-L63
lappis-unb/salic-ml
src/salicml/metrics/finance/item_prices.py
relevant_items
def relevant_items(df): """ Dataframe with items used by cultural projects, filtered by date and price. """ start_date = datetime(2013, 1, 1) df['DataProjeto'] = pd.to_datetime(df['DataProjeto']) # get only projects newer than start_date # and items with price > 0 df = df[df.DataProjeto >= start_date] df = df[df.VlUnitarioAprovado > 0.0] return df
python
def relevant_items(df): """ Dataframe with items used by cultural projects, filtered by date and price. """ start_date = datetime(2013, 1, 1) df['DataProjeto'] = pd.to_datetime(df['DataProjeto']) # get only projects newer than start_date # and items with price > 0 df = df[df.DataProjeto >= start_date] df = df[df.VlUnitarioAprovado > 0.0] return df
Dataframe with items used by cultural projects, filtered by date and price.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/item_prices.py#L67-L81
lappis-unb/salic-ml
src/salicml/metrics/finance/item_prices.py
items_with_price
def items_with_price(raw_df): """ Dataframe with price as number. """ df = ( raw_df [['PRONAC', 'idPlanilhaAprovacao', 'Item', 'idPlanilhaItens', 'VlUnitarioAprovado', 'idSegmento', 'DataProjeto', 'idPronac', 'UfItem', 'idProduto', 'cdCidade', 'cdEtapa']] ).copy() df['VlUnitarioAprovado'] = df['VlUnitarioAprovado'].apply(pd.to_numeric) return df
python
def items_with_price(raw_df): """ Dataframe with price as number. """ df = ( raw_df [['PRONAC', 'idPlanilhaAprovacao', 'Item', 'idPlanilhaItens', 'VlUnitarioAprovado', 'idSegmento', 'DataProjeto', 'idPronac', 'UfItem', 'idProduto', 'cdCidade', 'cdEtapa']] ).copy() df['VlUnitarioAprovado'] = df['VlUnitarioAprovado'].apply(pd.to_numeric) return df
Dataframe with price as number.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/item_prices.py#L85-L98
lappis-unb/salic-ml
src/salicml/metrics/finance/item_prices.py
get_outliers_percentage
def get_outliers_percentage(pronac): """ Returns the percentage of items of the project that are outliers. """ items = ( data.items_with_price .groupby(['PRONAC']) .get_group(pronac) ) df = data.aggregated_relevant_items outlier_items = {} url_prefix = '/prestacao-contas/analisar/comprovante' for _, item in items.iterrows(): item_id = item['idPlanilhaItens'] price = item['VlUnitarioAprovado'] segment_id = item['idSegmento'] item_name = item['Item'] if is_outlier(df, item_id, segment_id, price): outlier_items[item_id] = { 'name': item_name, 'salic_url': get_salic_url(item, url_prefix), 'has_receipt': has_receipt(item) } total_items = items.shape[0] outliers_amount = len(outlier_items) percentage = outliers_amount / total_items return { 'items': outlier_items, 'valor': outliers_amount, 'total_items': total_items, 'percentage': percentage, 'is_outlier': outliers_amount > 0, }
python
def get_outliers_percentage(pronac): """ Returns the percentage of items of the project that are outliers. """ items = ( data.items_with_price .groupby(['PRONAC']) .get_group(pronac) ) df = data.aggregated_relevant_items outlier_items = {} url_prefix = '/prestacao-contas/analisar/comprovante' for _, item in items.iterrows(): item_id = item['idPlanilhaItens'] price = item['VlUnitarioAprovado'] segment_id = item['idSegmento'] item_name = item['Item'] if is_outlier(df, item_id, segment_id, price): outlier_items[item_id] = { 'name': item_name, 'salic_url': get_salic_url(item, url_prefix), 'has_receipt': has_receipt(item) } total_items = items.shape[0] outliers_amount = len(outlier_items) percentage = outliers_amount / total_items return { 'items': outlier_items, 'valor': outliers_amount, 'total_items': total_items, 'percentage': percentage, 'is_outlier': outliers_amount > 0, }
Returns the percentage of items of the project that are outliers.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/item_prices.py#L101-L141
lappis-unb/salic-ml
src/salicml/metrics/finance/number_of_items.py
number_of_items
def number_of_items(pronac, dt): """ This metric calculates the project number of declared number of items and compare it to projects in the same segment output: is_outlier: True if projects number of items is not compatible to others projects in the same segment valor: absolute number of items maximo_esperado: mean number of items of segment desvio_padrao: standard deviation of number of items in project segment """ df = data.items_by_project project = df.loc[df['PRONAC'] == pronac] seg = project.iloc[0]["idSegmento"] info = data.items_by_project_agg.to_dict(orient="index")[seg] mean, std = info.values() threshold = mean + 1.5 * std project_items_count = project.shape[0] is_outlier = project_items_count > threshold return { 'is_outlier': is_outlier, 'valor': project_items_count, 'maximo_esperado': mean, 'desvio_padrao': std, }
python
def number_of_items(pronac, dt): """ This metric calculates the project number of declared number of items and compare it to projects in the same segment output: is_outlier: True if projects number of items is not compatible to others projects in the same segment valor: absolute number of items maximo_esperado: mean number of items of segment desvio_padrao: standard deviation of number of items in project segment """ df = data.items_by_project project = df.loc[df['PRONAC'] == pronac] seg = project.iloc[0]["idSegmento"] info = data.items_by_project_agg.to_dict(orient="index")[seg] mean, std = info.values() threshold = mean + 1.5 * std project_items_count = project.shape[0] is_outlier = project_items_count > threshold return { 'is_outlier': is_outlier, 'valor': project_items_count, 'maximo_esperado': mean, 'desvio_padrao': std, }
This metric calculates the project number of declared number of items and compare it to projects in the same segment output: is_outlier: True if projects number of items is not compatible to others projects in the same segment valor: absolute number of items maximo_esperado: mean number of items of segment desvio_padrao: standard deviation of number of items in project segment
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/number_of_items.py#L7-L31
lappis-unb/salic-ml
src/salicml/metrics/finance/common_items_ratio.py
common_items
def common_items(df): """ Returns the itens that are common in all the segments, in the format | idSegmento | id planilhaItens |. """ percentage = 0.1 return ( df .groupby(['idSegmento', 'idPlanilhaItens']) .count() .rename(columns={'PRONAC': 'itemOccurrences'}) .sort_values('itemOccurrences', ascending=False) .reset_index(['idSegmento', 'idPlanilhaItens']) .groupby('idSegmento') .apply(lambda x: x[None: max(2, int(len(x) * percentage))]) .reset_index(['idSegmento'], drop=True) .set_index(['idSegmento']) )
python
def common_items(df): """ Returns the itens that are common in all the segments, in the format | idSegmento | id planilhaItens |. """ percentage = 0.1 return ( df .groupby(['idSegmento', 'idPlanilhaItens']) .count() .rename(columns={'PRONAC': 'itemOccurrences'}) .sort_values('itemOccurrences', ascending=False) .reset_index(['idSegmento', 'idPlanilhaItens']) .groupby('idSegmento') .apply(lambda x: x[None: max(2, int(len(x) * percentage))]) .reset_index(['idSegmento'], drop=True) .set_index(['idSegmento']) )
Returns the itens that are common in all the segments, in the format | idSegmento | id planilhaItens |.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L14-L32
lappis-unb/salic-ml
src/salicml/metrics/finance/common_items_ratio.py
common_items_percentage
def common_items_percentage(pronac, seg_common_items): """ Returns the percentage of items in a project that are common in the cultural segment. """ if len(seg_common_items) == 0: return 0 project_items = get_project_items(pronac).values[:, 0] project_items_amount = len(project_items) if project_items_amount == 0: return 1 common_found_items = sum( seg_common_items.isin(project_items)['idPlanilhaItens'] ) return common_found_items / project_items_amount
python
def common_items_percentage(pronac, seg_common_items): """ Returns the percentage of items in a project that are common in the cultural segment. """ if len(seg_common_items) == 0: return 0 project_items = get_project_items(pronac).values[:, 0] project_items_amount = len(project_items) if project_items_amount == 0: return 1 common_found_items = sum( seg_common_items.isin(project_items)['idPlanilhaItens'] ) return common_found_items / project_items_amount
Returns the percentage of items in a project that are common in the cultural segment.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L61-L79
lappis-unb/salic-ml
src/salicml/metrics/finance/common_items_ratio.py
common_items_metrics
def common_items_metrics(all_items, common_items): """ Calculates the percentage of common items for each project in each segment and calculates the mean and std of this percentage for each segment. """ segments = common_items.index.unique() metrics = {} for seg in segments: seg_common_items = segment_common_items(seg) projects = get_segment_projects(seg) metric_values = [] for proj in projects: pronac = proj[0] percentage = common_items_percentage(pronac, seg_common_items) metric_values.append(percentage) metrics[seg] = { 'mean': np.mean(metric_values), 'std': np.std(metric_values) } return pd.DataFrame.from_dict(metrics, orient='index')
python
def common_items_metrics(all_items, common_items): """ Calculates the percentage of common items for each project in each segment and calculates the mean and std of this percentage for each segment. """ segments = common_items.index.unique() metrics = {} for seg in segments: seg_common_items = segment_common_items(seg) projects = get_segment_projects(seg) metric_values = [] for proj in projects: pronac = proj[0] percentage = common_items_percentage(pronac, seg_common_items) metric_values.append(percentage) metrics[seg] = { 'mean': np.mean(metric_values), 'std': np.std(metric_values) } return pd.DataFrame.from_dict(metrics, orient='index')
Calculates the percentage of common items for each project in each segment and calculates the mean and std of this percentage for each segment.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L83-L106
lappis-unb/salic-ml
src/salicml/metrics/finance/common_items_ratio.py
get_project_items
def get_project_items(pronac): """ Returns all items from a project. """ df = data.all_items return ( df[df['PRONAC'] == pronac] .drop(columns=['PRONAC', 'idSegmento']) )
python
def get_project_items(pronac): """ Returns all items from a project. """ df = data.all_items return ( df[df['PRONAC'] == pronac] .drop(columns=['PRONAC', 'idSegmento']) )
Returns all items from a project.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L110-L118
lappis-unb/salic-ml
src/salicml/metrics/finance/common_items_ratio.py
segment_common_items
def segment_common_items(segment_id): """ Returns all the common items in a segment. """ df = data.common_items return ( df .loc[str(segment_id)] .reset_index(drop=1) .drop(columns=["itemOccurrences"]) )
python
def segment_common_items(segment_id): """ Returns all the common items in a segment. """ df = data.common_items return ( df .loc[str(segment_id)] .reset_index(drop=1) .drop(columns=["itemOccurrences"]) )
Returns all the common items in a segment.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L122-L132
lappis-unb/salic-ml
src/salicml/metrics/finance/common_items_ratio.py
get_uncommon_items
def get_uncommon_items(pronac): """ Return all uncommon items of a project (related to segment common items). """ segment_id = get_segment_id(str(pronac)) seg_common_items = ( segment_common_items(segment_id) .set_index('idPlanilhaItens') .index ) project_items = ( get_project_items(pronac) .set_index('idPlanilhaItens') .index ) diff = list(project_items.difference(seg_common_items)) return ( data.distinct_items .loc[diff] .to_dict()['Item'] )
python
def get_uncommon_items(pronac): """ Return all uncommon items of a project (related to segment common items). """ segment_id = get_segment_id(str(pronac)) seg_common_items = ( segment_common_items(segment_id) .set_index('idPlanilhaItens') .index ) project_items = ( get_project_items(pronac) .set_index('idPlanilhaItens') .index ) diff = list(project_items.difference(seg_common_items)) return ( data.distinct_items .loc[diff] .to_dict()['Item'] )
Return all uncommon items of a project (related to segment common items).
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L136-L159
lappis-unb/salic-ml
src/salicml/metrics/finance/common_items_ratio.py
add_info_to_uncommon_items
def add_info_to_uncommon_items(filtered_items, uncommon_items): """ Add extra info to the uncommon items. """ result = uncommon_items url_prefix = '/prestacao-contas/analisar/comprovante' for _, item in filtered_items.iterrows(): item_id = item['idPlanilhaItens'] item_name = uncommon_items[item_id] result[item_id] = { 'name': item_name, 'salic_url': get_salic_url(item, url_prefix), 'has_recepit': has_receipt(item) } return result
python
def add_info_to_uncommon_items(filtered_items, uncommon_items): """ Add extra info to the uncommon items. """ result = uncommon_items url_prefix = '/prestacao-contas/analisar/comprovante' for _, item in filtered_items.iterrows(): item_id = item['idPlanilhaItens'] item_name = uncommon_items[item_id] result[item_id] = { 'name': item_name, 'salic_url': get_salic_url(item, url_prefix), 'has_recepit': has_receipt(item) } return result
Add extra info to the uncommon items.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L188-L206
lappis-unb/salic-ml
src/salicml/metrics/finance/common_items_ratio.py
common_items_ratio
def common_items_ratio(pronac, dt): """ Calculates the common items on projects in a cultural segment, calculates the uncommon items on projects in a cultural segment and verify if a project is an outlier compared to the other projects in his segment. """ segment_id = get_segment_id(str(pronac)) metrics = data.common_items_metrics.to_dict(orient='index')[segment_id] ratio = common_items_percentage(pronac, segment_common_items(segment_id)) # constant that defines the threshold to verify if a project # is an outlier. k = 1.5 threshold = metrics['mean'] - k * metrics['std'] uncommon_items = get_uncommon_items(pronac) pronac_filter = data.all_items['PRONAC'] == pronac uncommon_items_filter = ( data.all_items['idPlanilhaItens'] .isin(uncommon_items) ) items_filter = (pronac_filter & uncommon_items_filter) filtered_items = ( data .all_items[items_filter] .drop_duplicates(subset='idPlanilhaItens') ) uncommon_items = add_info_to_uncommon_items(filtered_items, uncommon_items) return { 'is_outlier': ratio < threshold, 'valor': ratio, 'maximo_esperado': metrics['mean'], 'desvio_padrao': metrics['std'], 'items_incomuns': uncommon_items, 'items_comuns_que_o_projeto_nao_possui': get_common_items_not_present(pronac), }
python
def common_items_ratio(pronac, dt): """ Calculates the common items on projects in a cultural segment, calculates the uncommon items on projects in a cultural segment and verify if a project is an outlier compared to the other projects in his segment. """ segment_id = get_segment_id(str(pronac)) metrics = data.common_items_metrics.to_dict(orient='index')[segment_id] ratio = common_items_percentage(pronac, segment_common_items(segment_id)) # constant that defines the threshold to verify if a project # is an outlier. k = 1.5 threshold = metrics['mean'] - k * metrics['std'] uncommon_items = get_uncommon_items(pronac) pronac_filter = data.all_items['PRONAC'] == pronac uncommon_items_filter = ( data.all_items['idPlanilhaItens'] .isin(uncommon_items) ) items_filter = (pronac_filter & uncommon_items_filter) filtered_items = ( data .all_items[items_filter] .drop_duplicates(subset='idPlanilhaItens') ) uncommon_items = add_info_to_uncommon_items(filtered_items, uncommon_items) return { 'is_outlier': ratio < threshold, 'valor': ratio, 'maximo_esperado': metrics['mean'], 'desvio_padrao': metrics['std'], 'items_incomuns': uncommon_items, 'items_comuns_que_o_projeto_nao_possui': get_common_items_not_present(pronac), }
Calculates the common items on projects in a cultural segment, calculates the uncommon items on projects in a cultural segment and verify if a project is an outlier compared to the other projects in his segment.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/common_items_ratio.py#L210-L249
lappis-unb/salic-ml
src/salicml/metrics/finance/verified_funds.py
verified_funds
def verified_funds(pronac, dt): """ Responsable for detecting anomalies in projects total verified funds. """ dataframe = data.planilha_comprovacao project = dataframe.loc[dataframe['PRONAC'] == pronac] segment_id = project.iloc[0]["idSegmento"] pronac_funds = project[ ["idPlanilhaAprovacao", "PRONAC", "vlComprovacao", "idSegmento"] ] funds_grp = pronac_funds.drop(columns=["idPlanilhaAprovacao"]).groupby( ["PRONAC"] ) project_funds = funds_grp.sum().loc[pronac]["vlComprovacao"] segments_info = data.verified_funds_by_segment_agg.to_dict(orient="index") mean = segments_info[segment_id]["mean"] std = segments_info[segment_id]["std"] is_outlier = gaussian_outlier.is_outlier(project_funds, mean, std) maximum_expected_funds = gaussian_outlier.maximum_expected_value(mean, std) return { "is_outlier": is_outlier, "valor": project_funds, "maximo_esperado": maximum_expected_funds, "minimo_esperado": 0, }
python
def verified_funds(pronac, dt): """ Responsable for detecting anomalies in projects total verified funds. """ dataframe = data.planilha_comprovacao project = dataframe.loc[dataframe['PRONAC'] == pronac] segment_id = project.iloc[0]["idSegmento"] pronac_funds = project[ ["idPlanilhaAprovacao", "PRONAC", "vlComprovacao", "idSegmento"] ] funds_grp = pronac_funds.drop(columns=["idPlanilhaAprovacao"]).groupby( ["PRONAC"] ) project_funds = funds_grp.sum().loc[pronac]["vlComprovacao"] segments_info = data.verified_funds_by_segment_agg.to_dict(orient="index") mean = segments_info[segment_id]["mean"] std = segments_info[segment_id]["std"] is_outlier = gaussian_outlier.is_outlier(project_funds, mean, std) maximum_expected_funds = gaussian_outlier.maximum_expected_value(mean, std) return { "is_outlier": is_outlier, "valor": project_funds, "maximo_esperado": maximum_expected_funds, "minimo_esperado": 0, }
Responsable for detecting anomalies in projects total verified funds.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/verified_funds.py#L9-L34
lappis-unb/salic-ml
src/salicml/metrics/finance/to_verify_funds.py
raised_funds_by_project
def raised_funds_by_project(df): """ Raised funds organized by project. """ df['CaptacaoReal'] = df['CaptacaoReal'].apply( pd.to_numeric ) return ( df[['Pronac', 'CaptacaoReal']] .groupby(['Pronac']) .sum() )
python
def raised_funds_by_project(df): """ Raised funds organized by project. """ df['CaptacaoReal'] = df['CaptacaoReal'].apply( pd.to_numeric ) return ( df[['Pronac', 'CaptacaoReal']] .groupby(['Pronac']) .sum() )
Raised funds organized by project.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/to_verify_funds.py#L8-L19
lappis-unb/salic-ml
src/salicml/metrics/finance/to_verify_funds.py
to_verify_funds
def to_verify_funds(pronac, dt): """ Checks how much money is left for the project to verify, using raised_funds - verified_funds This value can be negative (a project can verify more money than the value approved) """ project_raised_funds = data.raised_funds_by_project.loc[pronac]['CaptacaoReal'] dataframe = data.planilha_comprovacao project_verified = dataframe.loc[dataframe['PRONAC'] == str(pronac)] if project_verified.empty: project_verified_funds = 0 else: pronac_funds = project_verified[ ["idPlanilhaAprovacao", "PRONAC", "vlComprovacao", "idSegmento"] ] funds_grp = pronac_funds.drop(columns=["idPlanilhaAprovacao"]).groupby( ["PRONAC"] ) project_verified_funds = funds_grp.sum().loc[pronac]["vlComprovacao"] to_verify_value = project_raised_funds - float(project_verified_funds) is_outlier = to_verify_value != 0 return { 'is_outlier': is_outlier, 'valor': to_verify_value, 'valor_captado': project_raised_funds, 'valor_comprovado': project_verified_funds, 'minimo_esperado': 0, }
python
def to_verify_funds(pronac, dt): """ Checks how much money is left for the project to verify, using raised_funds - verified_funds This value can be negative (a project can verify more money than the value approved) """ project_raised_funds = data.raised_funds_by_project.loc[pronac]['CaptacaoReal'] dataframe = data.planilha_comprovacao project_verified = dataframe.loc[dataframe['PRONAC'] == str(pronac)] if project_verified.empty: project_verified_funds = 0 else: pronac_funds = project_verified[ ["idPlanilhaAprovacao", "PRONAC", "vlComprovacao", "idSegmento"] ] funds_grp = pronac_funds.drop(columns=["idPlanilhaAprovacao"]).groupby( ["PRONAC"] ) project_verified_funds = funds_grp.sum().loc[pronac]["vlComprovacao"] to_verify_value = project_raised_funds - float(project_verified_funds) is_outlier = to_verify_value != 0 return { 'is_outlier': is_outlier, 'valor': to_verify_value, 'valor_captado': project_raised_funds, 'valor_comprovado': project_verified_funds, 'minimo_esperado': 0, }
Checks how much money is left for the project to verify, using raised_funds - verified_funds This value can be negative (a project can verify more money than the value approved)
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/to_verify_funds.py#L23-L54
lappis-unb/salic-ml
src/salicml/metrics/finance/proponent_projects.py
proponent_projects
def proponent_projects(pronac, data): """ Checks the CNPJ/CPF of the proponent of project with the given pronac and returns all the projects that have been submitted by this proponent and all projects that have already been analyzed. """ cpf_cnpj = get_cpf_cnpj_by_pronac(pronac) proponent_submitted_projects = {} proponent_analyzed_projects = {} if cpf_cnpj: submitted_projects = get_proponent_submitted_projects(cpf_cnpj) analyzed_projects = get_proponent_analyzed_projects(cpf_cnpj) try: proponent_submitted_projects = { 'number_of_projects': submitted_projects['num_pronacs'], 'pronacs_of_this_proponent': submitted_projects['pronac_list'] } except KeyError: pass try: proponent_analyzed_projects = { 'number_of_projects': analyzed_projects['num_pronacs'], 'pronacs_of_this_proponent': analyzed_projects['pronac_list'] } except KeyError: pass return { 'cpf_cnpj': cpf_cnpj, 'valor': len(proponent_submitted_projects), 'projetos_submetidos': proponent_submitted_projects, 'projetos_analizados': proponent_analyzed_projects, }
python
def proponent_projects(pronac, data): """ Checks the CNPJ/CPF of the proponent of project with the given pronac and returns all the projects that have been submitted by this proponent and all projects that have already been analyzed. """ cpf_cnpj = get_cpf_cnpj_by_pronac(pronac) proponent_submitted_projects = {} proponent_analyzed_projects = {} if cpf_cnpj: submitted_projects = get_proponent_submitted_projects(cpf_cnpj) analyzed_projects = get_proponent_analyzed_projects(cpf_cnpj) try: proponent_submitted_projects = { 'number_of_projects': submitted_projects['num_pronacs'], 'pronacs_of_this_proponent': submitted_projects['pronac_list'] } except KeyError: pass try: proponent_analyzed_projects = { 'number_of_projects': analyzed_projects['num_pronacs'], 'pronacs_of_this_proponent': analyzed_projects['pronac_list'] } except KeyError: pass return { 'cpf_cnpj': cpf_cnpj, 'valor': len(proponent_submitted_projects), 'projetos_submetidos': proponent_submitted_projects, 'projetos_analizados': proponent_analyzed_projects, }
Checks the CNPJ/CPF of the proponent of project with the given pronac and returns all the projects that have been submitted by this proponent and all projects that have already been analyzed.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/proponent_projects.py#L9-L46
lappis-unb/salic-ml
src/salicml/metrics/finance/proponent_projects.py
analyzed_projects
def analyzed_projects(raw_df): """ Return all projects that was analyzed. """ df = raw_df[['PRONAC', 'proponenteCgcCpf']] analyzed_projects = df.groupby('proponenteCgcCpf')[ 'PRONAC' ].agg(['unique', 'nunique']) analyzed_projects.columns = ['pronac_list', 'num_pronacs'] return analyzed_projects
python
def analyzed_projects(raw_df): """ Return all projects that was analyzed. """ df = raw_df[['PRONAC', 'proponenteCgcCpf']] analyzed_projects = df.groupby('proponenteCgcCpf')[ 'PRONAC' ].agg(['unique', 'nunique']) analyzed_projects.columns = ['pronac_list', 'num_pronacs'] return analyzed_projects
Return all projects that was analyzed.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/proponent_projects.py#L50-L62
lappis-unb/salic-ml
src/salicml/metrics/finance/proponent_projects.py
submitted_projects
def submitted_projects(raw_df): """ Return all submitted projects. """ df = raw_df.astype({'PRONAC': str, 'CgcCpf': str}) submitted_projects = df.groupby('CgcCpf')[ 'PRONAC' ].agg(['unique', 'nunique']) submitted_projects.columns = ['pronac_list', 'num_pronacs'] return submitted_projects
python
def submitted_projects(raw_df): """ Return all submitted projects. """ df = raw_df.astype({'PRONAC': str, 'CgcCpf': str}) submitted_projects = df.groupby('CgcCpf')[ 'PRONAC' ].agg(['unique', 'nunique']) submitted_projects.columns = ['pronac_list', 'num_pronacs'] return submitted_projects
Return all submitted projects.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/proponent_projects.py#L66-L77
lappis-unb/salic-ml
src/salicml/utils/read_csv.py
read_csv
def read_csv(csv_name, usecols=None): """Returns a DataFrame from a .csv file stored in /data/raw/""" csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv(csv_path, low_memory=False, usecols=usecols, encoding="utf-8") return csv
python
def read_csv(csv_name, usecols=None): """Returns a DataFrame from a .csv file stored in /data/raw/""" csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv(csv_path, low_memory=False, usecols=usecols, encoding="utf-8") return csv
Returns a DataFrame from a .csv file stored in /data/raw/
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/utils/read_csv.py#L10-L15
lappis-unb/salic-ml
src/salicml/utils/read_csv.py
read_csv_with_different_type
def read_csv_with_different_type(csv_name, column_types_dict, usecols=None): """Returns a DataFrame from a .csv file stored in /data/raw/. Reads the CSV as string. """ csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv( csv_path, usecols=usecols, encoding="utf-8", dtype=column_types_dict, engine="python", ) for key_column, val_type in column_types_dict.items(): if val_type == str: csv[key_column] = csv[key_column].str.strip() return csv
python
def read_csv_with_different_type(csv_name, column_types_dict, usecols=None): """Returns a DataFrame from a .csv file stored in /data/raw/. Reads the CSV as string. """ csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv( csv_path, usecols=usecols, encoding="utf-8", dtype=column_types_dict, engine="python", ) for key_column, val_type in column_types_dict.items(): if val_type == str: csv[key_column] = csv[key_column].str.strip() return csv
Returns a DataFrame from a .csv file stored in /data/raw/. Reads the CSV as string.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/utils/read_csv.py#L18-L34
lappis-unb/salic-ml
src/salicml/utils/read_csv.py
read_csv_as_integer
def read_csv_as_integer(csv_name, integer_columns, usecols=None): """Returns a DataFrame from a .csv file stored in /data/raw/. Converts columns specified by 'integer_columns' to integer. """ csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv(csv_path, low_memory=False, usecols=usecols) for column in integer_columns: csv = csv[pd.to_numeric(csv[column], errors="coerce").notnull()] csv[integer_columns] = csv[integer_columns].apply(pd.to_numeric) return csv
python
def read_csv_as_integer(csv_name, integer_columns, usecols=None): """Returns a DataFrame from a .csv file stored in /data/raw/. Converts columns specified by 'integer_columns' to integer. """ csv_path = os.path.join(DATA_FOLDER, csv_name) csv = pd.read_csv(csv_path, low_memory=False, usecols=usecols) for column in integer_columns: csv = csv[pd.to_numeric(csv[column], errors="coerce").notnull()] csv[integer_columns] = csv[integer_columns].apply(pd.to_numeric) return csv
Returns a DataFrame from a .csv file stored in /data/raw/. Converts columns specified by 'integer_columns' to integer.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/utils/read_csv.py#L37-L46
lappis-unb/salic-ml
src/salicml/metrics/finance/operation_code_receipts.py
check_receipts
def check_receipts(pronac, dt): """ Checks how many items are in a same receipt when payment type is check - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt """ df = verified_repeated_receipts_for_pronac(pronac) comprovantes_cheque = df[df['tpFormaDePagamento'] == 1.0] return metric_return(comprovantes_cheque)
python
def check_receipts(pronac, dt): """ Checks how many items are in a same receipt when payment type is check - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt """ df = verified_repeated_receipts_for_pronac(pronac) comprovantes_cheque = df[df['tpFormaDePagamento'] == 1.0] return metric_return(comprovantes_cheque)
Checks how many items are in a same receipt when payment type is check - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/operation_code_receipts.py#L19-L28
lappis-unb/salic-ml
src/salicml/metrics/finance/operation_code_receipts.py
transfer_receipts
def transfer_receipts(pronac, dt): """ Checks how many items are in a same receipt when payment type is bank transfer - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt """ df = verified_repeated_receipts_for_pronac(pronac) comprovantes_transferencia = df[df['tpFormaDePagamento'] == 2.0] return metric_return(comprovantes_transferencia)
python
def transfer_receipts(pronac, dt): """ Checks how many items are in a same receipt when payment type is bank transfer - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt """ df = verified_repeated_receipts_for_pronac(pronac) comprovantes_transferencia = df[df['tpFormaDePagamento'] == 2.0] return metric_return(comprovantes_transferencia)
Checks how many items are in a same receipt when payment type is bank transfer - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/operation_code_receipts.py#L32-L42
lappis-unb/salic-ml
src/salicml/metrics/finance/operation_code_receipts.py
money_receipts
def money_receipts(pronac, dt): """ Checks how many items are in a same receipt when payment type is withdraw/money - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt """ df = verified_repeated_receipts_for_pronac(pronac) comprovantes_saque = df[df['tpFormaDePagamento'] == 3.0] return metric_return(comprovantes_saque)
python
def money_receipts(pronac, dt): """ Checks how many items are in a same receipt when payment type is withdraw/money - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt """ df = verified_repeated_receipts_for_pronac(pronac) comprovantes_saque = df[df['tpFormaDePagamento'] == 3.0] return metric_return(comprovantes_saque)
Checks how many items are in a same receipt when payment type is withdraw/money - is_outlier: True if there are any receipts that have more than one - itens_que_compartilham_comprovantes: List of items that share receipt
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/operation_code_receipts.py#L46-L56
lappis-unb/salic-ml
src/salicml/metrics/finance/raised_funds.py
raised_funds
def raised_funds(pronac, data): """ Returns the total raised funds of a project with the given pronac and if this project is an outlier based on this value. """ is_outlier, mean, std, total_raised_funds = get_outlier_info(pronac) maximum_expected_funds = gaussian_outlier.maximum_expected_value(mean, std) return { 'is_outlier': is_outlier, 'total_raised_funds': total_raised_funds, 'maximum_expected_funds': maximum_expected_funds }
python
def raised_funds(pronac, data): """ Returns the total raised funds of a project with the given pronac and if this project is an outlier based on this value. """ is_outlier, mean, std, total_raised_funds = get_outlier_info(pronac) maximum_expected_funds = gaussian_outlier.maximum_expected_value(mean, std) return { 'is_outlier': is_outlier, 'total_raised_funds': total_raised_funds, 'maximum_expected_funds': maximum_expected_funds }
Returns the total raised funds of a project with the given pronac and if this project is an outlier based on this value.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/raised_funds.py#L9-L22
lappis-unb/salic-ml
src/salicml/metrics/finance/raised_funds.py
segment_raised_funds_average
def segment_raised_funds_average(df): """ Return some info about raised funds. """ grouped = df.groupby('Segmento') aggregated = grouped.agg(['mean', 'std']) aggregated.columns = aggregated.columns.droplevel(0) return aggregated
python
def segment_raised_funds_average(df): """ Return some info about raised funds. """ grouped = df.groupby('Segmento') aggregated = grouped.agg(['mean', 'std']) aggregated.columns = aggregated.columns.droplevel(0) return aggregated
Return some info about raised funds.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/raised_funds.py#L38-L46
lappis-unb/salic-ml
src/salicml/metrics/finance/raised_funds.py
get_outlier_info
def get_outlier_info(pronac): """ Return if a project with the given pronac is an outlier based on raised funds. """ df = data.planilha_captacao raised_funds_averages = data.segment_raised_funds_average.to_dict('index') segment_id = df[df['Pronac'] == pronac]['Segmento'].iloc[0] mean = raised_funds_averages[segment_id]['mean'] std = raised_funds_averages[segment_id]['std'] project_raised_funds = get_project_raised_funds(pronac) outlier = gaussian_outlier.is_outlier(project_raised_funds, mean, std) return (outlier, mean, std, project_raised_funds)
python
def get_outlier_info(pronac): """ Return if a project with the given pronac is an outlier based on raised funds. """ df = data.planilha_captacao raised_funds_averages = data.segment_raised_funds_average.to_dict('index') segment_id = df[df['Pronac'] == pronac]['Segmento'].iloc[0] mean = raised_funds_averages[segment_id]['mean'] std = raised_funds_averages[segment_id]['std'] project_raised_funds = get_project_raised_funds(pronac) outlier = gaussian_outlier.is_outlier(project_raised_funds, mean, std) return (outlier, mean, std, project_raised_funds)
Return if a project with the given pronac is an outlier based on raised funds.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/raised_funds.py#L49-L66
lappis-unb/salic-ml
src/salicml/metrics/finance/verified_approved.py
verified_approved
def verified_approved(pronac, dt): """ This metric compare budgetary items of SALIC projects in terms of verified versus approved value Items that have vlComprovacao > vlAprovacao * 1.5 are considered outliers output: is_outlier: True if any item is outlier valor: Absolute number of items that are outliers outlier_items: Outlier items detail """ items_df = data.approved_verified_items items_df = items_df.loc[items_df['PRONAC'] == pronac] items_df[[APPROVED_COLUMN, VERIFIED_COLUMN]] = items_df[ [APPROVED_COLUMN, VERIFIED_COLUMN] ].astype(float) items_df["Item"] = items_df["Item"].str.replace("\r", "") items_df["Item"] = items_df["Item"].str.replace("\n", "") items_df["Item"] = items_df["Item"].str.replace('"', "") items_df["Item"] = items_df["Item"].str.replace("'", "") items_df["Item"] = items_df["Item"].str.replace("\\", "") THRESHOLD = 1.5 bigger_than_approved = items_df[VERIFIED_COLUMN] > ( items_df[APPROVED_COLUMN] * THRESHOLD ) features = items_df[bigger_than_approved] outlier_items = outlier_items_(features) features_size = features.shape[0] is_outlier = features_size > 0 return { "is_outlier": is_outlier, "valor": features_size, "maximo_esperado": MIN_EXPECTED_ITEMS, "minimo_esperado": MAX_EXPECTED_ITEMS, "lista_de_comprovantes": outlier_items, "link_da_planilha": "http://salic.cultura.gov.br/projeto/#/{0}/relacao-de-pagamento".format(pronac) }
python
def verified_approved(pronac, dt): """ This metric compare budgetary items of SALIC projects in terms of verified versus approved value Items that have vlComprovacao > vlAprovacao * 1.5 are considered outliers output: is_outlier: True if any item is outlier valor: Absolute number of items that are outliers outlier_items: Outlier items detail """ items_df = data.approved_verified_items items_df = items_df.loc[items_df['PRONAC'] == pronac] items_df[[APPROVED_COLUMN, VERIFIED_COLUMN]] = items_df[ [APPROVED_COLUMN, VERIFIED_COLUMN] ].astype(float) items_df["Item"] = items_df["Item"].str.replace("\r", "") items_df["Item"] = items_df["Item"].str.replace("\n", "") items_df["Item"] = items_df["Item"].str.replace('"', "") items_df["Item"] = items_df["Item"].str.replace("'", "") items_df["Item"] = items_df["Item"].str.replace("\\", "") THRESHOLD = 1.5 bigger_than_approved = items_df[VERIFIED_COLUMN] > ( items_df[APPROVED_COLUMN] * THRESHOLD ) features = items_df[bigger_than_approved] outlier_items = outlier_items_(features) features_size = features.shape[0] is_outlier = features_size > 0 return { "is_outlier": is_outlier, "valor": features_size, "maximo_esperado": MIN_EXPECTED_ITEMS, "minimo_esperado": MAX_EXPECTED_ITEMS, "lista_de_comprovantes": outlier_items, "link_da_planilha": "http://salic.cultura.gov.br/projeto/#/{0}/relacao-de-pagamento".format(pronac) }
This metric compare budgetary items of SALIC projects in terms of verified versus approved value Items that have vlComprovacao > vlAprovacao * 1.5 are considered outliers output: is_outlier: True if any item is outlier valor: Absolute number of items that are outliers outlier_items: Outlier items detail
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/metrics/finance/verified_approved.py#L12-L49
lappis-unb/salic-ml
src/salicml/data/loader.py
csv_to_pickle
def csv_to_pickle(path=ROOT / "raw", clean=False): """Convert all CSV files in path to pickle.""" for file in os.listdir(path): base, ext = os.path.splitext(file) if ext != ".csv": continue LOG(f"converting {file} to pickle") df = pd.read_csv(path / file, low_memory=True) WRITE_DF(df, path / (base + "." + FILE_EXTENSION), **WRITE_DF_OPTS) if clean: os.remove(path / file) LOG(f"removed {file}")
python
def csv_to_pickle(path=ROOT / "raw", clean=False): """Convert all CSV files in path to pickle.""" for file in os.listdir(path): base, ext = os.path.splitext(file) if ext != ".csv": continue LOG(f"converting {file} to pickle") df = pd.read_csv(path / file, low_memory=True) WRITE_DF(df, path / (base + "." + FILE_EXTENSION), **WRITE_DF_OPTS) if clean: os.remove(path / file) LOG(f"removed {file}")
Convert all CSV files in path to pickle.
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/data/loader.py#L105-L118
lappis-unb/salic-ml
src/salicml/data/loader.py
Loader.store
def store(self, loc, df): """Store dataframe in the given location. Store some arbitrary dataframe: >>> data.store('my_data', df) Now recover it from the global store. >>> data.my_data ... """ path = "%s.%s" % (self._root / "processed" / loc, FILE_EXTENSION) WRITE_DF(df, path, **WRITE_DF_OPTS) self._cache[loc] = df
python
def store(self, loc, df): """Store dataframe in the given location. Store some arbitrary dataframe: >>> data.store('my_data', df) Now recover it from the global store. >>> data.my_data ... """ path = "%s.%s" % (self._root / "processed" / loc, FILE_EXTENSION) WRITE_DF(df, path, **WRITE_DF_OPTS) self._cache[loc] = df
Store dataframe in the given location. Store some arbitrary dataframe: >>> data.store('my_data', df) Now recover it from the global store. >>> data.my_data ...
https://github.com/lappis-unb/salic-ml/blob/1b3ebc4f8067740999897ccffd9892dc94482a93/src/salicml/data/loader.py#L52-L66
MisterY/asset-allocation
asset_allocation/stocks.py
StocksInfo.close_databases
def close_databases(self): """ Close all database sessions """ if self.gc_book: self.gc_book.close() if self.pricedb_session: self.pricedb_session.close()
python
def close_databases(self): """ Close all database sessions """ if self.gc_book: self.gc_book.close() if self.pricedb_session: self.pricedb_session.close()
Close all database sessions
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/stocks.py#L31-L36
MisterY/asset-allocation
asset_allocation/stocks.py
StocksInfo.load_stock_quantity
def load_stock_quantity(self, symbol: str) -> Decimal(0): """ retrieves stock quantity """ book = self.get_gc_book() collection = SecuritiesAggregate(book) sec = collection.get_aggregate_for_symbol(symbol) quantity = sec.get_quantity() return quantity
python
def load_stock_quantity(self, symbol: str) -> Decimal(0): """ retrieves stock quantity """ book = self.get_gc_book() collection = SecuritiesAggregate(book) sec = collection.get_aggregate_for_symbol(symbol) quantity = sec.get_quantity() return quantity
retrieves stock quantity
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/stocks.py#L38-L45
MisterY/asset-allocation
asset_allocation/stocks.py
StocksInfo.get_gc_book
def get_gc_book(self): """ Returns the GnuCash db session """ if not self.gc_book: gc_db = self.config.get(ConfigKeys.gnucash_book_path) if not gc_db: raise AttributeError("GnuCash book path not configured.") # check if this is the abs file exists if not os.path.isabs(gc_db): gc_db = resource_filename( Requirement.parse("Asset-Allocation"), gc_db) if not os.path.exists(gc_db): raise ValueError(f"Invalid GnuCash book path {gc_db}") self.gc_book = open_book(gc_db, open_if_lock=True) return self.gc_book
python
def get_gc_book(self): """ Returns the GnuCash db session """ if not self.gc_book: gc_db = self.config.get(ConfigKeys.gnucash_book_path) if not gc_db: raise AttributeError("GnuCash book path not configured.") # check if this is the abs file exists if not os.path.isabs(gc_db): gc_db = resource_filename( Requirement.parse("Asset-Allocation"), gc_db) if not os.path.exists(gc_db): raise ValueError(f"Invalid GnuCash book path {gc_db}") self.gc_book = open_book(gc_db, open_if_lock=True) return self.gc_book
Returns the GnuCash db session
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/stocks.py#L55-L69
MisterY/asset-allocation
asset_allocation/stocks.py
StocksInfo.get_symbols_with_positive_balances
def get_symbols_with_positive_balances(self) -> List[str]: """ Identifies all the securities with positive balances """ from gnucash_portfolio import BookAggregate holdings = [] with BookAggregate() as book: # query = book.securities.query.filter(Commodity.) holding_entities = book.securities.get_all() for item in holding_entities: # Check holding balance agg = book.securities.get_aggregate(item) balance = agg.get_num_shares() if balance > Decimal(0): holdings.append(f"{item.namespace}:{item.mnemonic}") else: self.logger.debug(f"0 balance for {item}") # holdings = map(lambda x: , holding_entities) return holdings
python
def get_symbols_with_positive_balances(self) -> List[str]: """ Identifies all the securities with positive balances """ from gnucash_portfolio import BookAggregate holdings = [] with BookAggregate() as book: # query = book.securities.query.filter(Commodity.) holding_entities = book.securities.get_all() for item in holding_entities: # Check holding balance agg = book.securities.get_aggregate(item) balance = agg.get_num_shares() if balance > Decimal(0): holdings.append(f"{item.namespace}:{item.mnemonic}") else: self.logger.debug(f"0 balance for {item}") # holdings = map(lambda x: , holding_entities) return holdings
Identifies all the securities with positive balances
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/stocks.py#L71-L90
MisterY/asset-allocation
asset_allocation/stocks.py
StocksInfo.__get_pricedb_session
def __get_pricedb_session(self): """ Provides initialization and access to module-level session """ from pricedb import dal if not self.pricedb_session: self.pricedb_session = dal.get_default_session() return self.pricedb_session
python
def __get_pricedb_session(self): """ Provides initialization and access to module-level session """ from pricedb import dal if not self.pricedb_session: self.pricedb_session = dal.get_default_session() return self.pricedb_session
Provides initialization and access to module-level session
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/stocks.py#L125-L131
MisterY/asset-allocation
asset_allocation/stocklink_cli.py
add
def add(assetclass: int, symbol: str): """ Add a stock to an asset class """ assert isinstance(symbol, str) assert isinstance(assetclass, int) symbol = symbol.upper() app = AppAggregate() new_item = app.add_stock_to_class(assetclass, symbol) print(f"Record added: {new_item}.")
python
def add(assetclass: int, symbol: str): """ Add a stock to an asset class """ assert isinstance(symbol, str) assert isinstance(assetclass, int) symbol = symbol.upper() app = AppAggregate() new_item = app.add_stock_to_class(assetclass, symbol) print(f"Record added: {new_item}.")
Add a stock to an asset class
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/stocklink_cli.py#L23-L31
MisterY/asset-allocation
asset_allocation/stocklink_cli.py
unallocated
def unallocated(): """ Identify unallocated holdings """ app = AppAggregate() app.logger = logger unalloc = app.find_unallocated_holdings() if not unalloc: print(f"No unallocated holdings.") for item in unalloc: print(item)
python
def unallocated(): """ Identify unallocated holdings """ app = AppAggregate() app.logger = logger unalloc = app.find_unallocated_holdings() if not unalloc: print(f"No unallocated holdings.") for item in unalloc: print(item)
Identify unallocated holdings
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/stocklink_cli.py#L74-L84
MisterY/asset-allocation
asset_allocation/formatters.py
AsciiFormatter.format
def format(self, model: AssetAllocationModel, full: bool = False): """ Returns the view-friendly output of the aa model """ self.full = full # Header output = f"Asset Allocation model, total: {model.currency} {model.total_amount:,.2f}\n" # Column Headers for column in self.columns: name = column['name'] if not self.full and name == "loc.cur.": # Skip local currency if not displaying stocks. continue width = column["width"] output += f"{name:^{width}}" output += "\n" output += f"-------------------------------------------------------------------------------\n" # Asset classes view_model = ModelMapper(model).map_to_linear(self.full) for row in view_model: output += self.__format_row(row) + "\n" return output
python
def format(self, model: AssetAllocationModel, full: bool = False): """ Returns the view-friendly output of the aa model """ self.full = full # Header output = f"Asset Allocation model, total: {model.currency} {model.total_amount:,.2f}\n" # Column Headers for column in self.columns: name = column['name'] if not self.full and name == "loc.cur.": # Skip local currency if not displaying stocks. continue width = column["width"] output += f"{name:^{width}}" output += "\n" output += f"-------------------------------------------------------------------------------\n" # Asset classes view_model = ModelMapper(model).map_to_linear(self.full) for row in view_model: output += self.__format_row(row) + "\n" return output
Returns the view-friendly output of the aa model
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/formatters.py#L26-L50
MisterY/asset-allocation
asset_allocation/formatters.py
AsciiFormatter.__format_row
def __format_row(self, row: AssetAllocationViewModel): """ display-format one row Formats one Asset Class record """ output = "" index = 0 # Name value = row.name # Indent according to depth. for _ in range(0, row.depth): value = f" {value}" output += self.append_text_column(value, index) # Set Allocation value = "" index += 1 if row.set_allocation > 0: value = f"{row.set_allocation:.2f}" output += self.append_num_column(value, index) # Current Allocation value = "" index += 1 if row.curr_allocation > Decimal(0): value = f"{row.curr_allocation:.2f}" output += self.append_num_column(value, index) # Allocation difference, percentage value = "" index += 1 if row.alloc_diff_perc.copy_abs() > Decimal(0): value = f"{row.alloc_diff_perc:.0f} %" output += self.append_num_column(value, index) # Allocated value index += 1 value = "" if row.set_value: value = f"{row.set_value:,.0f}" output += self.append_num_column(value, index) # Current Value index += 1 value = f"{row.curr_value:,.0f}" output += self.append_num_column(value, index) # Value in security's currency. Show only if displaying full model, with stocks. index += 1 if self.full: value = "" if row.curr_value_own_currency: value = f"({row.curr_value_own_currency:,.0f}" value += f" {row.own_currency}" value += ")" output += self.append_num_column(value, index) # https://en.wikipedia.org/wiki/ANSI_escape_code # CSI="\x1B[" # red = 31, green = 32 # output += CSI+"31;40m" + "Colored Text" + CSI + "0m" # Value diff index += 1 value = "" if row.diff_value: value = f"{row.diff_value:,.0f}" # Color the output # value = f"{CSI};40m{value}{CSI};40m" output += self.append_num_column(value, index) return output
python
def __format_row(self, row: AssetAllocationViewModel): """ display-format one row Formats one Asset Class record """ output = "" index = 0 # Name value = row.name # Indent according to depth. for _ in range(0, row.depth): value = f" {value}" output += self.append_text_column(value, index) # Set Allocation value = "" index += 1 if row.set_allocation > 0: value = f"{row.set_allocation:.2f}" output += self.append_num_column(value, index) # Current Allocation value = "" index += 1 if row.curr_allocation > Decimal(0): value = f"{row.curr_allocation:.2f}" output += self.append_num_column(value, index) # Allocation difference, percentage value = "" index += 1 if row.alloc_diff_perc.copy_abs() > Decimal(0): value = f"{row.alloc_diff_perc:.0f} %" output += self.append_num_column(value, index) # Allocated value index += 1 value = "" if row.set_value: value = f"{row.set_value:,.0f}" output += self.append_num_column(value, index) # Current Value index += 1 value = f"{row.curr_value:,.0f}" output += self.append_num_column(value, index) # Value in security's currency. Show only if displaying full model, with stocks. index += 1 if self.full: value = "" if row.curr_value_own_currency: value = f"({row.curr_value_own_currency:,.0f}" value += f" {row.own_currency}" value += ")" output += self.append_num_column(value, index) # https://en.wikipedia.org/wiki/ANSI_escape_code # CSI="\x1B[" # red = 31, green = 32 # output += CSI+"31;40m" + "Colored Text" + CSI + "0m" # Value diff index += 1 value = "" if row.diff_value: value = f"{row.diff_value:,.0f}" # Color the output # value = f"{CSI};40m{value}{CSI};40m" output += self.append_num_column(value, index) return output
display-format one row Formats one Asset Class record
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/formatters.py#L52-L122
MisterY/asset-allocation
asset_allocation/formatters.py
AsciiFormatter.append_num_column
def append_num_column(self, text: str, index: int): """ Add value to the output row, width based on index """ width = self.columns[index]["width"] return f"{text:>{width}}"
python
def append_num_column(self, text: str, index: int): """ Add value to the output row, width based on index """ width = self.columns[index]["width"] return f"{text:>{width}}"
Add value to the output row, width based on index
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/formatters.py#L124-L127
MisterY/asset-allocation
asset_allocation/formatters.py
AsciiFormatter.append_text_column
def append_text_column(self, text: str, index: int): """ Add value to the output row, width based on index """ width = self.columns[index]["width"] return f"{text:<{width}}"
python
def append_text_column(self, text: str, index: int): """ Add value to the output row, width based on index """ width = self.columns[index]["width"] return f"{text:<{width}}"
Add value to the output row, width based on index
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/formatters.py#L129-L132
MisterY/asset-allocation
asset_allocation/maps.py
AssetClassMapper.map_entity
def map_entity(self, entity: dal.AssetClass): """ maps data from entity -> object """ obj = model.AssetClass() obj.id = entity.id obj.parent_id = entity.parentid obj.name = entity.name obj.allocation = entity.allocation obj.sort_order = entity.sortorder #entity.stock_links #entity.diff_adjustment if entity.parentid == None: obj.depth = 0 return obj
python
def map_entity(self, entity: dal.AssetClass): """ maps data from entity -> object """ obj = model.AssetClass() obj.id = entity.id obj.parent_id = entity.parentid obj.name = entity.name obj.allocation = entity.allocation obj.sort_order = entity.sortorder #entity.stock_links #entity.diff_adjustment if entity.parentid == None: obj.depth = 0 return obj
maps data from entity -> object
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L14-L28
MisterY/asset-allocation
asset_allocation/maps.py
ModelMapper.map_to_linear
def map_to_linear(self, with_stocks: bool=False): """ Maps the tree to a linear representation suitable for display """ result = [] for ac in self.model.classes: rows = self.__get_ac_tree(ac, with_stocks) result += rows return result
python
def map_to_linear(self, with_stocks: bool=False): """ Maps the tree to a linear representation suitable for display """ result = [] for ac in self.model.classes: rows = self.__get_ac_tree(ac, with_stocks) result += rows return result
Maps the tree to a linear representation suitable for display
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L36-L43
MisterY/asset-allocation
asset_allocation/maps.py
ModelMapper.__get_ac_tree
def __get_ac_tree(self, ac: model.AssetClass, with_stocks: bool): """ formats the ac tree - entity with child elements """ output = [] output.append(self.__get_ac_row(ac)) for child in ac.classes: output += self.__get_ac_tree(child, with_stocks) if with_stocks: for stock in ac.stocks: row = None if isinstance(stock, Stock): row = self.__get_stock_row(stock, ac.depth + 1) elif isinstance(stock, CashBalance): row = self.__get_cash_row(stock, ac.depth + 1) output.append(row) return output
python
def __get_ac_tree(self, ac: model.AssetClass, with_stocks: bool): """ formats the ac tree - entity with child elements """ output = [] output.append(self.__get_ac_row(ac)) for child in ac.classes: output += self.__get_ac_tree(child, with_stocks) if with_stocks: for stock in ac.stocks: row = None if isinstance(stock, Stock): row = self.__get_stock_row(stock, ac.depth + 1) elif isinstance(stock, CashBalance): row = self.__get_cash_row(stock, ac.depth + 1) output.append(row) return output
formats the ac tree - entity with child elements
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L45-L62
MisterY/asset-allocation
asset_allocation/maps.py
ModelMapper.__get_ac_row
def __get_ac_row(self, ac: model.AssetClass) -> AssetAllocationViewModel: """ Formats one Asset Class record """ view_model = AssetAllocationViewModel() view_model.depth = ac.depth # Name view_model.name = ac.name view_model.set_allocation = ac.allocation view_model.curr_allocation = ac.curr_alloc view_model.diff_allocation = ac.alloc_diff view_model.alloc_diff_perc = ac.alloc_diff_perc # value view_model.curr_value = ac.curr_value # expected value view_model.set_value = ac.alloc_value # diff view_model.diff_value = ac.value_diff return view_model
python
def __get_ac_row(self, ac: model.AssetClass) -> AssetAllocationViewModel: """ Formats one Asset Class record """ view_model = AssetAllocationViewModel() view_model.depth = ac.depth # Name view_model.name = ac.name view_model.set_allocation = ac.allocation view_model.curr_allocation = ac.curr_alloc view_model.diff_allocation = ac.alloc_diff view_model.alloc_diff_perc = ac.alloc_diff_perc # value view_model.curr_value = ac.curr_value # expected value view_model.set_value = ac.alloc_value # diff view_model.diff_value = ac.value_diff return view_model
Formats one Asset Class record
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L64-L85
MisterY/asset-allocation
asset_allocation/maps.py
ModelMapper.__get_stock_row
def __get_stock_row(self, stock: Stock, depth: int) -> str: """ formats stock row """ assert isinstance(stock, Stock) view_model = AssetAllocationViewModel() view_model.depth = depth # Symbol view_model.name = stock.symbol # Current allocation view_model.curr_allocation = stock.curr_alloc # Value in base currency view_model.curr_value = stock.value_in_base_currency # Value in security's currency. view_model.curr_value_own_currency = stock.value view_model.own_currency = stock.currency return view_model
python
def __get_stock_row(self, stock: Stock, depth: int) -> str: """ formats stock row """ assert isinstance(stock, Stock) view_model = AssetAllocationViewModel() view_model.depth = depth # Symbol view_model.name = stock.symbol # Current allocation view_model.curr_allocation = stock.curr_alloc # Value in base currency view_model.curr_value = stock.value_in_base_currency # Value in security's currency. view_model.curr_value_own_currency = stock.value view_model.own_currency = stock.currency return view_model
formats stock row
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L87-L108
MisterY/asset-allocation
asset_allocation/maps.py
ModelMapper.__get_cash_row
def __get_cash_row(self, item: CashBalance, depth: int) -> str: """ formats stock row """ assert isinstance(item, CashBalance) view_model = AssetAllocationViewModel() view_model.depth = depth # Symbol view_model.name = item.symbol # Value in base currency view_model.curr_value = item.value_in_base_currency # Value in security's currency. view_model.curr_value_own_currency = item.value view_model.own_currency = item.currency return view_model
python
def __get_cash_row(self, item: CashBalance, depth: int) -> str: """ formats stock row """ assert isinstance(item, CashBalance) view_model = AssetAllocationViewModel() view_model.depth = depth # Symbol view_model.name = item.symbol # Value in base currency view_model.curr_value = item.value_in_base_currency # Value in security's currency. view_model.curr_value_own_currency = item.value view_model.own_currency = item.currency return view_model
formats stock row
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/maps.py#L110-L128
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.create_asset_class
def create_asset_class(self, item: AssetClass): """ Inserts the record """ session = self.open_session() session.add(item) session.commit()
python
def create_asset_class(self, item: AssetClass): """ Inserts the record """ session = self.open_session() session.add(item) session.commit()
Inserts the record
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L20-L24
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.add_stock_to_class
def add_stock_to_class(self, assetclass_id: int, symbol: str): """ Add a stock link to an asset class """ assert isinstance(symbol, str) assert isinstance(assetclass_id, int) item = AssetClassStock() item.assetclassid = assetclass_id item.symbol = symbol session = self.open_session() session.add(item) self.save() return item
python
def add_stock_to_class(self, assetclass_id: int, symbol: str): """ Add a stock link to an asset class """ assert isinstance(symbol, str) assert isinstance(assetclass_id, int) item = AssetClassStock() item.assetclassid = assetclass_id item.symbol = symbol session = self.open_session() session.add(item) self.save() return item
Add a stock link to an asset class
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L26-L39
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.delete
def delete(self, id: int): """ Delete asset class """ assert isinstance(id, int) self.open_session() to_delete = self.get(id) self.session.delete(to_delete) self.save()
python
def delete(self, id: int): """ Delete asset class """ assert isinstance(id, int) self.open_session() to_delete = self.get(id) self.session.delete(to_delete) self.save()
Delete asset class
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L41-L48
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.find_unallocated_holdings
def find_unallocated_holdings(self): """ Identifies any holdings that are not included in asset allocation """ # Get linked securities session = self.open_session() linked_entities = session.query(AssetClassStock).all() linked = [] # linked = map(lambda x: f"{x.symbol}", linked_entities) for item in linked_entities: linked.append(item.symbol) # Get all securities with balance > 0. from .stocks import StocksInfo stocks = StocksInfo() stocks.logger = self.logger holdings = stocks.get_symbols_with_positive_balances() # Find those which are not included in the stock links. non_alloc = [] index = -1 for item in holdings: try: index = linked.index(item) self.logger.debug(index) except ValueError: non_alloc.append(item) return non_alloc
python
def find_unallocated_holdings(self): """ Identifies any holdings that are not included in asset allocation """ # Get linked securities session = self.open_session() linked_entities = session.query(AssetClassStock).all() linked = [] # linked = map(lambda x: f"{x.symbol}", linked_entities) for item in linked_entities: linked.append(item.symbol) # Get all securities with balance > 0. from .stocks import StocksInfo stocks = StocksInfo() stocks.logger = self.logger holdings = stocks.get_symbols_with_positive_balances() # Find those which are not included in the stock links. non_alloc = [] index = -1 for item in holdings: try: index = linked.index(item) self.logger.debug(index) except ValueError: non_alloc.append(item) return non_alloc
Identifies any holdings that are not included in asset allocation
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L50-L77
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.get
def get(self, id: int) -> AssetClass: """ Loads Asset Class """ self.open_session() item = self.session.query(AssetClass).filter( AssetClass.id == id).first() return item
python
def get(self, id: int) -> AssetClass: """ Loads Asset Class """ self.open_session() item = self.session.query(AssetClass).filter( AssetClass.id == id).first() return item
Loads Asset Class
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L79-L84
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.open_session
def open_session(self): """ Opens a db session and returns it """ from .dal import get_session cfg = Config() cfg.logger = self.logger db_path = cfg.get(ConfigKeys.asset_allocation_database_path) self.session = get_session(db_path) return self.session
python
def open_session(self): """ Opens a db session and returns it """ from .dal import get_session cfg = Config() cfg.logger = self.logger db_path = cfg.get(ConfigKeys.asset_allocation_database_path) self.session = get_session(db_path) return self.session
Opens a db session and returns it
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L86-L95
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.get_asset_allocation
def get_asset_allocation(self): """ Creates and populates the Asset Allocation model. The main function of the app. """ # load from db # TODO set the base currency base_currency = "EUR" loader = AssetAllocationLoader(base_currency=base_currency) loader.logger = self.logger model = loader.load_tree_from_db() model.validate() # securities # read stock links loader.load_stock_links() # read stock quantities from GnuCash loader.load_stock_quantity() # Load cash balances loader.load_cash_balances() # loader.session # read prices from Prices database loader.load_stock_prices() # recalculate stock values into base currency loader.recalculate_stock_values_into_base() # calculate model.calculate_current_value() model.calculate_set_values() model.calculate_current_allocation() # return the model for display return model
python
def get_asset_allocation(self): """ Creates and populates the Asset Allocation model. The main function of the app. """ # load from db # TODO set the base currency base_currency = "EUR" loader = AssetAllocationLoader(base_currency=base_currency) loader.logger = self.logger model = loader.load_tree_from_db() model.validate() # securities # read stock links loader.load_stock_links() # read stock quantities from GnuCash loader.load_stock_quantity() # Load cash balances loader.load_cash_balances() # loader.session # read prices from Prices database loader.load_stock_prices() # recalculate stock values into base currency loader.recalculate_stock_values_into_base() # calculate model.calculate_current_value() model.calculate_set_values() model.calculate_current_allocation() # return the model for display return model
Creates and populates the Asset Allocation model. The main function of the app.
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L101-L131
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.get_asset_classes_for_security
def get_asset_classes_for_security(self, namespace: str, symbol: str) -> List[AssetClass]: """ Find all asset classes (should be only one at the moment, though!) to which the symbol belongs """ full_symbol = symbol if namespace: full_symbol = f"{namespace}:{symbol}" result = ( self.session.query(AssetClassStock) .filter(AssetClassStock.symbol == full_symbol) .all() ) return result
python
def get_asset_classes_for_security(self, namespace: str, symbol: str) -> List[AssetClass]: """ Find all asset classes (should be only one at the moment, though!) to which the symbol belongs """ full_symbol = symbol if namespace: full_symbol = f"{namespace}:{symbol}" result = ( self.session.query(AssetClassStock) .filter(AssetClassStock.symbol == full_symbol) .all() ) return result
Find all asset classes (should be only one at the moment, though!) to which the symbol belongs
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L133-L144
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.validate_model
def validate_model(self): """ Validate the model """ model: AssetAllocationModel = self.get_asset_allocation_model() model.logger = self.logger valid = model.validate() if valid: print(f"The model is valid. Congratulations") else: print(f"The model is invalid.")
python
def validate_model(self): """ Validate the model """ model: AssetAllocationModel = self.get_asset_allocation_model() model.logger = self.logger valid = model.validate() if valid: print(f"The model is valid. Congratulations") else: print(f"The model is invalid.")
Validate the model
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L146-L155
MisterY/asset-allocation
asset_allocation/app.py
AppAggregate.export_symbols
def export_symbols(self): """ Exports all used symbols """ session = self.open_session() links = session.query(AssetClassStock).order_by( AssetClassStock.symbol).all() output = [] for link in links: output.append(link.symbol + '\n') # Save output to a text file. with open("symbols.txt", mode='w') as file: file.writelines(output) print("Symbols exported to symbols.txt")
python
def export_symbols(self): """ Exports all used symbols """ session = self.open_session() links = session.query(AssetClassStock).order_by( AssetClassStock.symbol).all() output = [] for link in links: output.append(link.symbol + '\n') # Save output to a text file. with open("symbols.txt", mode='w') as file: file.writelines(output) print("Symbols exported to symbols.txt")
Exports all used symbols
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/app.py#L157-L170
MisterY/asset-allocation
asset_allocation/config.py
Config.__read_config
def __read_config(self, file_path: str): """ Read the config file """ if not os.path.exists(file_path): raise FileNotFoundError("File path not found: %s", file_path) # check if file exists if not os.path.isfile(file_path): log(ERROR, "file not found: %s", file_path) raise FileNotFoundError("configuration file not found %s", file_path) self.config.read(file_path)
python
def __read_config(self, file_path: str): """ Read the config file """ if not os.path.exists(file_path): raise FileNotFoundError("File path not found: %s", file_path) # check if file exists if not os.path.isfile(file_path): log(ERROR, "file not found: %s", file_path) raise FileNotFoundError("configuration file not found %s", file_path) self.config.read(file_path)
Read the config file
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/config.py#L54-L63
MisterY/asset-allocation
asset_allocation/config.py
Config.__create_user_config
def __create_user_config(self): """ Copy the config template into user's directory """ src_path = self.__get_config_template_path() src = os.path.abspath(src_path) if not os.path.exists(src): log(ERROR, "Config template not found %s", src) raise FileNotFoundError() dst = os.path.abspath(self.get_config_path()) shutil.copyfile(src, dst) if not os.path.exists(dst): raise FileNotFoundError("Config file could not be copied to user dir!")
python
def __create_user_config(self): """ Copy the config template into user's directory """ src_path = self.__get_config_template_path() src = os.path.abspath(src_path) if not os.path.exists(src): log(ERROR, "Config template not found %s", src) raise FileNotFoundError() dst = os.path.abspath(self.get_config_path()) shutil.copyfile(src, dst) if not os.path.exists(dst): raise FileNotFoundError("Config file could not be copied to user dir!")
Copy the config template into user's directory
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/config.py#L75-L88
MisterY/asset-allocation
asset_allocation/config_cli.py
set
def set(aadb, cur): """ Sets the values in the config file """ cfg = Config() edited = False if aadb: cfg.set(ConfigKeys.asset_allocation_database_path, aadb) print(f"The database has been set to {aadb}.") edited = True if cur: cfg.set(ConfigKeys.default_currency, cur) edited = True if edited: print(f"Changes saved.") else: print(f"No changes were made.") print(f"Use --help parameter for more information.")
python
def set(aadb, cur): """ Sets the values in the config file """ cfg = Config() edited = False if aadb: cfg.set(ConfigKeys.asset_allocation_database_path, aadb) print(f"The database has been set to {aadb}.") edited = True if cur: cfg.set(ConfigKeys.default_currency, cur) edited = True if edited: print(f"Changes saved.") else: print(f"No changes were made.") print(f"Use --help parameter for more information.")
Sets the values in the config file
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/config_cli.py#L31-L49
MisterY/asset-allocation
asset_allocation/config_cli.py
get
def get(aadb: str): """ Retrieves a value from config """ if (aadb): cfg = Config() value = cfg.get(ConfigKeys.asset_allocation_database_path) click.echo(value) if not aadb: click.echo("Use --help for more information.")
python
def get(aadb: str): """ Retrieves a value from config """ if (aadb): cfg = Config() value = cfg.get(ConfigKeys.asset_allocation_database_path) click.echo(value) if not aadb: click.echo("Use --help for more information.")
Retrieves a value from config
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/config_cli.py#L53-L61
MisterY/asset-allocation
asset_allocation/model.py
_AssetBase.fullname
def fullname(self): """ includes the full path with parent names """ prefix = "" if self.parent: if self.parent.fullname: prefix = self.parent.fullname + ":" else: # Only the root does not have a parent. In that case we also don't need a name. return "" return prefix + self.name
python
def fullname(self): """ includes the full path with parent names """ prefix = "" if self.parent: if self.parent.fullname: prefix = self.parent.fullname + ":" else: # Only the root does not have a parent. In that case we also don't need a name. return "" return prefix + self.name
includes the full path with parent names
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L67-L77
MisterY/asset-allocation
asset_allocation/model.py
Stock.value
def value(self) -> Decimal: """ Value of the holdings in exchange currency. Value = Quantity * Price """ assert isinstance(self.price, Decimal) return self.quantity * self.price
python
def value(self) -> Decimal: """ Value of the holdings in exchange currency. Value = Quantity * Price """ assert isinstance(self.price, Decimal) return self.quantity * self.price
Value of the holdings in exchange currency. Value = Quantity * Price
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L116-L123
MisterY/asset-allocation
asset_allocation/model.py
Stock.asset_class
def asset_class(self) -> str: """ Returns the full asset class path for this stock """ result = self.parent.name if self.parent else "" # Iterate to the top asset class and add names. cursor = self.parent while cursor: result = cursor.name + ":" + result cursor = cursor.parent return result
python
def asset_class(self) -> str: """ Returns the full asset class path for this stock """ result = self.parent.name if self.parent else "" # Iterate to the top asset class and add names. cursor = self.parent while cursor: result = cursor.name + ":" + result cursor = cursor.parent return result
Returns the full asset class path for this stock
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L126-L134
MisterY/asset-allocation
asset_allocation/model.py
AssetClass.child_allocation
def child_allocation(self): """ The sum of all child asset classes' allocations """ sum = Decimal(0) if self.classes: for child in self.classes: sum += child.child_allocation else: # This is not a branch but a leaf. Return own allocation. sum = self.allocation return sum
python
def child_allocation(self): """ The sum of all child asset classes' allocations """ sum = Decimal(0) if self.classes: for child in self.classes: sum += child.child_allocation else: # This is not a branch but a leaf. Return own allocation. sum = self.allocation return sum
The sum of all child asset classes' allocations
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L152-L162
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.get_class_by_id
def get_class_by_id(self, ac_id: int) -> AssetClass: """ Finds the asset class by id """ assert isinstance(ac_id, int) # iterate recursively for ac in self.asset_classes: if ac.id == ac_id: return ac # if nothing returned so far. return None
python
def get_class_by_id(self, ac_id: int) -> AssetClass: """ Finds the asset class by id """ assert isinstance(ac_id, int) # iterate recursively for ac in self.asset_classes: if ac.id == ac_id: return ac # if nothing returned so far. return None
Finds the asset class by id
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L182-L191
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.get_cash_asset_class
def get_cash_asset_class(self) -> AssetClass: """ Find the cash asset class by name. """ for ac in self.asset_classes: if ac.name.lower() == "cash": return ac return None
python
def get_cash_asset_class(self) -> AssetClass: """ Find the cash asset class by name. """ for ac in self.asset_classes: if ac.name.lower() == "cash": return ac return None
Find the cash asset class by name.
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L193-L198
MisterY/asset-allocation
asset_allocation/model.py
AssetAllocationModel.validate
def validate(self) -> bool: """ Validate that the values match. Incomplete! """ # Asset class allocation should match the sum of children's allocations. # Each group should be compared. sum = Decimal(0) # Go through each asset class, not just the top level. for ac in self.asset_classes: if ac.classes: # get the sum of all the children's allocations child_alloc_sum = ac.child_allocation # compare to set allocation if ac.allocation != child_alloc_sum: message = f"The sum of child allocations {child_alloc_sum:.2f} invalid for {ac}!" self.logger.warning(message) print(message) return False # also make sure that the sum of 1st level children matches 100 for ac in self.classes: sum += ac.allocation if sum != Decimal(100): message = f"The sum of all allocations ({sum:.2f}) does not equal 100!" self.logger.warning(message) print(message) return False return True
python
def validate(self) -> bool: """ Validate that the values match. Incomplete! """ # Asset class allocation should match the sum of children's allocations. # Each group should be compared. sum = Decimal(0) # Go through each asset class, not just the top level. for ac in self.asset_classes: if ac.classes: # get the sum of all the children's allocations child_alloc_sum = ac.child_allocation # compare to set allocation if ac.allocation != child_alloc_sum: message = f"The sum of child allocations {child_alloc_sum:.2f} invalid for {ac}!" self.logger.warning(message) print(message) return False # also make sure that the sum of 1st level children matches 100 for ac in self.classes: sum += ac.allocation if sum != Decimal(100): message = f"The sum of all allocations ({sum:.2f}) does not equal 100!" self.logger.warning(message) print(message) return False return True
Validate that the values match. Incomplete!
https://github.com/MisterY/asset-allocation/blob/72239aa20762cda67c091f27b86e65d61bf3b613/asset_allocation/model.py#L200-L227