def addStocksToBalance(self, security_dict, stocks_alloc, recommended_stock_alloc, recommendations, exposure=True, exposure_threshold=5): pop = recom.recommend_stock(recommendations) while (stocks_alloc < recommended_stock_alloc): # get a recommendation security = next(pop) print('Checking if stock {} exists in portfolio'.format(security)) # check if the recommended security is in the portfolio already and get the second best if it is while self.check_security_in_portfolio(self.portfolio, security): print('Stock {} exists in portfolio'.format(security)) security = next(pop) print('Checking if stock {} exists in portfolio'.format( security)) # desired exposure if (exposure): fit_exposure = min(exposure_threshold, (recommended_stock_alloc - stocks_alloc)) else: fit_exposure = recommended_stock_alloc - stocks_alloc # add shares to portfolio self.addNewSecurity(security, fit_exposure, security_dict) # increase bond allocation stocks_alloc += fit_exposure
def addStocksToBalance(self, security_dict, stocks_alloc, recommended_stock_alloc, exposure_threshold=0.05): recommendations = recom.rank_stocks('Mid') pop = recom.recommend_stock(recommendations) while (stocks_alloc < recommended_stock_alloc): # get a recommendation security = next(pop) print('Checking if stock {} exists in portfolio'.format(security)) # check if the recommended security is in the portfolio already and get the second best if it is while ut.check_security_in_portfolio(self.portfolio, security): print('Stock {} exists in portfolio'.format(security)) security = next(pop) print('Checking if stock {} exists in portfolio'.format( security)) # desired exposure fit_exposure = min(exposure_threshold, (recommended_stock_alloc - stocks_alloc) / 100) # calculated desired shares to fit 0.05 exposure shares = fit_exposure * self.client['Capital'] / security_dict[ security]['Price'] current_exposure = shares * security_dict[security][ 'Price'] / self.client['Capital'] # add shares to portfolio self.addNewSecurity(security, shares) # increase bond allocation stocks_alloc += current_exposure * 100
def add_security_with_criterion(self, shares, region, preferences, allSecurities, criterion='Sector'): preferences = self.filter_list_by_criterion(preferences, region, allSecurities, criterion) # give error if list is empty pop = recom.recommend_stock(preferences) security = next(pop) ok = True while self.security_exists_in_portfolio(self.portfolio, security): try: security = next(pop) except StopIteration: pyfancy.pyfancy().red( "Cound not find a new security in {} {}".format( criterion, region)).output() ok = False break if ok: self.addNewSecurity(security, shares, allSecurities) return True else: return False
def buy_stocks(self, budget, preferences, allSecurities): pop = recom.recommend_stock(preferences) security = next(pop) print('Checking if stock {} exists in portfolio'.format(security)) while self.check_security_in_portfolio(self.portfolio, security): print('Stock {} exists in portfolio'.format(security)) security = next(pop) self.addNewSecurity(security, budget, allSecurities)
def add_one_item(self, preferences, exposure, allSecurities): pop = recom.recommend_stock(preferences) security = next(pop) while self.security_exists_in_portfolio(self.portfolio, security): # stock exists, look for another one security = next(pop) self.addNewSecurity(security, exposure, allSecurities) return True
def complete_exposure(self, security_dict, exposure_threshold=0.05): recommendations = recom.rank_stocks('Mid') pop = recom.recommend_stock(recommendations) while (self.extra_exposure > 0): security = next(pop) # check if the recommended security is in the portfolio already and get the second best if it is while ut.check_security_in_portfolio(self.portfolio, security): security = next(pop) if self.extra_exposure >= exposure_threshold: exp = exposure_threshold self.setExtraExposure(self.extra_exposure - exposure_threshold) else: exp = self.extra_exposure self.setExtraExposure(0) current_security = security_dict[security] price = current_security['Price'] sha = exp * self.getCapital() / price self.addNewSecurity(security, sha) print('Added security {} with {} shares and {} exposure'.format( security, sha, exp))
def addStocksToBalance(self, security_dict, stocks_alloc, recommended_stock_alloc, recommendations, exposure=True, exposure_threshold=5): pop = recom.recommend_stock(recommendations) while (stocks_alloc < recommended_stock_alloc): security = next(pop) print('Checking if stock {} exists in portfolio'.format(security)) while self.security_exists_in_portfolio(self.portfolio, security): print('Stock {} exists in portfolio'.format(security)) security = next(pop) print('Checking if stock {} exists in portfolio'.format( security)) if (exposure): fit_exposure = min(exposure_threshold, (recommended_stock_alloc - stocks_alloc)) else: fit_exposure = recommended_stock_alloc - stocks_alloc self.addNewSecurity(security, fit_exposure, security_dict) stocks_alloc += fit_exposure
def refine_alloc_with_sectors(client_portfolio, allSecurities, economy, stock_preferences, bonds_preferences, all_preferences): # recommended sector allocation divers_sectors, divers_percent = recom.bc_sector_allocation(economy) recomm_sector_dict = {} for i in range(0, len(divers_sectors)): recomm_sector_dict[divers_sectors[i]] = divers_percent[i] # check if we have enough stocks to fill sector alloc, add more if not while len(client_portfolio.portfolio) < len(recomm_sector_dict): sorted_exposures = client_portfolio.extract_item_with_most_exposure( client_portfolio.portfolio) pop = recom.recommend_stock(sorted_exposures) security = next(pop) security_exposure = client_portfolio.portfolio[security] exposure_to_remove = security_exposure / 2 exposure_to_add = security_exposure - exposure_to_remove client_portfolio.setExposure(security, exposure_to_remove) if (client_portfolio.getAssetType(security, allSecurities) == 'Equity'): client_portfolio.add_one_item(stock_preferences, exposure_to_add, allSecurities) elif (client_portfolio.getAssetType(security, allSecurities) == 'Bond'): client_portfolio.add_one_item(bonds_preferences, exposure_to_add, allSecurities) # current sector allocation portfolio_sector_dict = {} for sector in divers_sectors: sector_dict = client_portfolio.extract_securities_by_criterion( sector, allSecurities, 'Sector') portfolio_sector_dict[sector] = sum(sector_dict.values()) # cut regions with too much exposure to get some cash for key, value in recomm_sector_dict.items(): diff = portfolio_sector_dict.get(key, 0) - recomm_sector_dict[key] if diff > 0: client_portfolio.cutExposureOnCriterion(recomm_sector_dict[key], key, all_preferences, allSecurities, 'Sector') print("Cut {} from region {}".format(diff, key)) # cut exposure above recommended alloc stocks_alloc, bonds_alloc = client_portfolio.current_asset_allocation( allSecurities) recommended_stock_alloc, recommended_bonds_alloc = client_portfolio.recommended_asset_allocation( client_portfolio.client['Risk_profile']) print( "You have {} stocks and {} bonds. Recommended {} stocks and {} bonds". format(stocks_alloc, bonds_alloc, recommended_stock_alloc, recommended_bonds_alloc)) if (stocks_alloc > recommended_stock_alloc): client_portfolio.removeStocksToBalance(allSecurities, stocks_alloc, recommended_stock_alloc, stock_preferences, True) if (bonds_alloc > recommended_bonds_alloc): client_portfolio.removeBondsToBalance(allSecurities, bonds_alloc, recommended_bonds_alloc, bonds_preferences, True) # check current allocation again portfolio_sector_dict = {} for sector in divers_sectors: sector_dict = client_portfolio.extract_securities_by_criterion( sector, allSecurities, 'Sector') portfolio_sector_dict[sector] = sum(sector_dict.values()) #now deal with adding more exposure to sectors that don't have enough for key, value in recomm_sector_dict.items(): diff = recomm_sector_dict[key] - portfolio_sector_dict.get(key, 0) print("adding {} in sector {}".format(diff, key)) while diff > 0: #decide wheather to add a stock or a bond which_type = recom.recommend_asset_type(client_portfolio, allSecurities) for i in range(0, len(which_type), 2): if (which_type[i] == 'Equity' and diff > 0): client_portfolio.add_security_with_criterion( min(diff, 5, which_type[i + 1]), key, stock_preferences, allSecurities, 'Sector') diff = diff - min(diff, 5, which_type[i + 1]) elif (which_type[i] == 'Bond' and diff > 0): client_portfolio.add_security_with_criterion( min(diff, 5, which_type[i + 1]), key, bonds_preferences, allSecurities, 'Sector') diff = diff - min(diff, 5, which_type[i + 1]) print("finished sector alloc") return True
def advisor5(client_portfolio, allSecurities, economy): divers_sectors, divers_percent = recom.bc_sector_allocation(economy) # categorize existing securities by type of asset pyfancy.pyfancy().cyan("\n*** Portfolio analysis.... ***\n").output() time.sleep(1) stocks_held, bonds_held = client_portfolio.extract_securities_by_type( allSecurities) # categorize existing securities by sector pyfancy.pyfancy().cyan( "\n *** Sectors you currently hold in stocks: ***").output() time.sleep(2) portfolio_sector_dict = client_portfolio.categorize_stocks_by_sector( allSecurities) # calculate recommended percentages per sector pyfancy.pyfancy().cyan( "\n *** Sectors recommended to hold in stocks: ***").output() time.sleep(2) recomm_sector_dict = recom.recomm_sector_allocation( client_portfolio.portfolio, divers_percent, divers_sectors, sum(portfolio_sector_dict.values())) # add recommended sectors that do not exist pyfancy.pyfancy().cyan( "\n *** Looking for sectors that should not be in your portfolio ***" ).output() time.sleep(2) sectors_to_del = client_portfolio.sectors_you_should_not_have( recomm_sector_dict, portfolio_sector_dict) if (len(sectors_to_del) == 0): print('No sectors to remove') else: for sector_del in sectors_to_del: client_portfolio.deleteSector(sector_del, allSecurities) # refine securities per sector pyfancy.pyfancy().cyan( "\n *** Refining exposure for sectors you hold ***").output() time.sleep(2) for key, value in recomm_sector_dict.items(): time.sleep(1) diff = recomm_sector_dict[key] - portfolio_sector_dict.get(key, 0) if (diff == recomm_sector_dict[key]): # portfolio does not contain the recommended sector print('No {} in the portfolio. You should add {} of them'.format( key, value)) recommendations = recom.rank_stocks_without_bc(key) pop = recom.recommend_stock(recommendations) security = next(pop) client_portfolio.addNewSecurity(security, value, allSecurities) elif (diff > 0): print('You have {}% of {}. You should have {}% in {}.'.format( portfolio_sector_dict.get(key, 0), key, recomm_sector_dict.get(key, 0), key)) current_holdings = client_portfolio.extract_securities_by_sector( key, allSecurities) print("Currently holding {} stocks in sector {}:".format( len(current_holdings), key)) for k, v in current_holdings.items(): pyfancy.pyfancy().bold().white("{} {} %".format( k, v)).output() recommendations = recom.rank_stocks_without_bc(key) pop = recom.recommend_stock(recommendations) security = next(pop) client_portfolio.addNewSecurity(security, diff, allSecurities) elif (diff < 0): print('You have {}% of {}. You should have {}% in {}.'.format( portfolio_sector_dict.get(key, 0), key, recomm_sector_dict.get(key, 0), key)) current_holdings = client_portfolio.extract_securities_by_sector( key, allSecurities) print("Currently holding {} stocks in sector {}:".format( len(current_holdings), key)) for k, v in current_holdings.items(): pyfancy.pyfancy().bold().white("{} {} %".format( k, v)).output() current_holdings_list = sorted(current_holdings, key=current_holdings.get, reverse=True) diff = diff * (-1) for k in current_holdings_list: v = current_holdings[k] if diff == 0: break elif (diff > 0 and v > diff): client_portfolio.setExposure(k, v - diff) diff = 0 elif (diff > 0 and v <= diff): client_portfolio.deteleSecurity(k, allSecurities) diff -= v #print ('\n \n Exposure left in portfolio: {}'.format(client_portfolio.extra_exposure)) stocks_held, bonds_held = client_portfolio.extract_securities_by_type( allSecurities) return client_portfolio
else: for sector_del in sectors_to_del: client_portfolio.deleteSector(sector_del, allSecurities) # refine securities per sector print('\n *** Refining exposure for sectors you hold ***') for key, value in recomm_sector_dict.items(): diff = recomm_sector_dict[key] - portfolio_sector_dict.get(key, 0) if (diff == recomm_sector_dict[key]): # portfolio does not contain the recommended sector print('\n No {} in the portfolio. You should add {} of them'.format( key, value)) recommendations = recom.rank_stocks_without_bc(key) pop = recom.recommend_stock(recommendations) security = next(pop) client_portfolio.addNewSecurity(security, value) elif (diff > 0): print( '\n You have {} of {}. You should have {} of sector {}. diff is {}' .format(portfolio_sector_dict.get(key, 0), key, recomm_sector_dict.get(key, 0), key, diff)) current_holdings = client_portfolio.extract_securities_by_sector( key, allSecurities) print(current_holdings) print(len(current_holdings)) recommendations = recom.rank_stocks_without_bc(key) pop = recom.recommend_stock(recommendations)