7.5 KiB
This code uses the OpenBB Terminal and Riskfolio libraries to create and optimize a financial portfolio based on historical stock data. It first screens for stocks hitting new highs, filters them, and retrieves their historical prices. It calculates the returns, uses them to create a portfolio, and applies mean-variance optimization to determine the optimal asset allocation. The results are then visualized and detailed with the number of shares to purchase based on a specified investment amount.
from openbb_terminal.sdk import openbb, TerminalStyle theme = TerminalStyle("light", "light", "light")
import riskfolio as rp
Screen for stocks hitting new highs using OpenBB Terminal.
new_highs = openbb.stocks.screener.screener_data("new_high")
Filter stocks with a price above $15 and located in the USA.
port_data = new_highs[ (new_highs.Price > 15) & (new_highs.Country == "USA") ]
Retrieve the list of ticker symbols from the filtered data.
tickers = port_data.Ticker.tolist()
Fetch historical price data for the selected tickers from 2016-01-01 to 2022-12-31.
data = openbb.economy.index( tickers, start_date="2016-01-01", end_date="2022-12-31" )
Calculate the daily percentage returns of the stock prices and drop columns with any NaN values.
returns = data.pct_change()[1:] returns.dropna(how="any", axis=1, inplace=True)
Create a portfolio object using the calculated returns.
port = rp.Portfolio(returns=returns)
Compute asset statistics such as historical mean and covariance.
port.assets_stats(method_mu='hist', method_cov='hist', d=0.94)
Set the lower return constraint for the optimization problem.
port.lowerret = 0.0008
Perform mean-variance optimization using historical data and no risk-free rate.
w_rp_c = port.rp_optimization( model="Classic", # use historical rm="MV", # use mean-variance optimization hist=True, # use historical scenarios rf=0, # set risk-free rate to 0 b=None # don't use constraints )
Plot the optimized portfolio allocation as a pie chart.
ax = rp.plot_pie(w=w_rp_c)
Plot the risk contributions of each asset in the portfolio.
ax = rp.plot_risk_con( w_rp_c, cov=port.cov, returns=port.returns, rm="MV", rf=0, )
Calculate the investment amount and number of shares to purchase for each asset.
port_val = 10_000 w_rp_c["invest_amt"] = w_rp_c * port_val w_rp_c["last_price"] = data.iloc[-1] w_rp_c["shares"] = (w_rp_c.invest_amt / w_rp_c.last_price).astype(int)
Display the optimized portfolio with investment amounts and number of shares.
w_rp_c
Sort the portfolio by asset weights in ascending order.
w_rp_c.sort_values(by="weights")
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.
