idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
60,900 | def add_edge_configuration ( self , param_name , edge , param_value ) : if param_name not in self . config [ 'edges' ] : self . config [ 'edges' ] [ param_name ] = { edge : param_value } else : self . config [ 'edges' ] [ param_name ] [ edge ] = param_value | Set a parameter for a given edge |
60,901 | def add_edge_set_configuration ( self , param_name , edge_to_value ) : for edge , val in future . utils . iteritems ( edge_to_value ) : self . add_edge_configuration ( param_name , edge , val ) | Set Edges parameter |
60,902 | def multi_runs ( model , execution_number = 1 , iteration_number = 50 , infection_sets = None , nprocesses = multiprocessing . cpu_count ( ) ) : if nprocesses > multiprocessing . cpu_count ( ) : nprocesses = multiprocessing . cpu_count ( ) executions = [ ] if infection_sets is not None : if len ( infection_sets ) != execution_number : raise InitializationException ( { "message" : "Number of infection sets provided does not match the number of executions required" } ) for x in past . builtins . xrange ( 0 , execution_number , nprocesses ) : with closing ( multiprocessing . Pool ( processes = nprocesses , maxtasksperchild = 10 ) ) as pool : tasks = [ copy . copy ( model ) . reset ( infection_sets [ i ] ) for i in past . builtins . xrange ( x , min ( x + nprocesses , execution_number ) ) ] results = [ pool . apply_async ( __execute , ( t , iteration_number ) ) for t in tasks ] for result in results : executions . append ( result . get ( ) ) else : for x in past . builtins . xrange ( 0 , execution_number , nprocesses ) : with closing ( multiprocessing . Pool ( processes = nprocesses , maxtasksperchild = 10 ) ) as pool : tasks = [ copy . deepcopy ( model ) . reset ( ) for _ in past . builtins . xrange ( x , min ( x + nprocesses , execution_number ) ) ] results = [ pool . apply_async ( __execute , ( t , iteration_number ) ) for t in tasks ] for result in results : executions . append ( result . get ( ) ) return executions | Multiple executions of a given model varying the initial set of infected nodes |
60,903 | def __execute ( model , iteration_number ) : iterations = model . iteration_bunch ( iteration_number , False ) trends = model . build_trends ( iterations ) [ 0 ] del iterations del model return trends | Execute a simulation model |
60,904 | def set_initial_status ( self , configuration = None ) : super ( AlgorithmicBiasModel , self ) . set_initial_status ( configuration ) for node in self . status : self . status [ node ] = np . random . random_sample ( ) self . initial_status = self . status . copy ( ) | Override behaviour of methods in class DiffusionModel . Overwrites initial status using random real values . |
60,905 | def names ( self ) : if self . name == self . UNKNOWN_HUMAN_PLAYER : return "" , "" if not self . is_ai and " " in self . name : return "" , self . name return self . name , "" | Returns the player s name and real name . Returns two empty strings if the player is unknown . AI real name is always an empty string . |
60,906 | def _getgroup ( string , depth ) : out , comma = [ ] , False while string : items , string = _getitem ( string , depth ) if not string : break out += items if string [ 0 ] == '}' : if comma : return out , string [ 1 : ] return [ '{' + a + '}' for a in out ] , string [ 1 : ] if string [ 0 ] == ',' : comma , string = True , string [ 1 : ] return None | Get a group from the string where group is a list of all the comma separated substrings up to the next } char or the brace enclosed substring if there is no comma |
60,907 | def filter_noexpand_columns ( columns ) : prefix_len = len ( NOEXPAND_PREFIX ) noexpand = [ c [ prefix_len : ] for c in columns if c . startswith ( NOEXPAND_PREFIX ) ] other = [ c for c in columns if not c . startswith ( NOEXPAND_PREFIX ) ] return other , noexpand | Return columns not containing and containing the noexpand prefix . |
60,908 | def to_root ( df , path , key = 'my_ttree' , mode = 'w' , store_index = True , * args , ** kwargs ) : if mode == 'a' : mode = 'update' elif mode == 'w' : mode = 'recreate' else : raise ValueError ( 'Unknown mode: {}. Must be "a" or "w".' . format ( mode ) ) from root_numpy import array2tree df_ = df . copy ( deep = False ) if store_index : name = df_ . index . name if name is None : name = '' df_ [ '__index__' + name ] = df_ . index for col in df_ . select_dtypes ( [ 'category' ] ) . columns : name_components = [ '__rpCaT' , col , str ( df_ [ col ] . cat . ordered ) ] name_components . extend ( df_ [ col ] . cat . categories ) if [ '*' not in c for c in name_components ] : sep = '*' else : raise ValueError ( 'Unable to find suitable separator for columns' ) df_ [ col ] = df_ [ col ] . cat . codes df_ . rename ( index = str , columns = { col : sep . join ( name_components ) } , inplace = True ) arr = df_ . to_records ( index = False ) root_file = ROOT . TFile . Open ( path , mode ) if not root_file : raise IOError ( "cannot open file {0}" . format ( path ) ) if not root_file . IsWritable ( ) : raise IOError ( "file {0} is not writable" . format ( path ) ) open_dirs = [ root_file ] for dir_name in key . split ( '/' ) [ : - 1 ] : current_dir = open_dirs [ - 1 ] . Get ( dir_name ) if not current_dir : current_dir = open_dirs [ - 1 ] . mkdir ( dir_name ) current_dir . cd ( ) open_dirs . append ( current_dir ) key = key . split ( '/' ) [ - 1 ] tree = open_dirs [ - 1 ] . Get ( key ) if not tree : tree = None tree = array2tree ( arr , name = key , tree = tree ) tree . Write ( key , ROOT . TFile . kOverwrite ) root_file . Close ( ) | Write DataFrame to a ROOT file . |
60,909 | def run ( self , symbol : str ) -> SecurityDetailsViewModel : from pydatum import Datum svc = self . _svc sec_agg = svc . securities . get_aggregate_for_symbol ( symbol ) model = SecurityDetailsViewModel ( ) model . symbol = sec_agg . security . namespace + ":" + sec_agg . security . mnemonic model . security = sec_agg . security model . quantity = sec_agg . get_quantity ( ) model . value = sec_agg . get_value ( ) currency = sec_agg . get_currency ( ) if currency : assert isinstance ( currency , str ) model . currency = currency model . price = sec_agg . get_last_available_price ( ) model . average_price = sec_agg . get_avg_price ( ) model . total_paid = sec_agg . get_total_paid_for_remaining_stock ( ) model . profit_loss = model . value - model . total_paid if model . total_paid : model . profit_loss_perc = abs ( model . profit_loss ) * 100 / model . total_paid else : model . profit_loss_perc = 0 if abs ( model . value ) < abs ( model . total_paid ) : model . profit_loss_perc *= - 1 model . income = sec_agg . get_income_total ( ) if model . total_paid : model . income_perc = model . income * 100 / model . total_paid else : model . income_perc = 0 start = Datum ( ) start . subtract_months ( 12 ) end = Datum ( ) model . income_last_12m = sec_agg . get_income_in_period ( start , end ) if model . total_paid == 0 : model . income_perc_last_12m = 0 else : model . income_perc_last_12m = model . income_last_12m * 100 / model . total_paid roc = sec_agg . get_return_of_capital ( ) model . return_of_capital = roc model . total_return = model . profit_loss + model . income if model . total_paid : model . total_return_perc = model . total_return * 100 / model . total_paid else : model . total_return_perc = 0 model . accounts = sec_agg . accounts model . income_accounts = sec_agg . get_income_accounts ( ) from asset_allocation import AppAggregate aa = AppAggregate ( ) aa . open_session ( ) aa . get_asset_classes_for_security ( None , model . symbol ) return model | Loads the model for security details |
60,910 | def handle_friday ( next_date : Datum , period : str , mult : int , start_date : Datum ) : assert isinstance ( next_date , Datum ) assert isinstance ( start_date , Datum ) tmp_sat = next_date . clone ( ) tmp_sat . add_days ( 1 ) tmp_sun = next_date . clone ( ) tmp_sun . add_days ( 2 ) if period == RecurrencePeriod . END_OF_MONTH . value : if ( next_date . is_end_of_month ( ) or tmp_sat . is_end_of_month ( ) or tmp_sun . is_end_of_month ( ) ) : next_date . add_months ( 1 ) else : next_date . add_months ( mult - 1 ) else : if tmp_sat . get_day_name ( ) == start_date . get_day_name ( ) : next_date . add_days ( 1 ) next_date . add_months ( mult ) elif tmp_sun . get_day_name ( ) == start_date . get_day_name ( ) : next_date . add_days ( 2 ) next_date . add_months ( mult ) elif next_date . get_day ( ) >= start_date . get_day ( ) : next_date . add_months ( mult ) elif next_date . is_end_of_month ( ) : next_date . add_months ( mult ) elif tmp_sat . is_end_of_month ( ) : next_date . add_days ( 1 ) next_date . add_months ( mult ) elif tmp_sun . is_end_of_month ( ) : next_date . add_days ( 2 ) next_date . add_months ( mult ) else : next_date . subtract_months ( 1 ) return next_date | Extracted the calculation for when the next_day is Friday |
60,911 | def get_next_occurrence ( self ) -> date : result = get_next_occurrence ( self . transaction ) assert isinstance ( result , date ) return result | Returns the next occurrence date for transaction |
60,912 | def get_enabled ( self ) -> List [ ScheduledTransaction ] : query = ( self . query . filter ( ScheduledTransaction . enabled == True ) ) return query . all ( ) | Returns only enabled scheduled transactions |
60,913 | def get_by_id ( self , tx_id : str ) -> ScheduledTransaction : return self . query . filter ( ScheduledTransaction . guid == tx_id ) . first ( ) | Fetches a tx by id |
60,914 | def get_aggregate_by_id ( self , tx_id : str ) -> ScheduledTxAggregate : tran = self . get_by_id ( tx_id ) return self . get_aggregate_for ( tran ) | Creates an aggregate for single entity |
60,915 | def get_avg_price_stat ( self ) -> Decimal : avg_price = Decimal ( 0 ) price_total = Decimal ( 0 ) price_count = 0 for account in self . security . accounts : if account . type == AccountType . TRADING . name : continue for split in account . splits : if split . quantity == 0 : continue price = split . value / split . quantity price_count += 1 price_total += price if price_count : avg_price = price_total / price_count return avg_price | Calculates the statistical average price for the security by averaging only the prices paid . Very simple first implementation . |
60,916 | def get_avg_price_fifo ( self ) -> Decimal : balance = self . get_quantity ( ) if not balance : return Decimal ( 0 ) paid = Decimal ( 0 ) accounts = self . get_holding_accounts ( ) for account in accounts : splits = self . get_available_splits_for_account ( account ) for split in splits : paid += split . value avg_price = paid / balance return avg_price | Calculates the average price paid for the security . security = Commodity Returns Decimal value . |
60,917 | def get_available_splits_for_account ( self , account : Account ) -> List [ Split ] : available_splits = [ ] query = ( self . get_splits_query ( ) . filter ( Split . account == account ) ) buy_splits = ( query . filter ( Split . quantity > 0 ) . join ( Transaction ) . order_by ( desc ( Transaction . post_date ) ) ) . all ( ) buy_q = sum ( split . quantity for split in buy_splits ) sell_splits = query . filter ( Split . quantity < 0 ) . all ( ) sell_q = sum ( split . quantity for split in sell_splits ) balance = buy_q + sell_q if balance == 0 : return available_splits for real_split in buy_splits : split = splitmapper . map_split ( real_split , SplitModel ( ) ) if split . quantity < balance : balance -= split . quantity else : price = split . value / split . quantity split . quantity -= balance split . value = balance * price balance = 0 available_splits . append ( split ) if balance == 0 : break return available_splits | Returns all unused splits in the account . Used for the calculation of avg . price . The split that has been partially used will have its quantity reduced to available quantity only . |
60,918 | def get_num_shares ( self ) -> Decimal : from pydatum import Datum today = Datum ( ) . today ( ) return self . get_num_shares_on ( today ) | Returns the number of shares at this time |
60,919 | def get_last_available_price ( self ) -> PriceModel : price_db = PriceDbApplication ( ) symbol = SecuritySymbol ( self . security . namespace , self . security . mnemonic ) result = price_db . get_latest_price ( symbol ) return result | Finds the last available price for security . Uses PriceDb . |
60,920 | def __get_holding_accounts_query ( self ) : query = ( self . book . session . query ( Account ) . filter ( Account . commodity == self . security ) . filter ( Account . type != AccountType . trading . value ) ) return query | Returns all holding accounts except Trading accounts . |
60,921 | def get_income_accounts ( self ) -> List [ Account ] : query = ( self . book . session . query ( Account ) . join ( Commodity ) . filter ( Account . name == self . security . mnemonic ) . filter ( Commodity . namespace == "CURRENCY" ) . filter ( Account . type == AccountType . income . value ) ) return query . all ( ) | Returns all income accounts for this security . Income accounts are accounts not under Trading expressed in currency and having the same name as the mnemonic . They should be under Assets but this requires a recursive SQL query . |
60,922 | def get_income_total ( self ) -> Decimal : accounts = self . get_income_accounts ( ) income = Decimal ( 0 ) for acct in accounts : income += acct . get_balance ( ) return income | Sum of all income = sum of balances of all income accounts . |
60,923 | def get_income_in_period ( self , start : datetime , end : datetime ) -> Decimal : accounts = self . get_income_accounts ( ) income = Decimal ( 0 ) for acct in accounts : acc_agg = AccountAggregate ( self . book , acct ) acc_bal = acc_agg . get_balance_in_period ( start , end ) income += acc_bal return income | Returns all income in the given period |
60,924 | def get_prices ( self ) -> List [ PriceModel ] : from pricedb . dal import Price pricedb = PriceDbApplication ( ) repo = pricedb . get_price_repository ( ) query = ( repo . query ( Price ) . filter ( Price . namespace == self . security . namespace ) . filter ( Price . symbol == self . security . mnemonic ) . orderby_desc ( Price . date ) ) return query . all ( ) | Returns all available prices for security |
60,925 | def get_quantity ( self ) -> Decimal : from pydatum import Datum today = Datum ( ) today . today ( ) today . end_of_day ( ) return self . get_num_shares_on ( today . value ) | Returns the number of shares for the given security . It gets the number from all the accounts in the book . |
60,926 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) . join ( Account ) . filter ( Account . type != AccountType . trading . value ) . filter ( Account . commodity_guid == self . security . guid ) ) return query | Returns the query for all splits for this security |
60,927 | def get_total_paid ( self ) -> Decimal : query = ( self . get_splits_query ( ) ) splits = query . all ( ) total = Decimal ( 0 ) for split in splits : total += split . value return total | Returns the total amount paid in currency for the stocks owned |
60,928 | def get_total_paid_for_remaining_stock ( self ) -> Decimal : paid = Decimal ( 0 ) accounts = self . get_holding_accounts ( ) for acc in accounts : splits = self . get_available_splits_for_account ( acc ) paid += sum ( split . value for split in splits ) return paid | Returns the amount paid only for the remaining stock |
60,929 | def get_value ( self ) -> Decimal : quantity = self . get_quantity ( ) price = self . get_last_available_price ( ) if not price : return Decimal ( 0 ) value = quantity * price . value return value | Returns the current value of stocks |
60,930 | def get_value_in_base_currency ( self ) -> Decimal : amt_orig = self . get_value ( ) sec_cur = self . get_currency ( ) cur_svc = CurrenciesAggregate ( self . book ) base_cur = cur_svc . get_default_currency ( ) if sec_cur == base_cur : return amt_orig single_svc = cur_svc . get_currency_aggregate ( sec_cur ) rate = single_svc . get_latest_rate ( base_cur ) result = amt_orig * rate . value return result | Calculates the value of security holdings in base currency |
60,931 | def accounts ( self ) -> List [ Account ] : result = ( [ acct for acct in self . security . accounts if acct . fullname . startswith ( 'Assets' ) ] ) return result | Returns the asset accounts in which the security is held |
60,932 | def find ( self , search_term : str ) -> List [ Commodity ] : query = ( self . query . filter ( Commodity . mnemonic . like ( '%' + search_term + '%' ) | Commodity . fullname . like ( '%' + search_term + '%' ) ) ) return query . all ( ) | Searches for security by part of the name |
60,933 | def get_all ( self ) -> List [ Commodity ] : query = ( self . query . order_by ( Commodity . namespace , Commodity . mnemonic ) ) return query . all ( ) | Loads all non - currency commodities assuming they are stocks . |
60,934 | def get_by_symbol ( self , symbol : str ) -> Commodity : full_symbol = self . __parse_gc_symbol ( symbol ) query = ( self . query . filter ( Commodity . mnemonic == full_symbol [ "mnemonic" ] ) ) if full_symbol [ "namespace" ] : query = query . filter ( Commodity . namespace == full_symbol [ "namespace" ] ) return query . first ( ) | Returns the commodity with the given symbol . If more are found an exception will be thrown . |
60,935 | def get_stocks ( self , symbols : List [ str ] ) -> List [ Commodity ] : query = ( self . query . filter ( Commodity . mnemonic . in_ ( symbols ) ) ) . order_by ( Commodity . namespace , Commodity . mnemonic ) return query . all ( ) | loads stocks by symbol |
60,936 | def get_aggregate ( self , security : Commodity ) -> SecurityAggregate : assert security is not None assert isinstance ( security , Commodity ) return SecurityAggregate ( self . book , security ) | Returns the aggregate for the entity |
60,937 | def get_aggregate_for_symbol ( self , symbol : str ) -> SecurityAggregate : security = self . get_by_symbol ( symbol ) if not security : raise ValueError ( f"Security not found in GC book: {symbol}!" ) return self . get_aggregate ( security ) | Returns the aggregate for the security found by full symbol |
60,938 | def query ( self ) : query = ( self . book . session . query ( Commodity ) . filter ( Commodity . namespace != "CURRENCY" , Commodity . namespace != "template" ) ) return query | Returns the base query which filters out data for all queries . |
60,939 | def book ( self ) -> Book : if not self . __book : book_uri = self . settings . database_path self . __book = Database ( book_uri ) . open_book ( for_writing = self . __for_writing ) return self . __book | GnuCash Book . Opens the book or creates an database based on settings . |
60,940 | def accounts ( self ) -> AccountsAggregate : if not self . __accounts_aggregate : self . __accounts_aggregate = AccountsAggregate ( self . book ) return self . __accounts_aggregate | Returns the Accounts aggregate |
60,941 | def currencies ( self ) -> CurrenciesAggregate : if not self . __currencies_aggregate : self . __currencies_aggregate = CurrenciesAggregate ( self . book ) return self . __currencies_aggregate | Returns the Currencies aggregate |
60,942 | def securities ( self ) : if not self . __securities_aggregate : self . __securities_aggregate = SecuritiesAggregate ( self . book ) return self . __securities_aggregate | Returns securities aggregate |
60,943 | def get_currency_symbols ( self ) -> List [ str ] : result = [ ] currencies = self . currencies . get_book_currencies ( ) for cur in currencies : result . append ( cur . mnemonic ) return result | Returns the used currencies symbols as an array |
60,944 | def load_jinja_template ( file_name ) : original_script_path = sys . argv [ 0 ] script_dir = os . path . dirname ( original_script_path ) from jinja2 import Environment , FileSystemLoader env = Environment ( loader = FileSystemLoader ( script_dir ) ) template = env . get_template ( file_name ) return template | Loads the jinja2 HTML template from the given file . Assumes that the file is in the same directory as the script . |
60,945 | def get_days_in_month ( year : int , month : int ) -> int : month_range = calendar . monthrange ( year , month ) return month_range [ 1 ] | Returns number of days in the given month . 1 - based numbers as arguments . i . e . November = 11 |
60,946 | def get_from_gnucash26_date ( date_str : str ) -> date : date_format = "%Y%m%d" result = datetime . strptime ( date_str , date_format ) . date ( ) return result | Creates a datetime from GnuCash 2 . 6 date string |
60,947 | def parse_period ( period : str ) : period = period . split ( " - " ) date_from = Datum ( ) if len ( period [ 0 ] ) == 10 : date_from . from_iso_date_string ( period [ 0 ] ) else : date_from . from_iso_long_date ( period [ 0 ] ) date_from . start_of_day ( ) date_to = Datum ( ) if len ( period [ 1 ] ) == 10 : date_to . from_iso_date_string ( period [ 1 ] ) else : date_to . from_iso_long_date ( period [ 1 ] ) date_to . end_of_day ( ) return date_from . value , date_to . value | parses period from date range picker . The received values are full ISO date |
60,948 | def get_period ( date_from : date , date_to : date ) -> str : assert isinstance ( date_from , date ) assert isinstance ( date_to , date ) str_from : str = date_from . isoformat ( ) str_to : str = date_to . isoformat ( ) return str_from + " - " + str_to | Returns the period string from the given dates |
60,949 | def load_json_file_contents ( path : str ) -> str : assert isinstance ( path , str ) content = None file_path = os . path . abspath ( path ) content = fileutils . read_text_from_file ( file_path ) json_object = json . loads ( content ) content = json . dumps ( json_object , sort_keys = True , indent = 4 ) return content | Loads contents from a json file |
60,950 | def validate_json ( data : str ) : result = None try : result = json . loads ( data ) except ValueError as error : log ( ERROR , "invalid json: %s" , error ) return result | Validate JSON by parsing string data . Returns the json dict . |
60,951 | def get_sql ( query ) : sql = str ( query . statement . compile ( dialect = sqlite . dialect ( ) , compile_kwargs = { "literal_binds" : True } ) ) return sql | Returns the sql query |
60,952 | def save_to_temp ( content , file_name = None ) : temp_dir = tempfile . gettempdir ( ) out_file = os . path . join ( temp_dir , file_name ) file = open ( out_file , 'w' ) file . write ( content ) file . close ( ) return out_file | Save the contents into a temp file . |
60,953 | def read_book_uri_from_console ( ) : db_path : str = input ( "Enter book_url or leave blank for the default settings value: " ) if db_path : if db_path . startswith ( "sqlite://" ) : db_path_uri = db_path else : db_path_uri = "file:///" + db_path else : cfg = settings . Settings ( ) db_path_uri = cfg . database_uri return db_path_uri | Prompts the user to enter book url in console |
60,954 | def run_report_from_console ( output_file_name , callback ) : print ( "The report uses a read-only access to the book." ) print ( "Now enter the data or ^Z to continue:" ) result = callback ( ) output = save_to_temp ( result , output_file_name ) webbrowser . open ( output ) | Runs the report from the command line . Receives the book url from the console . |
60,955 | def get_dividend_sum_for_symbol ( book : Book , symbol : str ) : svc = SecuritiesAggregate ( book ) security = svc . get_by_symbol ( symbol ) sec_svc = SecurityAggregate ( book , security ) accounts = sec_svc . get_income_accounts ( ) total = Decimal ( 0 ) for account in accounts : income = get_dividend_sum ( book , account ) total += income return total | Calculates all income for a symbol |
60,956 | def import_file ( filename ) : file_path = os . path . abspath ( filename ) log ( DEBUG , "Loading prices from %s" , file_path ) prices = __read_prices_from_file ( file_path ) with BookAggregate ( for_writing = True ) as svc : svc . prices . import_prices ( prices ) print ( "Saving book..." ) svc . book . save ( ) | Imports the commodity prices from the given . csv file . |
60,957 | def generate_report ( book_url ) : shares_no = None avg_price = None stock_template = templates . load_jinja_template ( "stock_template.html" ) stock_rows = "" with piecash . open_book ( book_url , readonly = True , open_if_lock = True ) as book : all_stocks = portfoliovalue . get_all_stocks ( book ) for stock in all_stocks : for_date = datetime . today ( ) . date model = portfoliovalue . get_stock_model_from ( book , stock , for_date ) stock_rows += stock_template . render ( model ) template = templates . load_jinja_template ( "template.html" ) result = template . render ( ** locals ( ) ) return result | Generates an HTML report content . |
60,958 | def main ( symbol : str ) : print ( "Displaying the balance for" , symbol ) with BookAggregate ( ) as svc : security = svc . book . get ( Commodity , mnemonic = symbol ) sec_svc = SecurityAggregate ( svc . book , security ) shares_no = sec_svc . get_quantity ( ) print ( "Quantity:" , shares_no ) avg_price = sec_svc . get_avg_price ( ) print ( "Average price:" , avg_price ) | Displays the balance for the security symbol . |
60,959 | def generate_report ( book_url ) : with piecash . open_book ( book_url , readonly = True , open_if_lock = True ) as book : accounts = [ acc . fullname for acc in book . accounts ] return f | Generates the report HTML . |
60,960 | def get_project_files ( ) : if is_git_project ( ) : return get_git_project_files ( ) project_files = [ ] for top , subdirs , files in os . walk ( '.' ) : for subdir in subdirs : if subdir . startswith ( '.' ) : subdirs . remove ( subdir ) for f in files : if f . startswith ( '.' ) : continue project_files . append ( os . path . join ( top , f ) ) return project_files | Retrieve a list of project files ignoring hidden files . |
60,961 | def print_success_message ( message ) : try : import colorama print ( colorama . Fore . GREEN + message + colorama . Fore . RESET ) except ImportError : print ( message ) | Print a message indicating success in green color to STDOUT . |
60,962 | def print_failure_message ( message ) : try : import colorama print ( colorama . Fore . RED + message + colorama . Fore . RESET , file = sys . stderr ) except ImportError : print ( message , file = sys . stderr ) | Print a message indicating failure in red color to STDERR . |
60,963 | def main ( ) : importer = ExchangeRatesImporter ( ) print ( "####################################" ) latest_rates_json = importer . get_latest_rates ( ) mapper = None rates = mapper . map_to_model ( latest_rates_json ) print ( "####################################" ) print ( "importing rates into gnucash..." ) with BookAggregate ( for_writing = False ) as svc : svc . currencies . import_fx_rates ( rates ) print ( "####################################" ) print ( "displaying rates from gnucash..." ) importer . display_gnucash_rates ( ) | Default entry point |
60,964 | def generate_asset_allocation_report ( book_url ) : model = load_asset_allocation_model ( book_url ) template = templates . load_jinja_template ( "report_asset_allocation.html" ) result = template . render ( model = model ) return result | The otput is generated here . Separated from the generate_report function to allow executing from the command line . |
60,965 | def parse_value ( self , value_string : str ) : self . value = Decimal ( value_string ) return self . value | Parses the amount string . |
60,966 | def parse ( self , csv_row : str ) : self . date = self . parse_euro_date ( csv_row [ 2 ] ) self . symbol = csv_row [ 0 ] self . value = self . parse_value ( csv_row [ 1 ] ) return self | Parses the . csv row into own values |
60,967 | def load_cash_balances_with_children ( self , root_account_fullname : str ) : assert isinstance ( root_account_fullname , str ) svc = AccountsAggregate ( self . book ) root_account = svc . get_by_fullname ( root_account_fullname ) if not root_account : raise ValueError ( "Account not found" , root_account_fullname ) accounts = self . __get_all_child_accounts_as_array ( root_account ) model = { } for account in accounts : if account . commodity . namespace != "CURRENCY" or account . placeholder : continue currency_symbol = account . commodity . mnemonic if not currency_symbol in model : currency_record = { "name" : currency_symbol , "total" : 0 , "rows" : [ ] } model [ currency_symbol ] = currency_record else : currency_record = model [ currency_symbol ] balance = account . get_balance ( ) row = { "name" : account . name , "fullname" : account . fullname , "currency" : currency_symbol , "balance" : balance } currency_record [ "rows" ] . append ( row ) total = Decimal ( currency_record [ "total" ] ) total += balance currency_record [ "total" ] = total return model | loads data for cash balances |
60,968 | def get_balance ( self ) : on_date = Datum ( ) on_date . today ( ) return self . get_balance_on ( on_date . value ) | Current account balance |
60,969 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) . filter ( Split . account == self . account ) ) return query | Returns all the splits in the account |
60,970 | def get_transactions ( self , date_from : datetime , date_to : datetime ) -> List [ Transaction ] : assert isinstance ( date_from , datetime ) assert isinstance ( date_to , datetime ) dt_from = Datum ( ) dt_from . from_datetime ( date_from ) dt_from . start_of_day ( ) dt_to = Datum ( ) dt_to . from_datetime ( date_to ) dt_to . end_of_day ( ) query = ( self . book . session . query ( Transaction ) . join ( Split ) . filter ( Split . account_guid == self . account . guid ) . filter ( Transaction . post_date >= dt_from . date , Transaction . post_date <= dt_to . date ) . order_by ( Transaction . post_date ) ) return query . all ( ) | Returns account transactions |
60,971 | def __get_all_child_accounts_as_array ( self , account : Account ) -> List [ Account ] : result = [ ] result . append ( account ) for child in account . children : sub_accounts = self . __get_all_child_accounts_as_array ( child ) result += sub_accounts return result | Returns the whole tree of child accounts in a list |
60,972 | def find_by_name ( self , term : str , include_placeholders : bool = False ) -> List [ Account ] : query = ( self . query . filter ( Account . name . like ( '%' + term + '%' ) ) . order_by ( Account . name ) ) if not include_placeholders : query = query . filter ( Account . placeholder == 0 ) return query . all ( ) | Search for account by part of the name |
60,973 | def get_aggregate_by_id ( self , account_id : str ) -> AccountAggregate : account = self . get_by_id ( account_id ) return self . get_account_aggregate ( account ) | Returns the aggregate for the given id |
60,974 | def get_by_fullname ( self , fullname : str ) -> Account : query = ( self . book . session . query ( Account ) ) all_accounts = query . all ( ) for account in all_accounts : if account . fullname == fullname : return account return None | Loads account by full name |
60,975 | def get_account_id_by_fullname ( self , fullname : str ) -> str : account = self . get_by_fullname ( fullname ) return account . guid | Locates the account by fullname |
60,976 | def get_all_children ( self , fullname : str ) -> List [ Account ] : root_acct = self . get_by_fullname ( fullname ) if not root_acct : raise NameError ( "Account not found in book!" ) acct_agg = self . get_account_aggregate ( root_acct ) result = acct_agg . get_all_child_accounts_as_array ( ) return result | Returns the whole child account tree for the account with the given full name |
60,977 | def get_all ( self ) -> List [ Account ] : return [ account for account in self . book . accounts if account . parent . name != "Template Root" ] | Returns all book accounts as a list excluding templates . |
60,978 | def get_favourite_accounts ( self ) -> List [ Account ] : from gnucash_portfolio . lib . settings import Settings settings = Settings ( ) favourite_accts = settings . favourite_accounts accounts = self . get_list ( favourite_accts ) return accounts | Provides a list of favourite accounts |
60,979 | def get_favourite_account_aggregates ( self ) -> List [ AccountAggregate ] : accounts = self . get_favourite_accounts ( ) aggregates = [ ] for account in accounts : aggregate = self . get_account_aggregate ( account ) aggregates . append ( aggregate ) return aggregates | Returns the list of aggregates for favourite accounts |
60,980 | def get_by_id ( self , acct_id ) -> Account : return self . book . get ( Account , guid = acct_id ) | Loads an account entity |
60,981 | def get_by_name ( self , name : str ) -> List [ Account ] : return self . get_by_name_from ( self . book . root , name ) | Searches accounts by name |
60,982 | def get_by_name_from ( self , root : Account , name : str ) -> List [ Account ] : result = [ ] if root . name == name : result . append ( root ) for child in root . children : child_results = self . get_by_name_from ( child , name ) result += child_results return result | Searches child accounts by name starting from the given account |
60,983 | def get_list ( self , ids : List [ str ] ) -> List [ Account ] : query = ( self . query . filter ( Account . guid . in_ ( ids ) ) ) return query . all ( ) | Loads accounts by the ids passed as an argument |
60,984 | def query ( self ) : query = ( self . book . session . query ( Account ) . join ( Commodity ) . filter ( Commodity . namespace != "template" ) . filter ( Account . type != AccountType . root . value ) ) return query | Main accounts query |
60,985 | def search ( self , name : str = None , acc_type : str = None ) : query = self . query if name is not None : query = query . filter ( Account . name == name ) if acc_type is not None : acc_type = acc_type . upper ( ) query = query . filter ( Account . type == acc_type ) return query . all ( ) | Search accounts by passing parameters . name = exact name name_part = part of name parent_id = id of the parent account type = account type |
60,986 | def get_price_as_of ( self , stock : Commodity , on_date : datetime ) : prices = PriceDbApplication ( ) prices . get_prices_on ( on_date . date ( ) . isoformat ( ) , stock . namespace , stock . mnemonic ) | Gets the latest price on or before the given date . |
60,987 | def import_price ( self , price : PriceModel ) : symbol = price . symbol if "." in symbol : symbol = price . symbol . split ( "." ) [ 0 ] stock = SecuritiesAggregate ( self . book ) . get_by_symbol ( symbol ) if stock is None : logging . warning ( "security %s not found in book." , price . symbol ) return False existing_prices = stock . prices . filter ( Price . date == price . datetime . date ( ) ) . all ( ) if not existing_prices : self . __create_price_for ( stock , price ) else : logging . warning ( "price already exists for %s on %s" , stock . mnemonic , price . datetime . strftime ( "%Y-%m-%d" ) ) existing_price = existing_prices [ 0 ] existing_price . value = price . value return True | Import individual price |
60,988 | def __create_price_for ( self , commodity : Commodity , price : PriceModel ) : logging . info ( "Adding a new price for %s, %s, %s" , commodity . mnemonic , price . datetime . strftime ( "%Y-%m-%d" ) , price . value ) sec_svc = SecurityAggregate ( self . book , commodity ) currency = sec_svc . get_currency ( ) if currency != price . currency : raise ValueError ( "Requested currency does not match the currency previously used" , currency , price . currency ) new_price = Price ( commodity , currency , price . datetime . date ( ) , price . value , source = "Finance::Quote" ) commodity . prices . append ( new_price ) | Creates a new Price entry in the book for the given commodity |
60,989 | def get_splits_query ( self ) : query = ( self . book . session . query ( Split ) . filter ( Split . transaction_guid == self . transaction . guid ) ) return query | Returns the query for related splits |
60,990 | def generate_report ( book_url , fund_ids : StringOption ( section = "Funds" , sort_tag = "c" , documentation_string = "Comma-separated list of fund ids." , default_value = "8123,8146,8148,8147" ) ) : return render_report ( book_url , fund_ids ) | Generates the report output |
60,991 | def searchAccount ( searchTerm , book ) : print ( "Search results:\n" ) found = False for account in book . accounts : if searchTerm . lower ( ) in account . fullname . lower ( ) : print ( account . fullname ) found = True if not found : print ( "Search term not found in account names." ) | Searches through account names |
60,992 | def display_db_info ( self ) : with self . open_book ( ) as book : default_currency = book . default_currency print ( "Default currency is " , default_currency . mnemonic ) | Displays some basic info about the GnuCash book |
60,993 | def open_book ( self , for_writing = False ) -> piecash . Book : filename = None file_url = urllib . parse . urlparse ( self . filename ) if file_url . scheme == "file" or file_url . scheme == "sqlite" : filename = file_url . path [ 1 : ] else : filename = self . filename if not os . path . isfile ( filename ) : log ( WARN , "Database %s requested but not found. Creating an in-memory book." , filename ) return self . create_book ( ) access_type = "read/write" if for_writing else "readonly" log ( INFO , "Using %s in %s mode." , filename , access_type ) file_path = path . abspath ( filename ) if not for_writing : book = piecash . open_book ( file_path , open_if_lock = True ) else : book = piecash . open_book ( file_path , open_if_lock = True , readonly = False ) return book | Opens the database . Call this using with . If database file is not found an in - memory database will be created . |
60,994 | def read_text_from_file ( path : str ) -> str : with open ( path ) as text_file : content = text_file . read ( ) return content | Reads text file contents |
60,995 | def save_text_to_file ( content : str , path : str ) : with open ( path , mode = 'w' ) as text_file : text_file . write ( content ) | Saves text to file |
60,996 | def get_amount_in_base_currency ( self , currency : str , amount : Decimal ) -> Decimal : assert isinstance ( amount , Decimal ) if currency == self . get_default_currency ( ) . mnemonic : return amount agg = self . get_currency_aggregate_by_symbol ( currency ) if not agg : raise ValueError ( f"Currency not found: {currency}!" ) rate_to_base = agg . get_latest_price ( ) if not rate_to_base : raise ValueError ( f"Latest price not found for {currency}!" ) assert isinstance ( rate_to_base . value , Decimal ) result = amount * rate_to_base . value return result | Calculates the amount in base currency |
60,997 | def get_default_currency ( self ) -> Commodity : result = None if self . default_currency : result = self . default_currency else : def_currency = self . __get_default_currency ( ) self . default_currency = def_currency result = def_currency return result | returns the book default currency |
60,998 | def get_book_currencies ( self ) -> List [ Commodity ] : query = ( self . currencies_query . order_by ( Commodity . mnemonic ) ) return query . all ( ) | Returns currencies used in the book |
60,999 | def get_currency_aggregate_by_symbol ( self , symbol : str ) -> CurrencyAggregate : currency = self . get_by_symbol ( symbol ) result = self . get_currency_aggregate ( currency ) return result | Creates currency aggregate for the given currency symbol |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.