def test_validate_date(): bad_dates = ["2020-02-", "", None, "20-02-02", "2020-02-1"] for d in bad_dates: with pytest.raises(AssertionError): validate_date(d) good_dates = ["2020-02-02", "2020-02-01", "2021-12-31"] for d in good_dates: validate_date(d)
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 test_timeframe(data, expected): #print(data) tf = Timeframe(**data, today=datetime(year=2021, month=3, day=31).date()) # note today is fixed date for easier testing all_dates = tf.all_dates() assert len(all_dates) == expected[0] assert tf.n_days == expected[0] assert tf.n_days == len(tf) assert str(tf) == f"Timeframe: {data}" assert tf.description == expected[1] all_dates_expected = expected[2] if all_dates_expected is not None: assert all_dates == all_dates_expected assert all_dates_expected[-1] in tf assert not '1999-01-01' in tf validate_date(tf.most_recent_date)
def remove_bad_stocks(df: pd.DataFrame, date_to_check: str, messages, min_price): """ Remove stocks which have no data at start/end of the timeframe despite imputation that has been performed. This ensures that profit/loss can be calculated without missing data and that optimisation is not biased towards ridiculous outcomes. If min_price is not None, exclude all stocks with a start/end price less than min_price """ validate_date(date_to_check) missing_prices = list(df.columns[df.loc[date_to_check].isna()]) if len(missing_prices) > 0: df = df.drop(columns=missing_prices) messages.add("Ignoring stocks with no data at {}: {}".format( date_to_check, missing_prices)) if min_price is not None: bad_prices = list(df.columns[df.loc[date_to_check] <= min_price]) messages.add( f"Ignoring stocks with price < {min_price} at {date_to_check}: {bad_prices}" ) df = df.drop(columns=bad_prices) return df
def sum_portfolio(df: pd.DataFrame, date_str: str, stock_items): validate_date(date_str) portfolio_worth = sum( map(lambda t: df.at[t[0], date_str] * t[1], stock_items)) return portfolio_worth
def test_validate_date(): validate_date('2020-01-01') validate_date('2020-12-30') with pytest.raises(AssertionError): validate_date('2020-2-2')