5.9 KiB
This code retrieves stock prices, calculates returns, and evaluates portfolio performance against a benchmark. It fetches historical prices for specified stocks and computes their percentage changes to derive returns. The code then calculates portfolio returns based on equal weighting and compares them with a benchmark index. Finally, it computes the batting average to assess the portfolio's performance in up and down markets. This is useful for portfolio managers and financial analysts to evaluate investment strategies.
import numpy as np import pandas as pd from openbb_terminal.sdk import openbb
Fetch historical prices for specified stocks using the OpenBB SDK
prices = openbb.economy.index([ "META", "AAPL", "AMZN", "NFLX", "GOOG", "QQQ" ])
Calculate percentage returns from the historical prices and remove any rows with NaN values
returns = prices.pct_change().dropna()
Extract the benchmark returns (QQQ) from the returns DataFrame
bench_returns = returns.pop("QQQ")
Calculate portfolio returns by equally weighting the individual stock returns
port_returns = (returns * 0.2).sum(axis=1)
Define the function to calculate the batting average of portfolio returns against the benchmark
def batting_average(port_returns, bench_returns): """Calculate batting average of portfolio returns. This function computes the batting average of portfolio returns compared to a benchmark, indicating performance in up and down markets. Parameters ---------- port_returns : pd.Series Returns of the portfolio. bench_returns : pd.Series Returns of the benchmark index. Returns ------- pd.Series Batting average, up market, and down market metrics. """ # Initialize a dictionary to store the results results = dict( { "batting average": np.nan, "up market": np.nan, "down market": np.nan, } ) # Calculate active returns by subtracting benchmark returns from portfolio returns active_returns = port_returns - bench_returns # Determine boolean arrays for batting average, up market, and down market conditions ba = active_returns > 0 up = active_returns[bench_returns >= 0.0] > 0 down = active_returns[bench_returns < 0.0] > 0 # Compute the mean values for the batting average, up market, and down market if len(ba) > 0: results["batting average"] = ba.mean() if len(up) > 0: results["up market"] = up.mean() if len(down) > 0: results["down market"] = down.mean() # Return a Series with the computed results return pd.Series(results, index=results.keys())
Calculate and display the batting average metrics for the portfolio
batting_average(port_returns, bench_returns)
PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.
