Files
strategy-lab/to_explore/pyquantnews/43_OpenBBandRiskParity.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

7.5 KiB

No description has been provided for this image

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.

In [ ]:
from openbb_terminal.sdk import openbb, TerminalStyle
theme = TerminalStyle("light", "light", "light")
In [ ]:
import riskfolio as rp

Screen for stocks hitting new highs using OpenBB Terminal.

In [ ]:
new_highs = openbb.stocks.screener.screener_data("new_high")

Filter stocks with a price above $15 and located in the USA.

In [ ]:
port_data = new_highs[
    (new_highs.Price > 15) & (new_highs.Country == "USA")
]

Retrieve the list of ticker symbols from the filtered data.

In [ ]:
tickers = port_data.Ticker.tolist()

Fetch historical price data for the selected tickers from 2016-01-01 to 2022-12-31.

In [ ]:
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.

In [ ]:
returns = data.pct_change()[1:]
returns.dropna(how="any", axis=1, inplace=True)

Create a portfolio object using the calculated returns.

In [ ]:
port = rp.Portfolio(returns=returns)

Compute asset statistics such as historical mean and covariance.

In [ ]:
port.assets_stats(method_mu='hist', method_cov='hist', d=0.94)

Set the lower return constraint for the optimization problem.

In [ ]:
port.lowerret = 0.0008

Perform mean-variance optimization using historical data and no risk-free rate.

In [ ]:
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.

In [ ]:
ax = rp.plot_pie(w=w_rp_c)

Plot the risk contributions of each asset in the portfolio.

In [ ]:
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.

In [ ]:
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.

In [ ]:
w_rp_c

Sort the portfolio by asset weights in ascending order.

In [ ]:
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.