Reputation: 43
So I have this function and my goal is to print out which portfolios have open positions. A portfolio is represented by a name and a collection of positions. Each position has a name, a start date, and an end date. A position is considered to be open on a given date if its starting date is before or on the given date and its end date is either not specified or on a later date than the given date.
This is the template code.
import sys
from typing import List, Set, Optional
from datetime import datetime
DATE_FORMAT = '%Y-%m-%d'
def get_portfolios_with_open_positions(date_str: str, portfolio_strings: List[str]) -> List[str]:
# Access your code here. Feel free to create other methods as required
pass
date_str = sys.stdin.readline().rstrip("\n")
portfolio_strings = []
for line in sys.stdin:
print(line)
portfolio_strings.append(line.rstrip("\n"))
portfolios = get_portfolios_with_open_positions(date_str, portfolio_strings)
for portfolio in portfolios:
print(portfolio)
For a given output:
2020-01-01
Portfolio1|CUSIP1:2019-01-01:2022-02-01
Portfolio2|CUSIP2:2019-01-01:2022-02-01
This should be the given input
Expected Output:
Portfolio1
Portfolio2
I am having difficulties in extrapolating the two dates from the portfolio_string, so far I can only extrapolate the first date.
Upvotes: 1
Views: 468
Reputation: 838
Here is my possible answer
def get_portfolios_with_open_positions(date_str: str, portfolio_strings: List[str]) -> List[str]:
# list for the return value
output_list = []
for portfolio in portfolio_strings:
# splits the portfolio string into the 3 parts that are separated by ':'
port_full_name,open_date_str,close_date_str = portfolio.split(':')
if datetime.strptime(date_str,DATE_FORMAT) >= datetime.strptime(open_date_str,DATE_FORMAT):
if not close_date_str or datetime.strptime(close_date_str,DATE_FORMAT) > datetime.strptime(date_str,DATE_FORMAT):
port_name = port_full_name.split('|')[0]
output_list.append(port_name)
return output_list
Let me know what you think.
Upvotes: 1