Appearance
question:You are tasked with creating a function `unique_elements` that returns a list of unique elements from an input list while preserving the order of their first occurrence. This function should simulate the behavior of removing duplicates and maintaining order without using external libraries or the `set` data structure. 1. The function should accept a single parameter `input_list`, which is the list containing potentially duplicated elements. 2. The function should return a list of elements that appear only once in their first occurrence order. Function Signature ```python def unique_elements(input_list): pass ``` Example ```python # Sample Input input_list = [4, 5, 6, 4, 7, 8, 5, 9, 1, 7, 8, 1] # Expected Output output = [6, 9] # The output removes all duplicate elements and preserves the remaining in their order of first occurrence. ``` Libraries to Use - None
answer:def unique_elements(input_list): Returns a list of unique elements in the order of their first occurrence. unique_list = [] seen = set() for element in input_list: if input_list.count(element) == 1: unique_list.append(element) seen.add(element) return unique_list
question:You are tasked with writing a function called `calculate_portfolio_metrics` that evaluates a financial portfolio based on stock data. This function should use the following libraries and their specific functionalities: `pandas.DataFrame`, `numpy.std`, and `numpy.mean`. # Function Requirements 1. **Load Data**: Accept a pandas DataFrame containing stock prices with columns named as stock symbols and rows indexed by date (format `YYYY-MM-DD`). 2. **Calculate Daily Returns**: Compute daily returns for each stock. 3. **Portfolio Weights**: Use a dictionary input `weights` where keys are stock symbols and values are the weights of each stock in the portfolio. Ensure the weights sum up to 1. 4. **Portfolio Return and Volatility**: Compute the portfolio's return and volatility based on the daily returns and given weights. 5. **Sharpe Ratio**: Calculate the Sharpe ratio of the portfolio assuming a risk-free rate of 0. # Parameters ```python def calculate_portfolio_metrics( stock_data: pd.DataFrame, weights: dict) -> dict: Calculates portfolio metrics including daily returns, overall return, volatility, and Sharpe ratio. Args: - stock_data (pd.DataFrame): DataFrame with stock prices, columns as stock symbols, and indexed by date. - weights (dict): Dictionary with stock symbols as keys and portfolio weights as values. Returns: - dict: A dictionary containing portfolio metrics: 'portfolio_return', 'portfolio_volatility', 'sharpe_ratio'. pass ``` # Example Usage: ```python import pandas as pd data = { 'AAPL': [150.0, 153.0, 155.0, 149.0, 152.0], 'MSFT': [200.0, 202.0, 205.0, 198.0, 199.0], 'GOOGL': [2700.0, 2720.0, 2735.0, 2650.0, 2680.0] } index = ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'] stock_data = pd.DataFrame(data, index=index) weights = {'AAPL': 0.4, 'MSFT': 0.4, 'GOOGL': 0.2} metrics = calculate_portfolio_metrics(stock_data, weights) print(metrics) ``` # Instructions: 1. Implement the `calculate_portfolio_metrics` function using the specified libraries. 2. Compute daily returns for each stock from the stock price data. 3. Ensure the portfolio weights sum up to 1. If they don't, raise a ValueError. 4. Calculate the portfolio's overall return and volatility based on the daily returns and weights. 5. Calculate the Sharpe ratio of the portfolio assuming a risk-free rate of 0. 6. Return the portfolio metrics in a dictionary containing keys: `portfolio_return`, `portfolio_volatility`, and `sharpe_ratio`.
answer:import pandas as pd import numpy as np def calculate_portfolio_metrics(stock_data: pd.DataFrame, weights: dict) -> dict: Calculates portfolio metrics including daily returns, overall return, volatility, and Sharpe ratio. Args: - stock_data (pd.DataFrame): DataFrame with stock prices, columns as stock symbols, and indexed by date. - weights (dict): Dictionary with stock symbols as keys and portfolio weights as values. Returns: - dict: A dictionary containing portfolio metrics: 'portfolio_return', 'portfolio_volatility', 'sharpe_ratio'. # Check if weights sum up to 1 total_weight = sum(weights.values()) if not np.isclose(total_weight, 1): raise ValueError("The portfolio weights must sum to 1. Current sum is {}".format(total_weight)) # Calculate daily returns daily_returns = stock_data.pct_change().dropna() # Calculate portfolio return portfolio_return = np.dot(daily_returns, list(weights.values())) mean_daily_return = np.mean(portfolio_return) # Calculate portfolio volatility portfolio_volatility = np.std(portfolio_return) # Calculate Sharpe ratio sharpe_ratio = mean_daily_return / portfolio_volatility return { 'portfolio_return': mean_daily_return, 'portfolio_volatility': portfolio_volatility, 'sharpe_ratio': sharpe_ratio }
question:Generate a Fibonacci-like sequence using custom starting values and specific sequence length. The function should accept two starting values, a sequence length, and compute the sequence based on the summation of the two prior elements, similar to traditional Fibonacci sequence logic. Return the generated sequence as a list. The function should output with: list[int]: A list representing the Fibonacci-like sequence. You should write self-contained code starting with: ``` def generate_fibonacci_like_sequence(start1, start2, length): ```
answer:def generate_fibonacci_like_sequence(start1, start2, length): Generates a Fibonacci-like sequence of a given length using two custom starting values. Args: start1 (int): The first starting value. start2 (int): The second starting value. length (int): The length of the sequence to generate. Returns: list[int]: A list representing the Fibonacci-like sequence. if length <= 0: return [] elif length == 1: return [start1] elif length == 2: return [start1, start2] sequence = [start1, start2] for _ in range(2, length): next_value = sequence[-1] + sequence[-2] sequence.append(next_value) return sequence
question:You are tasked with developing a feature for an online book store that allows users to search for books based on specific keywords. The book data consists of a list of books, where each book is represented as a dictionary with keys: 'title', 'author', and 'description'. Your job is to implement a function `search_books(keyword, books)` that returns a list of books that contain the given keyword in their title, author, or description. Your function `search_books(keyword, books)` should: 1. Take a string `keyword` and a list of dictionaries `books` as input. 2. Perform a case-insensitive search for the keyword within the `title`, `author`, and `description` fields of each book. 3. Return a list of books (dictionaries) that match the search criteria. # Requirements: - The search should be case-insensitive. - Ensure that if no books match the keyword, an empty list is returned. # Example: Given the books data: ```python books = [ {'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'description': 'A novel set in the Jazz Age.'}, {'title': 'To Kill a Mockingbird', 'author': 'Harper Lee', 'description': 'A novel about racial injustice.'}, {'title': '1984', 'author': 'George Orwell', 'description': 'A dystopian social science fiction novel.'}, {'title': 'Moby Dick', 'author': 'Herman Melville', 'description': 'The saga of Captain Ahab.'} ] ``` And the keyword: `novel` Your function should return: ```python [ {'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'description': 'A novel set in the Jazz Age.'}, {'title': 'To Kill a Mockingbird', 'author': 'Harper Lee', 'description': 'A novel about racial injustice.'}, {'title': '1984', 'author': 'George Orwell', 'description': 'A dystopian social science fiction novel.'} ] ``` Ensure your solution is efficient and clear, while accurately finding books that contain the keyword in any field.
answer:def search_books(keyword, books): Searches for books that contain the keyword in the title, author, or description fields. The search is case-insensitive. :param keyword: The keyword to search for. :param books: A list of dictionaries, each representing a book with 'title', 'author', and 'description' keys. :return: A list of books (dictionaries) that match the search criteria. keyword_lower = keyword.lower() result_books = [] for book in books: if (keyword_lower in book['title'].lower() or keyword_lower in book['author'].lower() or keyword_lower in book['description'].lower()): result_books.append(book) return result_books