SkillAgentSearch skills...

Analyzerportfolio

USI - UNIVERSITY PROJECT. Python package designed for comprehensive portfolio analysis. It provides a wide range of common metrics, graphics and AI integrations

Install / Use

/learn @washednico/Analyzerportfolio
About this skill

Quality Score

0/100

Category

Design

Supported Platforms

Universal

README

AnalyzerPortfolio

AnalyzerPortfolio is a Python package designed for comprehensive portfolio analysis, offering a powerful and user-friendly toolkit for investors, analysts, and researchers. Built primarily on yfinance, it allows users to retrieve financial data, construct portfolios, and evaluate their performance using industry-standard metrics such as beta, alpha, Sharpe ratio, Sortino ratio, Value-at-Risk (VaR), and more.

The package also features advanced visualization tools powered by plotly, enabling interactive and insightful graphical representations of portfolio performance. Additionally, AnalyzerPortfolio supports various portfolio optimization techniques, including minimum variance optimization, Sharpe ratio maximization, and information ratio optimization.

Furthermore, the package integrates AI-driven capabilities for real-time stock news monitoring and automated investment report generation, helping users stay informed and make data-driven decisions.

Installation

You can install AnalyzerPortfolio via pip:

pip install analyzerportfolio

Alternatively you can install AnalyzerPortfolio directly from GitHub using the following command:

pip install git+https://github.com/washednico/analyzerportfolio.git

Dependencies

AnalyzerPortfolio relies on the following Python libraries:

  • openai>=1.43.0 – For AI-powered features (e.g., stock news monitoring, report generation)
  • pandas>=1.5.1 – For data manipulation and analysis
  • yfinance>=0.2.32 – For retrieving financial data
  • numpy==1.26.4 – For numerical computations
  • plotly>=5.18.0 – For interactive data visualization
  • arch>=7.0.0 – For financial econometrics and risk modeling
  • scipy==1.14.0 – For mathematical and statistical computations
  • statsmodels==0.14.1 – For statistical modeling and hypothesis testing
  • nbformat>=4.2.0 – For working with Jupyter Notebook formats

To manually install the dependencies, run:

pip install openai pandas yfinance numpy plotly arch scipy statsmodels nbformat

Note that nbformat is required not directly for analyzerportfolio but indirectly for plotly, solving plotting issues.

Basic Usage

Below are examples demonstrating how to use AnalyzerPortfolio to:

  • Calculate various portfolio metrics
  • Generate graphical outputs
  • Optimize a portfolio
  • Analyze stock newss

Neverthless, users are highly encouraged to utilize the docstring help function (help(function_name)) to fully understand how each function works.

Scraping Financial Data

To retrieve market data using yfinance, you should use the download_data function. Below is an example of how to access its documentation:

print(ap.download_data.__doc__)
Download stock and market data, convert to base currency, and return the processed data.

Parameters:
- tickers (list): List of stock tickers.
- market_ticker (str): Market index ticker.
- start_date (str): Start date for historical data.
- end_date (str): End date for historical data.
- base_currency (str): The base currency for the portfolio (e.g., 'USD').
- risk_free (str): The risk free rate to use in the calculations written as ticker on fred (e.g., 'DTB3' for USD).
- use_cache (bool): Whether to use cache to retrieve data, if data is not cached it will be stored for future computations. Default is False.
- folder_path (str): Path to the folder where the cache will be stored. Default is None.

Returns:
pd.DataFrame: DataFrame containing the adjusted and converted prices for all tickers and the market index.

Examples: Scraping Financial Data

ticker = ['AAPL','MSFT','GOOGL','AMZN','TSLA','E']
investments = [100,200,300,300,200,500]
start_date = '2019-01-01'
end_date = '2024-08-28'
market_ticker = '^GSPC'
base_currency = 'EUR'
risk_free = "PCREDIT8"
rebalancing_period_days = 250
# Download historical data
data = ap.download_data(tickers=ticker, start_date=start_date, end_date=end_date, base_currency=base_currency,market_ticker=market_ticker, risk_free=risk_free)

Build portfolio object

Once market data are successfully scraped, the user should use create_portfolio to create a portfolio that is a requirement to perform any further computation.

print(ap.create_portfolio.__doc__)
Calculates returns and value amounts for specified stocks over a return period,
the portfolio without rebalancing, optionally the portfolio with auto-rebalancing,
and includes market index calculations.

Parameters:
- data: DataFrame with adjusted closing prices (index as dates, columns as tickers).
- tickers: List of stock tickers in the portfolio.
- investments: List or array of initial investments for each stock.
- market_ticker: String representing the market index ticker.
- name_portfolio: String representing the name of the portfolio
- base_currency: String representing the base currency for the portfolio.
- return_period_days: Integer representing the return period in days. Default is 1.
- rebalancing_period_days: Optional integer representing the rebalancing period in days.
  If None, no rebalancing is performed.
- market_ticker: Optional string representing the market index ticker.
  If provided, market returns and values will be calculated.
- target_weights: Optional list or array of target weights (should sum to 1).
  If not provided, it will be calculated from the initial investments.
- exclude_ticker_time (int): if ticker is not available within +- x days from start date, exclude it. Default is 7.
- exclude_ticker (bool): Apply the exclusion of tickers based on the exclude_ticker_time parameter. Default is False.

Returns:
- returns_df: DataFrame containing:
  - Stock returns and values for each ticker.
  - 'Portfolio_Returns' and 'Portfolio_Value' columns for the portfolio without rebalancing.
  - 'Rebalanced_Portfolio_Returns' and 'Rebalanced_Portfolio_Value' columns (if rebalancing is performed).
  - 'Market_Returns' and 'Market_Value' columns (if market_ticker is provided).

Examples: Build portfolio object

# Build portfolio object 
portfolio_1 = ap.create_portfolio(data, ticker, investments, market_ticker=market_ticker, name_portfolio="Portfolio1", rebalancing_period_days=rebalancing_period_days)

Metrics Calculation

AnalyzerPortfolio provides a comprehensive set of portfolio performance metrics, including:

  • Total Portfolio Return – Overall return of the portfolio over a given period
  • Yearly Portfolio Return – Annualized return of the portfolio
  • Annual Volatility – Standard deviation of portfolio returns, measuring risk
  • Beta & Alpha – Measures of systematic risk and excess return relative to a benchmark
  • Information Ratio – Assesses risk-adjusted returns relative to a benchmark
  • Sharpe Ratio – Evaluates risk-adjusted returns using total volatility
  • Sortino Ratio – Similar to Sharpe Ratio but considers downside risk only
  • Dividend Yield – Measures the income generated by the portfolio relative to its value

Example: Metrics Calculation

import analyzerportfolio as ap  

# Download financial data  
data = ap.download_data(tickers=ticker, start_date=start_date, end_date=end_date,  
                        base_currency=base_currency, market_ticker=market_ticker,  
                        risk_free=risk_free)  

# Create a portfolio  
portfolio_1 = ap.create_portfolio(data, ticker, investments, market_ticker=market_ticker,  
                                  name_portfolio="Portfolio1",  
                                  rebalancing_period_days=rebalancing_period_days)  

# Calculate portfolio metrics  
beta, alpha = ap.c_beta(portfolio_1)  
return_port = ap.c_total_return(portfolio_1)  
volatility = ap.c_volatility(portfolio_1)  
sharpe = ap.c_sharpe(portfolio_1)  
sortino = ap.c_sortino(portfolio_1)  
dividend_yield = ap.c_dividend_yield(portfolio_1)  
max_drawdown = ap.c_max_drawdown(portfolio_1)  
Beta: 1.2747003924120648
Alpha: 0.1570779145816794
Portfolio Return: 20.93218943734265
Annual Volatility: 0.35298770243181105
Sharpe Ratio: 0.880984191948735
Sortino Ratio: 1.3597745688778438
Max Drawdown: 0.613344773273578
Dividend Yield: 0.02429375

Risk Assessment

To enhance risk management, AnalyzerPortfolio supports multiple methods for calculating Value-at-Risk (VaR) and Expected Shortfall (ES), offering a detailed perspective on downside risk. The available methodologies include:

  • Parametric (Variance-Covariance Method) – Assumes returns follow a normal distribution to estimate risk
  • Historical Simulation – Uses past returns to model potential future losses
  • Bootstrapping – Resamples historical data to assess risk without distributional assumptions
  • Extreme Value Theory (EVT) – Focuses on modelling tail risk to capture extreme market movements

These approaches allow users to tailor risk analysis based on their investment strategy and market conditions.

Example: Risk Assessment

import analyzerportfolio as ap

data = ap.download_data(tickers=ticker, start_date=start_date, end_date=end_date, base_currency=base_currency,market_ticker=market_ticker, risk_free=risk_free)
portfolio_1 = ap.create_portfolio(data, ticker, investments, market_ticker=market_ticker, name_portfolio="Portfolio1", rebalancing_period_days=rebalancing_period_days)

var_95 = ap.c_VaR(portfolio_1, confidence_level=0.95)
var_95_30d = ap.c_VaR(portfolio_1, confidence_level=0.95, horizon_days=30)
var_95_p = ap.c_VaR(portfolio_1, confidence_level=0.95, method="parametric")
var_95_p_30d = ap.c_VaR(portfolio_1, confidence_level=0.95, horizon_days=30, method="parametric")
var_95_b = ap.c_VaR(portfolio_1, confidence_level=0.95, method="bootstrap")

Related Skills

View on GitHub
GitHub Stars7
CategoryDesign
Updated10mo ago
Forks0

Languages

Python

Security Score

77/100

Audited on Jun 5, 2025

No findings