def show_all_stocks(request): all_dates = all_available_dates() if len(all_dates) < 1: raise Http404("No ASX price data available!") ymd = all_dates[-1] validate_date(ymd) qs = valid_quotes_only(ymd) timeframe = Timeframe() return show_companies(qs, request, timeframe, extra_context={ "title": "All stocks", "sentiment_heatmap_title": "All stock sentiment: {}".format(timeframe.description) })
def data_factory( ld: LazyDictionary, ): # dont create the dataframe unless we have to - avoid exxpensive call! purchase_buy_dates = [] purchases = [] stocks = [] for stock, purchases_for_stock in user_purchases(user).items(): stocks.append(stock) for purchase in purchases_for_stock: purchase_buy_dates.append(purchase.buy_date) purchases.append(purchase) purchase_buy_dates = sorted(purchase_buy_dates) # print("earliest {} latest {}".format(purchase_buy_dates[0], purchase_buy_dates[-1])) timeframe = Timeframe(from_date=str(purchase_buy_dates[0]), to_date=all_available_dates()[-1]) return make_portfolio_performance_dataframe(stocks, timeframe, purchases)
def test_find_movers( quotation_fixture, monkeypatch ): # pylint: disable=unused-argument,redefined-outer-name def mock_all_stocks(): # to correspond to fixture data return set(["ABC", "OTHER"]) def mock_superdf(*args, **kwargs): # to correspond to fixture data assert len(args) == 2 assert args[0] == ("uber-01-2021-asx",) assert args[1] is None assert kwargs == {} rows = [ { "asx_code": q.asx_code, "change_in_percent": q.change_in_percent, "fetch_date": q.fetch_date, } for q in Quotation.objects.all() ] raw_df = pd.DataFrame.from_records(rows) # print(raw_df) df = raw_df.pivot( index="fetch_date", columns="asx_code", values="change_in_percent" ) return df all_dates = all_available_dates(reference_stock="ABC") assert len(all_dates) > 5 monkeypatch.setattr(mdl, "all_stocks", mock_all_stocks) monkeypatch.setattr(mdl, "make_superdf", mock_superdf) results = find_movers( 10.0, Timeframe(from_date=all_dates[0], to_date=all_dates[-1]) ) assert results is not None # print(results) assert len(results) == 1 assert results.loc["ABC"] == 60.0
def test_find_movers(quotation_fixture, monkeypatch): def mock_all_stocks(): # to correspond to fixture data return set(['ABC', 'OTHER']) def mock_superdf(*args, **kwargs): # to correspond to fixture data assert args[0] == {'uber-01-2021-asx'} assert args[1] == {'ABC', 'OTHER'} assert kwargs == {} rows = [{'asx_code': q.asx_code, 'change_in_percent': q.change_in_percent, 'fetch_date': q.fetch_date} for q in Quotation.objects.all()] raw_df = pd.DataFrame.from_records(rows) #print(raw_df) df = raw_df.pivot(index='fetch_date', columns='asx_code', values='change_in_percent') return df all_dates = all_available_dates(reference_stock='ABC') assert len(all_dates) > 5 monkeypatch.setattr(mdl, 'all_stocks', mock_all_stocks) monkeypatch.setattr(mdl, 'make_superdf', mock_superdf) results = find_movers(10.0, Timeframe(from_date=all_dates[0], to_date=all_dates[-1])) assert results is not None #print(results) assert len(results) == 1 assert results.loc['ABC'] == 60.0
def test_all_available_dates( crafted_quotation_fixture, ): # pylint: disable=unused-argument,redefined-outer-name assert all_available_dates() == ["2021-01-01"] assert all_available_dates(reference_stock="ASX1") == []
def show_purchase_performance(request): purchase_buy_dates = [] purchases = [] stocks = [] for stock, purchases_for_stock in user_purchases(request.user).items(): stocks.append(stock) for purchase in purchases_for_stock: purchase_buy_dates.append(purchase.buy_date) purchases.append(purchase) purchase_buy_dates = sorted(purchase_buy_dates) # print("earliest {} latest {}".format(purchase_buy_dates[0], purchase_buy_dates[-1])) timeframe = Timeframe(from_date=str(purchase_buy_dates[0]), to_date=all_available_dates()[-1]) df = company_prices(stocks, timeframe, transpose=True) rows = [] stock_count = defaultdict(int) stock_cost = defaultdict(float) portfolio_cost = 0.0 for d in [ datetime.strptime(x, "%Y-%m-%d").date() for x in timeframe.all_dates() ]: d_str = str(d) if d_str not in df.columns: # not a trading day? continue purchases_to_date = filter(lambda vp, d=d: vp.buy_date <= d, purchases) for purchase in purchases_to_date: if purchase.buy_date == d: portfolio_cost += purchase.amount stock_count[purchase.asx_code] += purchase.n stock_cost[purchase.asx_code] += purchase.amount portfolio_worth = sum_portfolio(df, d_str, stock_count.items()) #print(df) # emit rows for each stock and aggregate portfolio for asx_code in stocks: cur_price = df.at[asx_code, d_str] if np.isnan(cur_price): # price missing? ok, skip record continue assert cur_price is not None and cur_price >= 0.0 stock_worth = cur_price * stock_count[asx_code] rows.append({ "portfolio_cost": portfolio_cost, "portfolio_worth": portfolio_worth, "portfolio_profit": portfolio_worth - portfolio_cost, "stock_cost": stock_cost[asx_code], "stock_worth": stock_worth, "stock_profit": stock_worth - stock_cost[asx_code], "date": d_str, "stock": asx_code, }) t = plot_portfolio(pd.DataFrame.from_records(rows)) portfolio_performance_figure, stock_performance_figure, profit_contributors_figure = t context = { "title": "Portfolio performance", "portfolio_title": "Overall", "portfolio_figure": portfolio_performance_figure, "stock_title": "Stock", "stock_figure": stock_performance_figure, "profit_contributors": profit_contributors_figure, } return render(request, "portfolio_trends.html", context=context)
def test_all_available_dates(crafted_quotation_fixture): assert all_available_dates() == ['2021-01-01'] assert all_available_dates(reference_stock='ASX1') == []