def test_update_befor_trade(self): p = Portfolio( buy_commission_rate=0.001, sell_commission_rate=0.0015, min_commission=5.0, round_lot=100) p.buy(price=10.0, volume=1000) p.update_before_trade(divide_rate=1.0) self.assertEqual(1000, p.sellable) self.assertEqual(0, p.frozen_volume) self.assertEqual(0, p.transaction_cost) p = Portfolio( buy_commission_rate=0.001, sell_commission_rate=0.0015, min_commission=5.0, round_lot=100, divide_rate_threshold=1.005) p.buy(price=10.0, volume=1000) p.update_before_trade(divide_rate=1.1) self.assertEqual(1100, p.volume) self.assertEqual(1100, p.sellable) # 有拆分 p.update_before_trade(divide_rate=1.006) self.assertEqual(1106, p.volume) self.assertEqual(1106, p.sellable) # 没有拆分 p.update_before_trade(divide_rate=1.005) self.assertEqual(1106, p.volume) self.assertEqual(1106, p.sellable)
def test_portfolio(self): """ Testing portfolio creation. initialisation and add stock. """ if DataHandler.check_portfolio_exists(): result = Portfolio() self.assertIsInstance(result.portfolio, dict) else: result = Portfolio() result.add_stock("AA", 10, 50, "2010-04-03") self.assertTrue(result.portfolio['AA'], True)
def test_basicWithdrawal(self): length = 30 gk = GuytonKlinger(.05, True, True, True, True, length) gk.reset(Portfolio(Assets(.5, .5))) withdrawal = gk.yearWithdraw(1.0) self.assertAlmostEqual(withdrawal, .05, delta=.005) gk.reset(Portfolio(Assets(.5, .5))) monthlyWithdrawals = 0.0 for i in range(0, 12): monthlyWithdrawals += gk.withdraw(1.0, 12) self.assertAlmostEqual(withdrawal, monthlyWithdrawals, delta=.005)
def add_trades(): if request.method == 'POST': trades_df = resp_to_trades_df(request) if path.isfile(TRADES_FILE): logger.info(f'{TRADES_FILE} exists, loading') pf_trades = pd.read_pickle(TRADES_FILE) pf = Portfolio(pf_trades, DATA_FILE) pf.add_trades(trades_df) else: pf = Portfolio(trades_df, DATA_FILE) pf.trades_df.to_pickle(TRADES_FILE) return render_template('home.jinja2', message='Trades added successfully') return render_template('add_trades.jinja2')
def updatepf(): # get as at date from drop down. If left blank, set none (defaults to today per portfolio info function) as_at_date = None if request.form.get( 'up_date') == '' else request.form.get('up_date') hide_zero = bool(request.form.get('hide_zero')) or True no_update = not (bool(request.form.get('no_update'))) or False currency = request.form.get('currency') or 'AUD' start = datetime.now() if path.isfile(TRADES_FILE): logger.info(f'{TRADES_FILE} exists, loading') pf_trades = pd.read_pickle(TRADES_FILE) pf = Portfolio(trades=pf_trades, currency=currency, filename=DATA_FILE, names_filename=NAMES_FILE) else: pf = Portfolio(filename=DATA_FILE, names_filename=NAMES_FILE, currency=currency) logger.info(f'file loading took {(datetime.now()-start)} to run') start = datetime.now() df = pf.info_date(as_at_date, hide_zero_pos=hide_zero, no_update=no_update) logger.info(f'info_date took {(datetime.now()-start)} to run') start = datetime.now() df['Date'] = df['Date'].dt.strftime('%d-%m-%y') df_html = ( df.style.applymap( neg_red, subset=[ '%LastChange', '$LastChange', '%UnRlGain', 'RlGain', 'UnRlGain', 'TotalGain' ]).format(PF_FORMAT_DICT, na_rep="--").set_properties( **{ 'text-align': 'left' }, subset=['Ticker', 'Name' ]).set_properties(**{ 'font-weight': 'bold' }, subset=df.index[-1]).hide_index(). set_uuid('portfolio').set_table_attributes( 'class="hover stripe row-border order-column display compact" style="width:100%"' ).render()) df_html = add_footer(df_html) logger.info(f'render HTML took {(datetime.now()-start)} to run') start = datetime.now() pf.trades_df.to_pickle(TRADES_FILE) logger.info(f'trades_df.to_pickle took {(datetime.now()-start)} to run') return render_template('home.jinja2', tables=df_html, title="Portfolio Tracker: Portfolio")
def _validate(self) -> None: """Validates the properties set on an order before it is placed. Raises: MalformedOrderError: If the combinations of properties set on the order are not compatible. """ if self.quantity <= 0: raise MalformedOrderError( 'The quantity must be greater than or equal to 1.') if self.price and self.price < 0: raise MalformedOrderError( 'The price must be greater than or equal to 0.') if self.stop_price and self.stop_price < 0: raise MalformedOrderError( 'The stop price must be greater than or equal to 0.') if (self.order_type in [ Order.Type.STOP_LIMIT_BUY_ORDER, Order.Type.STOP_LIMIT_SELL_ORDER, Order.Type.STOP_LOSS_BUY_ORDER, Order.Type.STOP_LOSS_SELL_ORDER ] and self.stop_price == None): raise MalformedOrderError( 'You must include a stop_price with the current order.') if self.order_type in [ Order.Type.STOP_LIMIT_BUY_ORDER, Order.Type.STOP_LIMIT_SELL_ORDER ] and self.price == None: raise MalformedOrderError( 'You must include a price with the current order.') if (self.order_type in [ Order.Type.SELL, Order.Type.LIMIT_SELL_ORDER, Order.Type.MARKET_SELL_ORDER, Order.Type.STOP_LIMIT_SELL_ORDER, Order.Type.STOP_LOSS_SELL_ORDER ]): if not Portfolio().contains_instrument(self.instrument): raise UnownedInstrumentError(self.instrument.ticker_symbol) if self.order_type in [ Order.Type.BUY, Order.Type.LIMIT_BUY_ORDER, Order.Type.MARKET_BUY_ORDER, Order.Type.STOP_LIMIT_BUY_ORDER, Order.Type.STOP_LOSS_BUY_ORDER ]: if Portfolio( ).withdrawable_amount < self.quantity * self.instrument.last_trade_price( ): raise InsufficientFundsError(self.instrument.ticker_symbol)
def test_fee(self): p = Portfolio() self.assertEqual(5.0, p._buy_fee(0)) self.assertEqual(5.0, p._buy_fee(1000)) self.assertEqual(10.0, p._buy_fee(10000)) self.assertEqual(0, p._sell_fee(0)) self.assertEqual(1.5, p._sell_fee(1000))
def test_update_value_percent(self): p = Portfolio() p.update_value_percent(0) self.assertEqual(0, p.value_percent) p.market_value = 10 p.update_value_percent(100.0) self.assertEqual(0.1, p.value_percent)
def simulate_accumulation(series, portfolio=(0, 0), years=35, annual_inflow=25000, accumulation=N_80_RebalanceAccumulation): portfolio = Portfolio(portfolio[0], portfolio[1]) strategy = accumulation(portfolio).accumulate() strategy.send(None) annual = [] for _, change in zip(range(years), series): gains, _, _ = portfolio.adjust_returns(change) strategy.send(annual_inflow) annual.append( YearlyResults(returns=gains, withdraw_n=0, withdraw_r=0, withdraw_pct_cur=0, withdraw_pct_orig=0, portfolio_n=portfolio.value, portfolio_r=portfolio.real_value, portfolio_bonds=portfolio.bonds, portfolio_stocks=portfolio.stocks)) annual_inflow *= 1 + change.inflation return annual
def protfolio_cost(name) -> float: ''' Calculate the cost of portfolio ''' stocks = read_portfolio(name) portfolio = Portfolio(stocks) return portfolio.cost_shares
def __init__(self, portfolio = Portfolio(), start = "2019", end = "2019-09-20", max = 25): #setting our initial variables self.search_after = start # the start of the time period to scrape self.search_before = end # the end of the time period to scrape self.output_filename = 'out-id' + portfolio.id + "-" + start + "to" + end + ".csv" #wack filename sorry self.max_articles_per_term = max # how many articles to scrape per search term self.portfolio = portfolio # the portfolio to self.analyzer = NaiveBayesAnalyzer() # create used_url list from file in portfolio self.used_urls = [] try: up = open(self.portfolio.url_filename, "r") # open the file line = up.readline() while (line): # go through each line, get the url, and add it to the list self.used_urls.append(line.strip("\n")) line = up.readline() up.close() print() except: print("no url file yet") #create articles list self.articles = []
def __init__(self, commission=0.002, price_type='close', short=False, begin_equity=1000000, date="2015-11-01", output=True): ''' Initializing the broker class :param commission: commission fee, default 0.002 :param price_type: vwap or close price or open price or other choices(close*0.5+open*0.5) :param short: True or False, True if shorting is allowed ''' # set default parameters self.commission = commission self.price = price_type self.short = short self.output = output # self.port = Portfolio(begin_equity=begin_equity, commission=commission) self.order_list = [] self.order_count = 0 self.trading_data = pd.DataFrame() self.trade_info = {} # two checking triggers self.execute_trigger = False self.update_trigger = False # daily recorder self.trade_amount = 0.0 self.trade_cost = 0.0 self.date = date # log self.trade_log = {}
def __init__(self, initial_cash, events_queue, price_handler, position_sizer, risk_manager): """ The PortfolioHandler is designed to interact with the backtesting or live trading overall event-driven architecture. It exposes two methods, on-signal and on_fill, which handle how SignalEvent and FillEvent objects are dealt with. Each PortfolioHandler contains a Portfolio object, which stores the actual Position objects. The PortfolioHandler takes a handle to a PositionSizer object which determines a mechanism, based on the current Portfolio, as to how to size a new Order. The PortfolioHandler also takes a handle to the RiskManager, which is used to modify any generated Orders to remain in line with risk parameters. """ self.initial_cash = initial_cash self.events_queue = events_queue self.price_handler = price_handler self.position_sizer = position_sizer self.risk_manager = risk_manager self.portfolio = Portfolio(price_handler, initial_cash)
def update_combined_figures(trigger, finance, fund, period, div): """ Update combined worth graph and exposure pie charts """ finance = pd.read_json(finance) summary = pd.read_json(fund) ptf = Portfolio(finance=finance, summary=summary, period=period) if trigger is not None: figure1 = px.line(ptf.get_combined_worth(), title='Combined revenue') figure1.update_layout(yaxis_tickformat='%', showlegend=False) sector_split = ptf.get_sector_split() currency_split = ptf.get_currency_split() figure2 = make_subplots(rows=1, cols=2, specs=[[{ "type": "pie" }, { "type": "pie" }]]) figure2.add_trace(go.Pie(labels=currency_split.index, values=currency_split['weight'], name='Currency', title='Currency exposure'), row=1, col=1) figure2.add_trace(go.Pie(labels=sector_split.index, values=sector_split.to_list(), name='Sector', title='Sector exposure'), row=1, col=2) div = html.Div([dcc.Graph(figure=figure1), dcc.Graph(figure=figure2)]) return div
def __init__(self): # Base url of the SEC website self.base_url = r"https://www.sec.gov" # Official SEC url that contains all the CIK x Ticker data self.cik_url = self.base_url + r'/include/ticker.txt' # Get ticker from Portfolio sheet with Portfolio() as p: self.ticker = p.get_ticker_selection() # Get CIK number from SEC website self.cik = self.get_cik_number() # Base url for finding company filings self.edgar_url = self.base_url + "/cgi-bin/browse-edgar" # Define search parameters for the SEC EDGAR browser self.param_dict = { 'action': 'getcompany', 'CIK': str(self.cik), 'dateb': datetime.today().date().strftime("%Y%m%d"), 'start': '', 'output': 'atom', 'count': '100' }
def test_delete(self): """ Testing deletion of stock. """ result = Portfolio() result.add_stock("AA", 10, 50, "2010-04-03") self.assertTrue(result.delete_stock("AA"), True)
def __init__ (self, stockExchange): self.stockExchange = stockExchange userName = input("Hi trader, what's your name?\n") self.portfolio = Portfolio(userName) self.dayCount = 1 print("Play till 5 days have passed see if your portfolio prices are better than the market's!\n") print("Trading has begun!")
def test_yearBase(self): length = 30 gk = GuytonKlinger(.05, True, True, True, True, length) gk.reset(Portfolio(Assets(.5, .5))) # withdraw and grow once initialWithdrawal = gk.withdraw(1.0, 12) initialPortfolio = gk.getPortfolioValue() gk.grow(Assets(1.1, 1.1)) # now do it 11 more times for i in range(1, 12): withdrawal = gk.withdraw(1.0, 12) gk.grow(Assets(1.1, 1.1)) portfolio = gk.getPortfolioValue() self.assertAlmostEqual(withdrawal, initialWithdrawal, delta=.0005) self.assertAlmostEqual(portfolio, initialPortfolio - (i * initialWithdrawal), delta=.0005) # now do it 1 more time, which will trigger the new year calculations. grownWithdrawal = gk.withdraw(1.1, 12) gk.grow(Assets(1.1, 1.1)) grownPortfolio = gk.getPortfolioValue() self.assertNotAlmostEqual(grownWithdrawal, initialWithdrawal, delta=.00005) self.assertNotAlmostEqual(grownPortfolio, initialPortfolio, delta=.00005)
def update(self, *args): """Updates the graph with the altered sliders""" #Fetches slider information s1 = self.s1.get() s2 = self.s2.get() r1 = self.r1.get() r2 = self.r2.get() p = self.p.get() #Changes the number next to the bar self.r1_string.configure(text="%.2f" % r1) self.r2_string.configure(text="%.2f" % r2) self.s1_string.configure(text="%.2f" % s1) self.s2_string.configure(text="%.2f" % s2) self.p_string.configure(text="%.2f" % self.p.get()) #Creates two asset objects self.I1 = Instrument(r1, s1, "Asset 1", "Equity") self.I2 = Instrument(r2, s2, "Asset 2", "Bond") #Builds a portfolio object self.port = Portfolio([self.I1, self.I2]) self.port.addcorr([[0, p]]) #Displays the new graph to the graph frame fff = Frame(height=400, width=400, bd=10, bg='white') Chart(self.port, 0.02).scatter(fff) fff.grid(row=1, column=0)
def test_portfolio_update_works(self): pf = Portfolio(cash=10, market_size=3) target = np.array([[0.2, 0.4, 0.4]]) prices = np.array([[1, 2, 3]]) pf.update_transaction(target, prices) self.assertTrue((pf.quantities == np.array([[10, 0, 0], [3, 2, 1]])).all())
def load_portfolio(self): """ Load a portfolio from a file. """ if self.terminate: return # First get a file. self.lock.acquire() self.windows['ACTION'].erase() curses.curs_set(1) tp = curses.textpad.Textbox(self.windows['ACTION']) file_str = tp.edit() curses.curs_set(0) self.clear_action() self.lock.release() self.refresh() # Now that we have a portfolio file, let's load it up and # fire off a thread to update it. p = Portfolio(file_str.strip()) self.portfolios.append(p) self.track_portfolio(p)
def __init__(self): self.live_trading = True # set False for backtesting. self.log_level = logging.DEBUG self.logger = self.setup_logger() # Don't connect to live data feeds if backtesting. if self.live_trading: self.exchanges = self.load_exchanges(self.logger) # Connect to database. print("Connecting to database...") self.db_client = MongoClient( self.DB_URL, serverSelectionTimeoutMS=self.DB_TIMEOUT_MS) self.db = self.db_client[self.DB_NAME] self.check_db_connection() # Event queue and producer/consumer worker classes. self.events = queue.Queue(0) self.data = Datahandler(self.exchanges, self.logger, self.db, self.db_client) self.strategy = Strategy(self.exchanges, self.logger, self.db, self.db_client) self.portfolio = Portfolio(self.logger) self.broker = Broker(self.exchanges, self.logger) # Processing performance variables. self.start_processing = None self.end_processing = None self.run()
def main(): # Initialize blacklist object. blacklist = BlacklistGenerator(const.MINIMUM_FAILURES, const.SUCCESS_TO_FAILURE_RATIO, const.SYMBOL_DATA_PATH) # Get data from NASDAQ. symbol_to_nasdaq_data = GrabStockInformationFromCsv( const.STOCK_SYMBOL_PATH % '', const.SYMBOL_KEY, blacklist=blacklist) # Add data from Yahoo. symbol_to_yahoo_data = GrabStockInformationFromYahoo( symbol_to_nasdaq_data.keys(), const.MAX_SYMBOLS, blacklist=blacklist) # Join NASDAQ and Yahoo data. symbol_to_data = symbol_to_nasdaq_data for symbol, yahoo_data in symbol_to_yahoo_data.iteritems(): default_nasdaq_data = {key: 'n/a' for key in const.NASDAQ_CONSTANTS} symbol_to_data.get(symbol, default_nasdaq_data).update(yahoo_data) # Construct and print portfolio out to CSV. portfolio = Portfolio('Whole Portfolio', blacklist) portfolio.AddStockDict(symbol_to_data) #portfolio.BlacklistBySector(const.SECTOR_BLACKLIST) portfolio.CleanUpStocks() portfolio.WriteToCsv('%s%s%s%s.csv' %( const.BASE_PATH, const.DATA_SUB_PATH, 'stock_data_', time.strftime('%Y-%m-%d', time.localtime())))
def test_add_account(self): alg = self._init_test() prt = Portfolio(FILE_NAME) fnds = Funds(FILE_NAME) accs = alg.add_account(name='01', fee=0, risk=0.7, profit=0.7, fund=0.0) self.assertEqual(0.0, alg.portfolio_total_fund) accounts = [(1, '01', 0.0, accs[0][3], 0, 0.7, 0.7, 1, accs[0][-1])] self.assertEqual(accounts, accs) prt_data = prt.retrieve_id(1) self.assertEqual(-1, prt_data[-1]) acc_fnds = fnds.retrieve_funds_for_account(account_id=1) self.assertEqual(0, acc_fnds[-1][1]) accs = alg.add_account(name="03", fee=0, risk=0.3, profit=0.9, fund=100.0, is_main=True) self.assertEqual(100.0, alg.portfolio_total_fund) accounts = [ (1, '01', 0.0, accs[0][3], 0, 0.7, 0.7, 1, accs[0][-1]), (2, '03', 1.0, accs[1][3], 0, 0.3, 0.9, 1, accs[1][-1]), ] self.assertEqual(accounts, accs) prt_data = prt.retrieve_id(1) self.assertEqual(2, prt_data[-1]) acc_fnds = fnds.retrieve_funds_for_account(account_id=2) self.assertEqual(100, acc_fnds[-1][1]) os.remove(FILE_NAME)
def setUp(self): self.p = Portfolio() self.p.build_portfolio(generate_tickers_string()) self.p.set_ticker_data() self.allocations, self.balances = generate_portfolio_inputs( self.p.get_portfolio())
def create_portfolio(data): print("CREATING PORTFOLIO") pf = Portfolio() for index, row in data.iterrows(): ticker = row['Verdipapir'] amount = float(row['Antall'].replace(',', '.').replace(' ', '')) kurs = float(row['Kurs'].replace(',', '.').replace(' ', '')) vekslingskurs = float(row['Vekslingskurs'].replace(',', '.').replace( ' ', '')) transaksjonstype = row['Transaksjonstype'] belop = float(row['Beløb'].replace(',', '.').replace(' ', '')) # Deposit and withdraw cash if transaksjonstype == 'INNSKUDD' or transaksjonstype == 'UTTAK INTERNET': if transaksjonstype == 'INNSKUDD': pf.deposit(belop) if transaksjonstype == 'UTTAK INTERNET': pf.withdraw(belop) if transaksjonstype == 'KJØPT' or transaksjonstype == 'SALG': a = Asset(ticker) pf.buy(a, amount, (kurs * vekslingskurs)) if belop < 0 else pf.sell( a, amount, (kurs * vekslingskurs)) return pf
def _init_test(self): if os.path.isfile(FILE_NAME): os.remove(FILE_NAME) create_db(FILE_NAME) p = Portfolio(FILE_NAME) prt = p.create_portfolio() return Algorithm(FILE_NAME, prt[0])
def get_portfolio(self, userid, hashkey, *, get_coins=False, get_coin_ts=False, recalc=False): table = self.get_table("Portfolio") res = table.get_item(Key={"CompanyID": userid, "HashKey": hashkey}) if 'Item' in res: port = Portfolio(res['Item']) port.W = sum([float(a['Allocation']) for a in port.Allocations]) if get_coins: hashkeys = [a['HashKey'] for a in port.Allocations] if hashkeys: coins = self.get_coins(owner=userid, coinids=hashkeys) coin_hash = dict([(f.HashKey, f) for f in coins]) for a in port.Allocations: coinid = a['HashKey'] if coinid in coin_hash: a['Coin'] = coin_hash[coinid] return port return None
def parse_portfolio(): portfolio = Portfolio(date(2020, 1, 2)) with open(filepath) as fp: lines = fp.readlines() for line in lines: portfolio.add_holding(Holding(*line.split(','))) return portfolio
def portfolio_update_all(): update_all = Portfolio() # Get important data for updates rule1_data = update_all.get_rule1_data() # Update all main blocks update_all.fill_in_summary_block() update_all.fill_in_general_info_block(rule1_data) update_all.fill_in_stock_price_block() update_all.fill_in_capital_block() update_all.fill_in_time_block() update_all.fill_in_status_block() update_all.fill_in_balance_block() update_all.fill_in_profits_block() update_all.fill_in_ta_block() update_all.fill_in_rule1_analysis_block(rule1_data) # Update TA chart update_all.get_ta_chart() # Update Portfolio chart update_all.get_portfolio_chart() # Store new data in the portfolio backend json file update_all.save_backend_dict()