def filterAttributeDataSet(self, dataToBeFiltered): filteredData = [] i = 0 for data in dataToBeFiltered: assetObj = Asset(data['resourceId']) # Find out whether there are any attributes tied to the asset: possibleAttributesList = assetObj.fetchPossibleAttributesTypes() if len(possibleAttributesList['attributeType']) > 0: # Fetch attributes for the resourceId attributesResponse = assetObj.fetchAttributes() attributesResponseList = attributesResponse[ 'attributeReference'] # Loop through the attributesResponseList to check whether specified filterValue has been set for listIndex in range(0, len(attributesResponseList)): attributeResponseMap = attributesResponseList[listIndex] attributeType = attributeResponseMap['labelReference'][ 'signifier'] if attributeType == self.parameterMap[ 'attributeTypeEquals']: filteredData.append(data) i += 1 return filteredData
def op_regions(asset, region, output='json', date=None, srs=None, srs_type='unknown', resample=None, region_srs=None, region_srs_type='unknown', reducers=None, region_type='json', **kwargs): outputDriver = Outputs.getDriver(output) ## Parse the region R = Region(region) if region_srs: region_SR = SpatialReference.parse(region_srs, region_srs_type) R.geom.AssignSpatialReference(region_SR) DS = Asset(asset) if srs: SR = SpatialReference.parse(srs, srs_type) DS = DS.warpTo(SR, resample) data, weights = DS.getRegion(R, date, resample) if reducers: data = Reducers.apply(reducers, data, weights) data = data.tolist() return outputDriver(data, ds=DS)
def MakeOrders(self, currentPortfolio, targetPortfolio): orders = [] for currentAsset in currentPortfolio: # if exists in target, buy/sell to get to target tgtAssetArray = [ a for a in targetPortfolio if a._symbol == currentAsset._symbol ] if len(tgtAssetArray) > 0: symbol = tgtAssetArray[0]._symbol price = tgtAssetArray[0]._sharePrice numShares = tgtAssetArray[ 0]._numShares - currentAsset._numShares if numShares > 0: orders.append(Order("Buy", Asset(symbol, price, numShares))) elif numShares < 0: orders.append( Order("Sell", Asset(symbol, price, -numShares))) else: # else, sell all orders.append(Order("Sell", currentAsset)) for targetAsset in targetPortfolio: # if not exists in current, buy all if not any([ a for a in currentPortfolio if a._symbol == targetAsset._symbol ]): orders.append(Order("Buy", targetAsset)) return orders
def filterComplexRelationDataSet(self, dataToBeFiltered): filteredData = [] for data in dataToBeFiltered: #Fetch relations for the resourceId assetObj = Asset(data['resourceId']) assetComplexRelationMapList = assetObj.fetchComplexRelations() if assetComplexRelationMapList != 'No Relations Found': for assetComplexRelationMap in assetComplexRelationMapList: #Loop through each inner map in assetComplexRelationMap for complexRelationMapList in assetComplexRelationMap[ 'relationReference']: # Extract complex relation map from inner complexRelationMap if len(complexRelationMapList) > 0: complexRelationMap = complexRelationMapList[ 'typeReference'] complexRelationHeadTerm = complexRelationMap[ 'headTerm'] complexRelationName = complexRelationHeadTerm[ 'signifier'] # Check whether complex relation type exists for an asset if complexRelationName in self.parameterList[ 'complexRelationName']: if data not in filteredData: filteredData.append(data) return filteredData
def test(): import sys import OpLookup import Auth import Role try: username = sys.argv[1] asset_id = int (sys.argv[2]) asset = Asset (asset_id) user = Auth.get_user(username) roles = Role.get_user_roles (username) params = { 'roles': roles, 'user_id': user['id']} except IndexError: print 'Required test parameters: user sample_asset_id' sys.exit(1) # Create asset for testing new_asset = Asset () new_asset._db = asset._db new_asset._tags = asset._tags flag = id (new_asset) new_asset['title'] = flag oa = OpAsset (new_asset, params) assert oa print '#1 OpAsset (): Creation OK' ret = oa.add() assert ret == True print '#2 OpAsset.add(): Addition OK' ol = OpLookup.OpLookup () new_asset_id = ol({'title': flag})[0] new_asset = Asset (new_asset_id) assert int(new_asset['title']) == int(flag) print '#3 OpAsset.add(): Retrieval after addition OK' oa = OpAsset (new_asset, params) assert oa print '#4 OpAsset (new_asset): Creation after retrieval OK' new_asset['description'] = flag oa = OpAsset (new_asset, params) ret = oa.update() assert ret == True print '#5 OpAsset.update(): Modification OK' ol = OpLookup.OpLookup () updated_asset_id = ol({'description': int(flag)})[0] updated_asset = Asset (new_asset_id) assert int(updated_asset['description']) == int(flag) print '#6 OpAsset.update(): Retrieval after modification OK' assert updated_asset['id'] == new_asset['id'] print '#7 OpAsset.update(): Comparison with original OK' ret = oa.delete() assert ret['ret'] == True print '#8 OpAsset.delete(): Deletion OK'
def main(project_name_param_, assets_param, assets_out_of_scope): project_name = project_name_param_ project = Project(project_name) assets = assets_param project.set_assets(assets) project.save_project() scan_instance = Scan(project) scan_instance.save_scan() for asset in assets: asset_instance = Asset(scan_instance, asset) asset_subdomains = asset_instance.get_subdomains() asset_id = asset_instance.save_asset() for subdomain in asset_subdomains: subdomain_instance = Subdomain(asset_id, subdomain, assets_out_of_scope) subdomain_links = subdomain_instance.parse_links() subdomain_id = subdomain_instance.save_subdomain() for link in subdomain_links: if link in assets_out_of_scope: continue link_instance = Link(subdomain_id, link) link_instance.process_link() link_id = link_instance.save_link() forms = link_instance.forms for form_index in range(len(forms)): form = forms[form_index] form_instance = Form(link_id, form, form_index) form_instance.save_form()
def op_window(asset, window, window_size, date, srs=None, output='png', srs_type='unknown', resample=None, reducers=None, **kwargs): outputDriver = Outputs.getDriver(output) DS = Asset(asset) if srs: SR = SpatialReference.parse(srs, srs_type) DS = DS.warpTo(SR, resample) driver = gdal.GetDriverByName('VRT') driver.CreateCopy('/data/apicache/' + asset + '_warped.vrt', DS.ds) data = DS.getWindow(window, date, window_size, resample) if reducers: data = Reducers.apply(reducers, data) return outputDriver(data, ds=DS) '''Returns bounds of the given tile in EPSG:900913 coordinates'''
def filterTargetDataSet(self, filterAttributeType, dataToBeFiltered): filteredData = [] for key in self.parameterMap.keys(): filterValue = self.parameterMap[key] if str.upper(key).find("ATTRIBUTEVALUEEQUALS") != -1: for data in dataToBeFiltered: # Find the resourceId assetObj = Asset(data['resourceId']) attributesResponse = assetObj.fetchAttributes() attributesResponseList = attributesResponse[ 'attributeReference'] # Loop through the attributesResponseList to check whether specified filterValue has been set for listIndex in range(0, len(attributesResponseList)): attributeResponseMap = attributesResponseList[ listIndex] # key = attributeResponseMap['resourceId'] + ' -> ' + attributeResponseMap['labelReference']['signifier'] attributeType = attributeResponseMap['labelReference'][ 'signifier'] if attributeType == filterAttributeType: cleanedValue = AttributeFilter.cleanhtml( attributeResponseMap['value']) if cleanedValue == filterValue: filteredData.append(data) return filteredData
def execute_order(initial_cash, _asset_list): asset_list = [] for asset in _asset_list: name = asset[0] #e.g. Spotify ticker = asset[1] #e.g. "SPOT" asset_level = asset[2] #e.g. 2 (for already having 2 shares) _asset = Asset(name, ticker) order = _asset.execute_order(asset_level, initial_cash) #_asset.plot_projections() asset_list.append([_asset, order]) return asset_list
def __init__(self, parent, title="PyAsset", cfgFile="", assetFile=""): self.parent = parent self.frame = self self.assets = AssetList(self) self.bills = BillList() self.cur_asset = Asset(name=assetFile) self.edited = False self.payType = "" self.ref_date = None self.netpay = "" self.payDepositAcct = "" self.cfgFile = copy.deepcopy(cfgFile) super(AssetFrame, self).__init__(parent, title=title) if self.readConfigFile(cfgFile): valid_date_seps = ['/', '-'] for j in range(len(valid_date_seps)): date_sep = valid_date_seps[j] date_fields = self.dateFormat.split(valid_date_seps[j]) if len(date_fields) == 3: break if len(date_fields) == 3: Date.set_global_date_format(self, self.dateFormat) Date.set_global_date_sep(self, date_sep) self.curr_date = Date.set_curr_date(self) self.proj_date = Date.set_proj_date(self, "") Date.set_global_curr_date(self, self.curr_date) Date.set_global_proj_date(self, self.proj_date) Date.set_curr_paydate(self) Date.set_next_paydate(self) self.make_widgets() self.filename = assetFile if self.filename == "": d = wx.FileDialog(self, "Open", "", "", "*.qif", wx.FD_OPEN) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() self.filename = os.path.join(dir, fname) if self.filename: latest_assets = qif.load_file(self, self.filename) self.process_asset_list(latest_assets) else: error = 'Badly formatted date format sting: %s - Aborting!\n' self.DisplayMsg(error) else: error = cfgFile + ' does not exist / cannot be opened!! - Aborting\n' self.DisplayMsg(error)
def test(): import sys import OpLookup import Auth import Role try: username = sys.argv[1] asset_id = int(sys.argv[2]) asset = Asset(asset_id) user = Auth.get_user(username) roles = Role.get_user_roles(username) params = {'roles': roles, 'user_id': user['id']} except IndexError: print 'Required test parameters: user sample_asset_id' sys.exit(1) # Create asset for testing new_asset = Asset() new_asset._db = asset._db new_asset._tags = asset._tags flag = id(new_asset) new_asset['title'] = flag oa = OpAsset(new_asset, params) assert oa print '#1 OpAsset (): Creation OK' ret = oa.add() assert ret == True print '#2 OpAsset.add(): Addition OK' ol = OpLookup.OpLookup() new_asset_id = ol({'title': flag})[0] new_asset = Asset(new_asset_id) assert int(new_asset['title']) == int(flag) print '#3 OpAsset.add(): Retrieval after addition OK' oa = OpAsset(new_asset, params) assert oa print '#4 OpAsset (new_asset): Creation after retrieval OK' new_asset['description'] = flag oa = OpAsset(new_asset, params) ret = oa.update() assert ret == True print '#5 OpAsset.update(): Modification OK' ol = OpLookup.OpLookup() updated_asset_id = ol({'description': int(flag)})[0] updated_asset = Asset(new_asset_id) assert int(updated_asset['description']) == int(flag) print '#6 OpAsset.update(): Retrieval after modification OK' assert updated_asset['id'] == new_asset['id'] print '#7 OpAsset.update(): Comparison with original OK' ret = oa.delete() assert ret['ret'] == True print '#8 OpAsset.delete(): Deletion OK'
def del_asset(): """Delete asset""" # Target asset asset_id = CTK.request.url.split('/')[-1] try: asset_id = __check_asset_id(asset_id) asset = Asset(asset_id) if not asset['id']: return CTK.HTTP_Redir('/') except: return CTK.HTTP_Redir('/') # Authentication fail_admin = Auth.assert_is_role(Role.ROLE_ADMIN) user_id = Auth.get_user_id() is_creator = (asset['creator_id'] == user_id) if fail_admin and not is_creator: return fail_admin op = OpAsset(asset) result = op.delete() if result['ret'] == False: return default() if result['type'] == 'total': return CTK.HTTP_Redir(LOCATION) return default(ERROR_IN_USE)
def test_update_alias(self): con = Connection("http://127.0.0.1:9888") response = Asset.update_alias( con, "d05b4cc1615509bf0d58cda7be4c5da43a33cc920ae439eaaac6507853e3cbf1", "shengsheng") print(response)
def interest_function(): for x in interest_stocks: print(x) for i in range(len(interest_stocks[x])): print(interest_stocks[x][i]) interest_stocks[x][i] = Asset(interest_stocks[x][i][0], interest_stocks[x][i][1])
def initializePortfolio(): write("Initializing Portfolio... ") flush() items = config.getElementsByTagName('item') indices = config.getElementsByTagName('index') for item in items: tickerNode = item.getElementsByTagName('ticker') symbol = tickerNode[0].firstChild.data averagePriceNode = item.getElementsByTagName('averagePrice') averagePrice = float(averagePriceNode[0].firstChild.data) shareCountNode = item.getElementsByTagName('shareCount') shareCount = int(shareCountNode[0].firstChild.data) name = item.getAttribute('name') asset = Asset(symbol, name, averagePrice, shareCount) portfolio.addAsset(asset) for index in indices: tickerNode = index.getElementsByTagName('ticker') symbol = tickerNode[0].firstChild.data name = index.getAttribute('name') indexAsset = Index(symbol, name) portfolio.addIndex(indexAsset) write("done") flush()
def GetTargetPortfolio(self): if (not self.IsInMarket()): return {} closes = {} momentums = {} for symbol in self._symbols: data = self._repo.GetData(symbol) momentum = self.Momentum(data['Close']) if momentum > 1: closes[symbol] = data momentums[symbol] = momentum buyThreshold = sorted( momentums.values())[-min(self._maxNumPositions, len(momentums))] symbolsToBuy = { k: v for k, v in momentums.items() if v >= buyThreshold } assets = [] for symbol in symbolsToBuy: df = closes[symbol] sharePrice = df['Close'][-1] if (symbol, self._tradingDay) in closes[symbol].index: sharePrice = df.loc[(symbol, Timestamp(self._tradingDay))]['Close'] numShares = int(self._holdingsValue / len(symbolsToBuy) / sharePrice) assets.append(Asset(symbol, sharePrice, numShares)) return assets
def position(self, account: str, contract: Contract, position: float, avgCost: float): super().position(account, contract, position, avgCost) self._positions.append(Asset(contract.symbol, avgCost, position)) print("Position.", account, "Symbol:", contract.symbol, "SecType:", contract.secType, "Currency:", contract.currency, "Position:", position, "Avg cost:", avgCost)
def publish_asset_apply(): # Authentication fail = Auth.assert_is_role(Role.ROLE_PUBLISHER) if fail: return fail acl = ACL() ret = [] for key in CTK.post: if not key.startswith('published_'): continue flag = int(CTK.post[key]) asset_id = key[len('published_'):] asset = Asset(asset_id) if asset['published_flag'] == flag: continue asset['published_flag'] = flag asset['publisher_id'] = Auth.get_user_id() asset['date_available'] = "CURRENT_TIMESTAMP()" op = OpAsset(asset) ret.append(op.update()) if ret[-1] == False: break if asset['published_flag']: acl.set_published_asset_acl(asset, True) else: acl.set_published_asset_acl(asset, False) if False in ret: return {'ret': "error"} return {'ret': "ok"}
def add_asset_apply (): # Authentication fail = Auth.assert_is_role (Role.ROLE_UPLOADER) if fail: return fail asset = Asset() asset['creator_id'] = Auth.get_user_id() asset['version'] = 1 if 'parts' in CTK.post: parts = CTK.post['parts'] if parts: parts = Validations.split_list (CTK.post['parts']) asset._parts['has_parts_of'] = [int(p) for p in parts] if 'parent_id' in CTK.post: asset._parent_id = int(CTK.post['parent_id']) for key in ['asset_types_id', 'licenses_id', 'title', 'description', 'version', 'language', 'subject']: if key in CTK.post: asset[key] = CTK.post[key] filenames = [] if 'name' in CTK.post and 'ref' in CTK.post: tmp_name = CTK.post['ref'] src_name = CTK.post['name'] filenames = Upload.process_file (tmp_name, src_name) #Collection if len(filenames) > 1: col_id = create_collection (src_name) asset['collections_id'] = col_id elif len(filenames) == 1: info = Upload.get_info (filenames[0]) #If unique file is broken if not info['filename']: return {'ret': "ok", 'redirect': '%s/broken' %(LOCATION)} ret = create_assets (asset, filenames) if False in ret: return {'ret': "error"} return {'ret': "ok", 'redirect': LOCATION}
def add_asset_apply(): # Authentication fail = Auth.assert_is_role(Role.ROLE_UPLOADER) if fail: return fail asset = Asset() asset['creator_id'] = Auth.get_user_id() asset['version'] = 1 if 'parts' in CTK.post: parts = CTK.post['parts'] if parts: parts = Validations.split_list(CTK.post['parts']) asset._parts['has_parts_of'] = [int(p) for p in parts] if 'parent_id' in CTK.post: asset._parent_id = int(CTK.post['parent_id']) for key in [ 'asset_types_id', 'licenses_id', 'title', 'description', 'version', 'language', 'subject' ]: if key in CTK.post: asset[key] = CTK.post[key] filenames = [] if 'name' in CTK.post and 'ref' in CTK.post: tmp_name = CTK.post['ref'] src_name = CTK.post['name'] filenames = Upload.process_file(tmp_name, src_name) #Collection if len(filenames) > 1: col_id = create_collection(src_name) asset['collections_id'] = col_id elif len(filenames) == 1: info = Upload.get_info(filenames[0]) #If unique file is broken if not info['filename']: return {'ret': "ok", 'redirect': '%s/broken' % (LOCATION)} ret = create_assets(asset, filenames) if False in ret: return {'ret': "error"} return {'ret': "ok", 'redirect': LOCATION}
def edit_asset_apply(): # Authentication fail = Auth.assert_is_role(Role.ROLE_EDITOR) if fail: return fail asset_id = CTK.post.pop('asset_id') if not asset_id: return CTK.HTTP_Error(400) acl = ACL() editable = acl.filter_assets("ed", [asset_id]) if not int(asset_id) in editable: return CTK.HTTP_Error(401) # Update the asset asset = Asset(asset_id) asset['edited_flag'] = 0 asset['creator_id'] = "%s" % (Auth.get_user_id()) sql_values = [] for key in [ 'asset_types_id', 'licenses_id', 'title', 'description', 'language', 'subject' ]: if CTK.post[key]: asset[key] = CTK.post[key] # Always evolve the version number post_version = asset['version'] if 'version' in CTK.post: post_version = int(CTK.post['version']) if post_version <= asset['version']: asset['version'] += 1 else: asset['version'] = post_version # Duplicate the attached file try: attachment = File.clone_file(asset._file) asset._file = attachment except IOError, e: # If file copying is not possible, report and abort msg = 'File duplication could not be performed while editing asset ID %s.' % ( asset_id) msg += '\n%s\n' % (str(e)) print msg return {'ret': "error"}
def purchase(self, symbol, ticker, num, dayIdx, ignoreCapital=False, field='adj_close'): price = ticker.getData(field, dayIdx) asset = self.assets.get(symbol) if not asset: asset = Asset() if not ignoreCapital and self.capital < price * num: return False netCost = asset.increasePosition(num, price) self.assets[symbol] = asset self.capital -= netCost
def __init__(self, asset=None, debug_params=None): self.params = debug_params if isinstance(asset, Asset): self._asset = asset elif asset == None or type(asset) == int: self._asset = Asset(asset) else: raise TypeError
def __init__(self): pygame.init() pygame.mixer.init() pygame.display.set_caption("Sokoben") self.asset = Asset() self.background = self.asset.createBackground() self.sound = Sound(self.asset) self.asset.loadImages() self.asset.loadLevels() self.asset.loadSounds() self.asset.loadFonts() self.asset.loadControls() self.levelIndex = 0 self.level = None Controls.add('sound_enabled', self.asset.controls['sound_enabled'], (const.MAPWIDTH * const.TILEWIDTH) - ((1 * 64) + 64), 10, self.sound.enabled) Controls.add('sound_disabled', self.asset.controls['sound_disabled'], (const.MAPWIDTH * const.TILEWIDTH) - ((1 * 64) + 64), 10, not self.sound.enabled) Controls.add('reset', self.asset.controls['reset'], (const.MAPWIDTH * const.TILEWIDTH) - ((2 * 64) + 64), 10, True) Controls.add('undo', self.asset.controls['undo'], (const.MAPWIDTH * const.TILEWIDTH) - ((3 * 64) + 64), 10, True) Controls.add('next', self.asset.controls['next'], (const.MAPWIDTH * const.TILEWIDTH) - ((4 * 64) + 64), 10, True) Controls.add('back', self.asset.controls['back'], (const.MAPWIDTH * const.TILEWIDTH) - ((5 * 64) + 64), 10, True) Controls.add('solution', self.asset.controls['solution'], (const.MAPWIDTH * const.TILEWIDTH) - ((6 * 64) + 64), 10, False) self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode( (const.MAPWIDTH * const.TILEWIDTH, (const.MAPHEIGHT - 1) * const.TILEANGLEHEIGHT + const.TILEHEIGHT))
def edit_asset_apply(): # Authentication fail = Auth.assert_is_role (Role.ROLE_EDITOR) if fail: return fail asset_id = CTK.post.pop('asset_id') if not asset_id: return CTK.HTTP_Error(400) acl = ACL() editable = acl.filter_assets ("ed" , [asset_id]) if not int(asset_id) in editable: return CTK.HTTP_Error(401) # Update the asset asset = Asset(asset_id) asset['edited_flag'] = 0 asset['creator_id'] = "%s" % (Auth.get_user_id()) sql_values = [] for key in ['asset_types_id', 'licenses_id', 'title', 'description', 'language', 'subject']: if CTK.post[key]: asset[key] = CTK.post[key] # Always evolve the version number post_version = asset['version'] if 'version' in CTK.post: post_version = int(CTK.post['version']) if post_version <= asset['version']: asset['version'] += 1 else: asset['version'] = post_version # Duplicate the attached file try: attachment = File.clone_file (asset._file) asset._file = attachment except IOError,e: # If file copying is not possible, report and abort msg = 'File duplication could not be performed while editing asset ID %s.' %(asset_id) msg += '\n%s\n' %(str(e)) print msg return {'ret':"error"}
def testConstructor(self): startTime, endTime, directory = "2016511 07:15", "2016511 07:20", "/home/pi/slides" fileName, fileType, duration, sequence = "Ads.mp4", "video", 225, 1 asset = Asset(startTime, endTime, directory, fileName, fileType, duration, 1.0) checkStartTime = "20160510 21:15" == asset.getStartTime().strftime(TimeZoneConverter.dateFormat) checkEndTime = "20160510 21:20" == asset.getEndTime().strftime(TimeZoneConverter.dateFormat) checkDirectory = directory == asset.getDirectory() checkFileName = fileName == asset.getFileName() checkFileType = fileType == asset.getFileType() checkDuration = duration == asset.getDuration() checkSequence = sequence == asset.getSequence() self.assertTrue(checkStartTime and checkEndTime and checkDirectory and checkFileName and checkFileType and checkDuration and checkSequence, "should be equal")
def makeMap(pathToOriginalImg, name): imgFile = io.open(pathToOriginalImg, mode='rb').read() img = Asset("asset", 'png', imgFile) #lets get the image coords array #first you need to pre process # countedArray = analyzeImage(pathToOriginalImg, 5) raw_array = ProcessImage(pathToOriginalImg, 3) countedArray = CreateSquares(raw_array, 3) thisMap = Map(image=img, VBCoords=countedArray) thisMap.make_file('output/ ' + name + '.zip') thisMap.make_file('output/ ' + name + '.rpmap')
def op_info(asset, output='yaml', **kwargs): outputDriver = Outputs.getDriver(output) info = Asset(asset).metadata # Only yaml natively serializes datetime objects if output.lower() != 'yaml': if 'band-dates' in info: info['band-dates'] = { k: v.isoformat() for k, v in info['band-dates'].iteritems() } return outputDriver(info)
def load_file(self, *args): self.close() self.cur_asset = Asset() self.edited = 0 d = wx.FileDialog(self, "Open", "", "", "*.qif", wx.OPEN) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() self.cur_asset.read_qif(os.path.join(dir, fname)) self.redraw_all(-1) if self.cur_asset.name: self.SetTitle("PyAsset: %s" % self.cur_asset.name) return
def exampleBacktesting(): logger = Logger() logger.addTarget('log/backtestlog.txt') start = datetime.datetime(2019, 2, 10) end = datetime.datetime(2019, 2, 25) interval = datetime.timedelta(days=5) portfolio = Portfolio(1000) portfolio.addAsset(Asset('ethereum', 'ETH')) asset = Asset('ethereum', 'ETH') metrics_list = [ "burn_rate", "transaction_volume", "exchange_funds_flow", "price" ] start_train = datetime.datetime(2018, 12, 1) end_train = datetime.datetime(2019, 1, 30) trader = LinearRegressionTrader(portfolio, logger, 0, metrics_list, asset) trader.train(start_train, end_train, interval) trader.backtest(start, end, interval)
def op_window(asset, window, window_size, date, srs=None, output='png', srs_type='unknown', resample=None, reducers=None, **kwargs): outputDriver = Outputs.getDriver(output) DS = Asset(asset) if srs: SR = SpatialReference.parse(srs, srs_type) DS = DS.warpTo(SR, resample) data = DS.getWindow(window, date, window_size, resample) if reducers: data = Reducers.apply(reducers, data) return outputDriver(data, ds=DS)
def portfolio_checker(): teststocks = stockgroupY port = Portfolio(0) asset = Asset("STOCK1", pl=-967) port.asset_list.append(asset) for stock in teststocks: port.add_asset(Asset(stock)) num = 1 asset = Asset("STOCK2", num, (num * 3.05), nosell=True) # asset.AddStock(50000,3.05) port.asset_list.append(asset) port.capital = 38140 tc = TradeChecker(port) tc.startDateIndex = 1180329 tc.algo8(buyhunger=0, sellhunger=0, showgraph=False, endIndex=0)
def filterRelationDataSet(self, dataToBeFiltered): filteredData = [] for data in dataToBeFiltered: #Fetch relations for the resourceId assetObj = Asset(data['resourceId']) assetRelationList = assetObj.fetchRelations() #Loop through each inner map in assetRelationList for relationMap in assetRelationList: # Extra relation map from inner relation list assetRelationInnerList = relationMap['relation'] if len(assetRelationList) > 0: # Loop through assetRelationInnerList to find the relation for innerRelationMap in assetRelationInnerList: role = innerRelationMap['typeReference']['role'] # Check whether relation type exists for an asset for relationType in self.parameterList[ 'RelationTypeIn']: if role == relationType: if data not in filteredData: filteredData.append(data) return filteredData
def exampleFronttesting(): logger = Logger() logger.addTarget('log/fronttestlog.txt') portfolio = Portfolio(1000) portfolio.addAsset(Asset('ethereum', 'ETH')) end_date = datetime.datetime(2019, 2, 15) timeframe = datetime.timedelta(minutes=5) apiKey = 'SOME BINANCE API KEY' privKey = 'SOME BINANCE PRIV KEY' trader = TestTrader(portfolio, logger, 0) trader.fronttest(apiKey, privKey, end_date, timeframe)
def exampleBinance(): logger = Logger() logger.addTarget('log/log.txt', 0) portfolio = Portfolio() portfolio.addAsset(Asset('ethereum', 'ETH')) apiKey = 'insert api key here' privKey = 'insert private key here' market = BinanceMarket(apiKey, privKey) end = datetime.datetime(2019, 1, 25) tf = datetime.timedelta(minutes=5) trader = TestTrader(portfolio, logger, 0) trader.trade(market, end, tf)
def __init__(self, file, language=None): Asset.__init__(self, file) self.language = None #self._inferLanguage(file, language) return
class AssetFrame(wx.Frame): def __init__(self, style, parent, my_id, title="PyAsset:Asset", myfile=None, **kwds): self.assets = AssetList() self.bills = BillList() self.cur_asset = None self.edited = 0 self.rowSize = 27 self.colSize = 20 if style == None: style = wx.DEFAULT_FRAME_STYLE kwds["style"] = style wx.Frame.__init__(self, parent, my_id, title, **kwds) self.make_widgets() if myfile: self.cur_asset.read_qif(myfile) self.redraw_all(-1) if self.cur_asset.get_name() != None: self.SetTitle("PyAsset: Asset %s" % self.cur_asset.get_name()) return def DisplayMsg(self, str): d = wx.MessageDialog(self, str, "Error", wx.OK | wx.ICON_INFORMATION) d.ShowModal() d.Destroy() return wx.CANCEL def make_widgets(self): self.menubar = wx.MenuBar() self.SetMenuBar(self.menubar) self.statusbar = self.CreateStatusBar(1, 0) self.make_filemenu() self.make_editmenu() self.make_helpmenu() self.make_grid() self.set_properties() self.do_layout() def make_filemenu(self): self.filemenu = wx.Menu() # ID_EXPORT_TEXT = wx.NewId() # ID_ARCHIVE = wx.NewId() # ID_IMPORT_CSV = wx.NewId() ID_IMPORT_XLSM = wx.NewId() ID_UPDATE_FROM_NET = wx.NewId() ID_PROPERTIES = wx.NewId() self.filemenu.Append(wx.ID_OPEN, "Open\tCtrl-o", "Open a new transction file", wx.ITEM_NORMAL) self.filemenu.Append(wx.ID_SAVE, "Save\tCtrl-s", "Save the current transactions in the same file", wx.ITEM_NORMAL) self.filemenu.Append(wx.ID_SAVEAS, "Save As", "Save the current transactions under a different name", wx.ITEM_NORMAL) self.filemenu.Append(wx.ID_CLOSE, "Close\tCtrl-w", "Close the current file", wx.ITEM_NORMAL) # self.filemenu.Append(ID_EXPORT_TEXT, "Export Text", # "Export the current transaction register as a text file", # wx.ITEM_NORMAL) # self.filemenu.Append(ID_ARCHIVE, "Archive", # "Archive transactions older than a specified date", # wx.ITEM_NORMAL) self.filemenu.AppendSeparator() # self.filemenu.Append(ID_IMPORT_CSV, "Import CSV\tCtrl-c", # "Import transactions from a CSV file", # wx.ITEM_NORMAL) self.filemenu.Append(ID_IMPORT_XLSM, "Import XLSM file\tCtrl-i", "Import transactions from an EXCEL file with Macros", wx.ITEM_NORMAL) self.filemenu.Append(ID_UPDATE_FROM_NET, "Update Accounts from Net\tCtrl-u", "Update accounts using pre-defined iMacros", wx.ITEM_NORMAL) self.filemenu.AppendSeparator() self.filemenu.Append(ID_PROPERTIES, "Properties\tCtrl-p", "Display and/or edit Number and Data/Time display properties, pay frequencies", wx.ITEM_NORMAL) self.filemenu.AppendSeparator() self.filemenu.Append(wx.ID_EXIT, "Quit\tCtrl-q", "Exit PyAsset", wx.ITEM_NORMAL) self.menubar.Append(self.filemenu, "&File") wx.EVT_MENU(self, wx.ID_OPEN, self.load_file) wx.EVT_MENU(self, wx.ID_SAVE, self.save_file) wx.EVT_MENU(self, wx.ID_SAVEAS, self.save_as_file) wx.EVT_MENU(self, wx.ID_CLOSE, self.close) # wx.EVT_MENU(self, ID_EXPORT_TEXT, self.export_text) # wx.EVT_MENU(self, ID_ARCHIVE, self.archive) # wx.EVT_MENU(self, ID_IMPORT_CSV, self.import_CSV_file) wx.EVT_MENU(self, ID_IMPORT_XLSM, self.import_XLSM_file) wx.EVT_MENU(self, ID_UPDATE_FROM_NET, self.update_from_net) wx.EVT_MENU(self, ID_PROPERTIES, self.properties) wx.EVT_MENU(self, wx.ID_EXIT, self.quit) return def make_editmenu(self): ID_SORT = wx.NewId() ID_DELETE_ENTRY = wx.NewId() self.editmenu = wx.Menu() self.editmenu.Append(wx.ID_NEW, "New Entry\tCtrl-n", "Create a new asset in the list", wx.ITEM_NORMAL) self.editmenu.Append(ID_DELETE_ENTRY, "Delete Entry", "Delete the current asset", wx.ITEM_NORMAL) self.editmenu.Append(ID_SORT, "Sort Entries", "Sort entries", wx.ITEM_NORMAL) self.menubar.Append(self.editmenu, "&Edit") wx.EVT_MENU(self, wx.ID_NEW, self.newentry) wx.EVT_MENU(self, ID_DELETE_ENTRY, self.deleteentry) wx.EVT_MENU(self, ID_SORT, self.sort) return def make_helpmenu(self): ID_HELP = wx.NewId() self.helpmenu = wx.Menu() self.helpmenu.Append(wx.ID_ABOUT, "About", "About PyAsset", wx.ITEM_NORMAL) self.helpmenu.Append(ID_HELP, "Help\tCtrl-h", "PyAsset Help", wx.ITEM_NORMAL) self.menubar.Append(self.helpmenu, "&Help") wx.EVT_MENU(self, wx.ID_ABOUT, self.about) wx.EVT_MENU(self, ID_HELP, self.gethelp) return def make_grid(self): self.assetGrid = AssetGrid(self) def set_properties(self): self.total_width = self.assetGrid.set_properties(self) def do_layout(self): self.sizer_1 = wx.BoxSizer(wx.VERTICAL) self.sizer_1.Add(self.assetGrid, 1, wx.EXPAND, 0) self.SetSizer(self.sizer_1) self.SetAutoLayout(True) self.sizer_1.Fit(self) self.sizer_1.SetSizeHints(self) self.Layout() self.Show() def redraw_all(self, index=None): nassets = len(self.assets) if index == -1: nrows = self.assetGrid.GetNumberRows() if nrows > 0 and (index == None or index == -1): self.assetGrid.DeleteRows(0, nrows) nrows = 0 start_range = 0 end_range = nassets if nrows < nassets: rows_needed = nassets - nrows self.assetGrid.AppendRows(rows_needed) else: nrows = 1 start_range = index end_range = start_range + 1 for row in range(start_range, end_range): for col in range(self.assetGrid.getNumLayoutCols()): ret_val = wx.OK if row < 0 or row >= len(self.assets): str = "Warning: skipping redraw on bad cell %d %d!" % (row, col) ret_val = self.DisplayMsg(str) if ret_val != wx.OK: continue # Logic to always display Value (Curr), Value (Proj), Avail(Proj), Amt Over, Cash Limit, Cash Used and Cash Avail for credit cards and store cards asset_type = self.assets[row].get_type() col_name = self.assetGrid.getColName(col) self.assetGrid.setColZeroSuppress(row, col, True) if (asset_type == "store card" or asset_type == "credit card") and ("Curr" in col_name or "Proj" in col_name or "Amt" in col_name or "Cash" in col_name): self.assetGrid.setColZeroSuppress(row, col, False) # cellValue = self.assetGrid.GridCellDefaultRenderer(row, col) cellType = self.assetGrid.getColType(col) if cellType == self.assetGrid.DOLLAR_TYPE: self.assetGrid.GridCellDollarRenderer(row, col) elif cellType == self.assetGrid.RATE_TYPE: self.assetGrid.GridCellPercentRenderer(row, col) elif cellType == self.assetGrid.DATE_TYPE: self.assetGrid.GridCellDateRenderer(row, col) elif cellType == self.assetGrid.DATE_TIME_TYPE: self.assetGrid.GridCellDateTimeRenderer(row, col) elif cellType == self.assetGrid.STRING_TYPE: self.assetGrid.GridCellStringRenderer(row, col) else: self.assetGrid.GridCellErrorRenderer(row, col) if index == -1: self.assetGrid.SetGridCursor(nassets-1, 0) self.assetGrid.MakeCellVisible(nassets-1, True) elif index > 0: self.assetGrid.SetGridCursor(index, 0) self.assetGrid.MakeCellVisible(index, True) nassets = len(self.assets) self.SetSize(size=(self.total_width, nassets*self.rowSize)) self.Show() def assetchange(self, evt): row = evt.GetRow() col = evt.GetCol() val = evt.String colName = self.assetGrid.getColName(col) if colName == "Acct name": self.assets[row].set_name(val) elif colName == "Curr val": self.assets[row].set_total(val) elif colName == "Last pulled": self.assets[row].set_last_pull_date(val) elif colName == "Limit": self.assets[row].set_limit(val) elif colName == "Avail online": self.assets[row].set_avail(val) elif colName == "Rate": self.assets[row].set_rate(val) elif colName == "Payment amt": self.assets[row].set_payment(val) elif colName == "Due date": self.assets[row].set_due_date(val) elif colName == "Sched date": self.assets[row].set_sched(val) elif colName == "Min Pmt": self.assets[row].set_min_pay(val) elif colName == "Stmt Bal": self.assets[row].set_stme_bal(val) elif colName == "Amt Over": self.assets[row].set_amt_over(val) elif colName == "Cash Limit": self.assets[row].set_cash_limit(val) elif colName == "Cash Used": self.assets[row].set_cash_used(val) elif colName == "Cash Avail": self.assets[row].set_cash_avail(val) else: print "assetchange: Warning: modifying incorrect cell! row, ", row, " col ", col return def load_file(self, *args): self.close() self.cur_asset = Asset() self.edited = 0 d = wx.FileDialog(self, "Open", "", "", "*.qif", wx.OPEN) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() self.cur_asset.read_qif(os.path.join(dir, fname)) self.redraw_all(-1) if self.cur_asset.name: self.SetTitle("PyAsset: %s" % self.cur_asset.name) return def save_file(self, *args): for cur_asset in self.assets: if not cur_asset.filename: self.save_as_file() else: self.edited = 0 self.cur_asset.write_qif() return def save_as_file(self, *args): d = wx.FileDialog(self, "Save", "", "", "*.qif", wx.SAVE) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() self.cur_asset.write_qif(os.path.join(dir, fname)) if self.cur_asset.name: self.SetTitle("PyAsset: %s" % self.cur_asset.name) return def close(self, *args): if self.edited: d = wx.MessageDialog(self, 'Save file before closing?', 'Question', wx.YES_NO) if d.ShowModal() == wx.ID_YES: self.save_file() self.assets = AssetList() self.cur_asset = None nrows = self.assetGrid.GetNumberRows() if nrows > 0: self.assetGrid.DeleteRows(0, nrows) self.redraw_all(-1) self.edited = 0 self.SetTitle("PyAsset: Asset") return def quit(self, *args): self.close() self.Close() # # @brief Receives data to be written to and its location # # @params[in] date_ # Data of transaction # @params[in] amount_ # Amount of money for transaction # @params[in] memo_ # Description of transaction # @params[in] payee_ # Who transaction was paid to # @params[in] filelocation_ # Location of the Output file # # # https://en.wikipedia.org/wiki/Quicken_Interchange_Format # def write_file(self, date_, amount_, memo_, payee_, filelocation_): outFile = open(filelocation_, "a") # Open file to be appended outFile.write("!Type:Cash\n") # Header of transaction, Currently all set to cash outFile.write("D") # Date line starts with the capital D outFile.write(date_) outFile.write("\n") outFile.write("T") # Transaction amount starts here outFile.write(amount_) outFile.write("\n") outFile.write("M") # Memo Line outFile.write(memo_) outFile.write("\n") if (payee_ != -1): outFile.write("P") # Payee line outFile.write(payee_) outFile.write("\n") outFile.write("^\n") # The last line of each transaction starts with a Caret to mark the end outFile.close() # # @brief Takes given CSV and parses it to be exported to a QIF # # @params[in] inf_ # File to be read and converted to QIF # @params[in] outf_ # File that the converted data will go # @params[in] deff_ # File with the settings for converting CSV # # def read_csv(self, inf_, outf_, deff_): # will need to receive input csv and def file csvdeff = csv.reader(deff_, delimiter=',') next(csvdeff, None) for settings in csvdeff: date_ = (settings[0]) # convert to amount_ = (settings[2]) # How much was the transaction memo_ = (settings[3]) # discription of the transaction payee_ = (settings[4]) # Where the money is going deli_ = settings[5] # How the csv is separated header_ = (settings[6]) # Set if there is a header to skip csvIn = csv.reader(inf_, delimiter=deli_) # create csv object using the given separator if header_ >= 1: # If there is a header skip the fist line next(csvIn, None) # skip header for row in csvIn: self.write_file(row[date_], row[amount_], row[memo_], row[payee_], outf_) # export each row as a qif entry inf_.close() deff_.close() def import_CSV_file(self, *args): # Appends the records from a .csv file to the current Asset d = wx.FileDialog(self, "Import", "", "", "*.csv", wx.OPEN) if d.ShowModal() == wx.ID_OK: self.edited = 1 fname = d.GetFilename() dir = d.GetDirectory() total_name_in = os.path.join(dir, fname) total_name_extension_place = total_name_in.find(".csv") total_name_def = "" total_name_qif = "" if total_name_extension_place != -1: total_name_def = total_name_in[:total_name_extension_place] + ".def" total_name_qif = total_name_in[:total_name_extension_place] + ".qif" # pr total_name_in, total_name_def, total_name_qif error = "" try: fromfile = open(total_name_in, 'r') except: error = total_name_in + ' does not exist / cannot be opened !!\n' if total_name_qif != "": try: tofile = open(total_name_qif, 'a') except: error = total_name_qif + ' cannot be created !!\n' if total_name_def != "": if os.path.isfile(total_name_def): deffile = open(total_name_def, 'r') else: error = total_name_def + ' does not exist / cannot be opened !!\n' if error == "": tofile = total_name_qif self.read_csv(fromfile, tofile, deffile) self.cur_asset.read_qif(total_name_qif) fromfile.close() deffile.close() self.redraw_all(-1) else: d = wx.MessageDialog(self, error, wx.OK | wx.ICON_INFORMATION) d.ShowModal() d.Destroy() return if self.cur_asset.name: self.SetTitle("PyAsset: %s" % self.cur_asset.name) return def import_XLSM_file(self, *args): # Appends or Merges as appropriate the records from a .xlsm file to the current Asset d = wx.FileDialog(self, "Import", "", "", "*.xlsm", wx.OPEN) if d.ShowModal() == wx.ID_OK: self.edited = 1 fname = d.GetFilename() dir = d.GetDirectory() total_name_in = os.path.join(dir, fname) error = "" try: fromfile = open(total_name_in, 'r') except: error = total_name_in + ' does not exist / cannot be opened !!\n' fromfile.close() if error == "": self.cur_assets = None xlsm = ExcelToAsset() xlsm.OpenXLSMFile(total_name_in) latest_assets = xlsm.ProcessAssetsSheet() # print latest_assets for i in range(len(latest_assets)): xlsm_asset = latest_assets.__getitem__(i) self.cur_asset = copy.deepcopy(xlsm_asset) cur_name = self.cur_asset.get_name() found = False for j in range(len(self.assets)): if self.assets[j].get_name() == cur_name: self.assets[j] = copy.deepcopy(xlsm_asset) found = True break if not found: self.assets.append(self.cur_asset.get_name()) self.assets[-1] = copy.deepcopy(xlsm_asset) # latest_bills = xlsm.ProcessBillsSheet(self.bills) # print latest_bills #TODO: Process latest_bills if self.cur_asset.name: self.SetTitle("PyAsset: Asset %s" % total_name_in) self.redraw_all(-1) else: d = wx.MessageDialog(self, error, wx.OK | wx.ICON_INFORMATION) d.ShowModal() d.Destroy() def update_from_net(self, *args): w = iMacrosToAsset() w.Init() net_asset_codes = [("HFCU",1,[False,False,False,True]), ("BOA",-1,[False,True]), ("CITI",-1,[True]), ("MACYS",-1,[True]), ("SEARS",-1,[True]), ("TSP",-1,[False,False,False,True]), ("MET",1,[False])] for net_asset_code in net_asset_codes: latest_assets = w.GetNetInfo(net_asset_code) # print latest_assets for i in range(len(latest_assets)): net_asset = latest_assets.__getitem__(i) if net_asset != None: latest_name = net_asset.get_name() found = False for j in range(len(self.assets)): cur_name = self.assets[j].get_name() if "(" in cur_name: cur_name = cur_name.split("(")[1].split(")")[0] if cur_name in latest_name: net_index = j found = True break if not found: self.assets.append(latest_name) net_index = -1 # Always update Value (Curr) column... others check if non-zero value before update is done! self.assets[net_index].set_total(net_asset.get_total()) if net_asset.get_value_proj() != 0.0: self.assets[net_index].set_value_proj(net_asset.get_value_proj()) if net_asset.get_last_pull_date() != 0.0: self.assets[net_index].set_last_pull_date(net_asset.get_last_pull_date()) if net_asset.get_limit() != 0.0: self.assets[net_index].set_limit(net_asset.get_limit()) if net_asset.get_avail() != 0.0: self.assets[net_index].set_avail(net_asset.get_avail()) if net_asset.get_avail_proj() != 0.0: self.assets[net_index].set_avail_proj(net_asset.get_avail_proj()) if net_asset.get_rate() != 0.0: self.assets[net_index].set_rate(net_asset.get_rate()) if net_asset.get_payment() != 0.0: self.assets[net_index].set_payment(net_asset.get_payment()) if net_asset.get_due_date() != 0.0: self.assets[net_index].set_due_date(net_asset.get_due_date()) if net_asset.get_sched() != 0.0: self.assets[net_index].set_sched(net_asset.get_sched()) if net_asset.get_min_pay() != 0.0: self.assets[net_index].set_min_pay(net_asset.get_min_pay()) if net_asset.get_stmt_bal() != 0.0: self.assets[net_index].set_stmt_bal(net_asset.get_stmt_bal()) if net_asset.get_amt_over() != 0.0: self.assets[net_index].set_amt_over(net_asset.get_amt_over()) if net_asset.get_cash_limit() != 0.0: self.assets[net_index].set_cash_limit(net_asset.get_cash_limit()) if net_asset.get_cash_used() != 0.0: self.assets[net_index].set_cash_used(net_asset.get_cash_used()) if net_asset.get_cash_avail() != 0.0: self.assets[net_index].set_cash_avail(net_asset.get_cash_avail()) w.Finish() self.redraw_all(-1) def properties(self, *args): # TODO properties self.DisplayMsg("properties called") def export_text(self, *args): d = wx.FileDialog(self, "Save", "", "", "*.txt", wx.SAVE) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() self.cur_asset.write_txt(os.path.join(dir, fname)) return def archive(self, *args): d = wx.TextEntryDialog(self, "Archive transactions before what date (mm/dd/yy)?", "Archive Date") if d.ShowModal() == wx.ID_OK: date = Date(d.GetValue()) else: date = None d.Destroy() if not date: return archive = Asset() newcb_starttransaction = Transaction() newcb_starttransaction.amount = 0 newcb_starttransaction.payee = "Starting Balance" newcb_starttransaction.memo = "Archived by PyAsset" newcb_starttransaction.cleared = 1 newcb_starttransaction.date = date newcb = Asset() newcb.filename = self.cur_asset.filename newcb.name = self.cur_asset.name newcb.append(newcb_starttransaction) archtot = 0 for transaction in self.cur_asset: if transaction.date < date and transaction.cleared: archive.append(transaction) archtot += transaction.amount else: newcb.append(transaction) newcb_starttransaction.amount = archtot self.cur_asset = newcb while 1: d = wx.FileDialog(self, "Save Archive As", "", "", "*.qif", wx.SAVE) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() d.Destroy() if fname: break archive.write_qif(os.path.join(dir, fname)) self.redraw_all(-1) self.edited = 1 return def newentry(self, *args): self.edited = 1 self.cur_asset.append(Asset()) self.assetGrid.AppendRows() nassets = self.assetGrid.GetNumberRows() self.assetGrid.SetGridCursor(nassets - 1, 0) self.assetGrid.MakeCellVisible(nassets - 1, 1) def sort(self, *args): self.edited = 1 self.cur_asset.sort() self.redraw_all(-1) def deleteentry(self, *args): index = self.assetGrid.GetGridCursorRow() if index < 0: return d = wx.MessageDialog(self, "Really delete this asset?", "Really delete?", wx.YES_NO) if d.ShowModal() == wx.ID_YES: del self.cur_asset[index] self.redraw_all(index - 1) # only redraw cells [index-1:] return def about(self, *args): d = wx.MessageDialog(self, "Python Asset Manager\n" "Copyright (c) 2016,2017 Joseph J. Gorak\n" "Based on idea from Python Checkbook (pyCheckbook)\n" "written by Richard P. Muller\n" "Released under the Gnu GPL\n", "About PyAsset", wx.OK | wx.ICON_INFORMATION) d.ShowModal() d.Destroy() return def gethelp(self, *args): d = HelpDialog(self, -1, "Help", __doc__) val = d.ShowModal() d.Destroy() return
def archive(self, *args): d = wx.TextEntryDialog(self, "Archive transactions before what date (mm/dd/yy)?", "Archive Date") if d.ShowModal() == wx.ID_OK: date = Date(d.GetValue()) else: date = None d.Destroy() if not date: return archive = Asset() newcb_starttransaction = Transaction() newcb_starttransaction.amount = 0 newcb_starttransaction.payee = "Starting Balance" newcb_starttransaction.memo = "Archived by PyAsset" newcb_starttransaction.cleared = 1 newcb_starttransaction.date = date newcb = Asset() newcb.filename = self.cur_asset.filename newcb.name = self.cur_asset.name newcb.append(newcb_starttransaction) archtot = 0 for transaction in self.cur_asset: if transaction.date < date and transaction.cleared: archive.append(transaction) archtot += transaction.amount else: newcb.append(transaction) newcb_starttransaction.amount = archtot self.cur_asset = newcb while 1: d = wx.FileDialog(self, "Save Archive As", "", "", "*.qif", wx.SAVE) if d.ShowModal() == wx.ID_OK: fname = d.GetFilename() dir = d.GetDirectory() d.Destroy() if fname: break archive.write_qif(os.path.join(dir, fname)) self.redraw_all(-1) self.edited = 1 return
def __init__(self, name): Asset.__init__(self, name) self.assets = [] return
def __init__(self, name): Asset.__init__(self, name) from Sources import Sources self._sources = Sources(self.name) return