### Install FinQuant from source Source: https://github.com/fmilthaler/finquant/blob/master/docs/index.rst After cloning the FinQuant repository, this command installs the library locally. Ensure you are in the FinQuant directory. ```text python setup.py install ``` -------------------------------- ### Install FinQuant from Source (Python) Source: https://github.com/fmilthaler/finquant/blob/master/README.md Installs FinQuant after cloning the repository from GitHub. This involves running the setup.py script, which is useful for installing from local source code. ```python setup.py install ``` -------------------------------- ### Install FinQuant using pip Source: https://github.com/fmilthaler/finquant/blob/master/docs/index.rst This command installs the FinQuant library from the Python Package Index (PyPI). Ensure you have pip and a compatible Python version installed. ```text pip install FinQuant ``` -------------------------------- ### Build Portfolio with Preset Data (Python) Source: https://github.com/fmilthaler/finquant/blob/master/docs/examples.rst Shows how to construct a financial portfolio using pre-existing stock price data, such as data loaded from a file. This is useful when market data is already available locally. ```python import pandas as pd from finquant.portfolio import Portfolio # Load data from a CSV file data = pd.read_csv('stock_prices.csv', index_col=0, parse_dates=True) # Create a Portfolio instance pf = Portfolio(data) print(pf.get_stocks()) print(pf.get_start_date()) print(pf.get_end_date()) ``` -------------------------------- ### Analyze Portfolio Metrics and Visualize (Python) Source: https://github.com/fmilthaler/finquant/blob/master/docs/examples.rst This example demonstrates how to analyze a financial portfolio using a Portfolio object. It covers calculating key metrics like Expected Returns, Volatility, and Sharpe Ratio, and visualizing returns, moving averages, and Bollinger Bands. ```python import pandas as pd from finquant.portfolio import Portfolio import matplotlib.pyplot as plt # Assuming 'pf' is an existing Portfolio object loaded with data # Example: pf = Portfolio(pd.read_csv('stock_prices.csv', index_col=0, parse_dates=True)) # Calculate and print portfolio quantities print("Expected Returns:", pf.expected_returns()) print("Volatility:", pf.volatility()) print("Sharpe Ratio:", pf.sharpe_ratio()) # Extract individual stocks stock_aapl = pf.get_stock('AAPL') # Visualize returns, moving averages, and Bollinger Bands fig, ax = plt.subplots(figsize=(12, 6)) pf.plot_returns(ax=ax) pf.plot_moving_avg(ax=ax) pf.plot_bollinger_bands(ax=ax) plt.show() fig, ax = plt.subplots(figsize=(12, 6)) pf.plot_daily_returns(ax=ax) plt.show() ``` -------------------------------- ### Build Portfolio from Web Data (Python) Source: https://github.com/fmilthaler/finquant/blob/master/docs/examples.rst Demonstrates building a financial portfolio by downloading stock price data using Python packages quandl and yfinance. This function initializes a portfolio object with real-time or historical stock data. ```python import pandas as pd import quandl import yfinance as yf from finquant.portfolio import Portfolio # Download data from quandl quandl.ApiConfig.api_key = "YOUR_QUANDL_API_KEY" # Define stock tickers and time frame symbols = ['AAPL', 'MSFT', 'GOOGL'] date_start = '2020-01-01' date_end = '2023-01-01' # Fetch data using yfinance data = yf.download(symbols, start=date_start, end=date_end)['Adj Close'] # Create a Portfolio instance pf = Portfolio(data) print(pf.get_stocks()) print(pf.get_start_date()) print(pf.get_end_date()) ``` -------------------------------- ### Build Portfolio with Quandl Data Source: https://github.com/fmilthaler/finquant/blob/master/docs/quickstart.rst Constructs a FinQuant Portfolio object using stock data fetched from Quandl. It requires a list of stock ticker symbols as input. The default data API is Quandl. ```python from finquant.portfolio import build_portfolio names = ['GOOG', 'AMZN', 'MCD', 'DIS'] pf = build_portfolio(names=names) ``` -------------------------------- ### Clone FinQuant repository from GitHub Source: https://github.com/fmilthaler/finquant/blob/master/docs/index.rst This command downloads the FinQuant source code from its GitHub repository. You can then install it locally. ```text git clone https://github.com/fmilthaler/FinQuant.git ``` -------------------------------- ### Build Portfolio with Yahoo Finance Data Source: https://github.com/fmilthaler/finquant/blob/master/docs/quickstart.rst Constructs a FinQuant Portfolio object using stock data fetched from Yahoo Finance. This is an alternative to using Quandl, specified by setting the 'data_api' parameter to 'yfinance'. It requires a list of stock ticker symbols. ```python from finquant.portfolio import build_portfolio names = ['GOOG', 'AMZN', 'MCD', 'DIS'] pf = build_portfolio(names=names, data_api="yfinance") ``` -------------------------------- ### Optimize Portfolio using Efficient Frontier (Python) Source: https://github.com/fmilthaler/finquant/blob/master/docs/examples.rst Focuses on portfolio optimization using FinQuant's EfficientFrontier class. It demonstrates optimizing for minimum volatility, maximum Sharpe Ratio, and achieving target returns or volatilities. Visualization of the Efficient Frontier and optimal portfolios is also included. ```python import pandas as pd from finquant.portfolio import Portfolio from finquant.efficient_frontier import EfficientFrontier import matplotlib.pyplot as plt # Assuming 'pf' is an existing Portfolio object loaded with data # Example: pf = Portfolio(pd.read_csv('stock_prices.csv', index_col=0, parse_dates=True)) # Initialize EfficientFrontier ef = EfficientFrontier(pf) # Optimize for Minimum Volatility min_vol_weights = ef.minimum_volatility() print("Minimum Volatility Portfolio Weights:", min_vol_weights) # Optimize for Maximum Sharpe Ratio max_sharpe_weights = ef.maximum_sharpe_ratio() print("Maximum Sharpe Ratio Portfolio Weights:", max_sharpe_weights) # Optimize for Minimum Volatility for a given target return target_return = 0.0005 min_vol_target_return_weights = ef.minimum_volatility(target_return=target_return) print(f"Minimum Volatility Portfolio Weights for Target Return {target_return}:", min_vol_target_return_weights) # Optimize for Maximum Sharpe Ratio for a given target volatility target_volatility = 0.01 max_sharpe_target_volatility_weights = ef.maximum_sharpe_ratio(target_volatility=target_volatility) print(f"Maximum Sharpe Ratio Portfolio Weights for Target Volatility {target_volatility}:", max_sharpe_target_volatility_weights) # Plot the Efficient Frontier and optimal portfolios fig, ax = plt.subplots(figsize=(10, 6)) ef.plot_efficient_frontier(ax=ax) ef.plot_optimal_portfolios(ax=ax) plt.show() # Plot Monte Carlo simulation results overlayed on the Efficient Frontier monte_carlo_runs = 1000 ef.plot_monte_carlo(ax=ax, runs=monte_carlo_runs) plt.show() ``` -------------------------------- ### Build Portfolio from DataFrame Source: https://github.com/fmilthaler/finquant/blob/master/docs/quickstart.rst Creates a FinQuant Portfolio object from an existing pandas DataFrame containing stock price data. The DataFrame must have stock prices as columns and a 'Date' index. This method is useful when stock data is already available locally. ```python import pathlib from finquant.portfolio import build_portfolio df_data_path = pathlib.Path() / 'data' / 'ex1-stockdata.csv' df_data = pd.read_csv(df_data_path, index_col='Date', parse_dates=True) # building a portfolio by providing stock data pf = build_portfolio(data=df_data) ``` -------------------------------- ### Portfolio Optimization with Monte Carlo and Efficient Frontier Source: https://github.com/fmilthaler/finquant/blob/master/docs/quickstart.rst Performs portfolio optimization using both Monte Carlo simulation and the Efficient Frontier method. It includes plotting the results of the Monte Carlo simulation, visualizing the Efficient Frontier, and plotting optimal portfolios along it. Individual stock price plots are also generated. ```python # Monte Carlo optimisation opt_w, opt_res = pf.mc_optimisation(num_trials=5000) pf.mc_plot_results() # minimisation to compute efficient frontier and optimal portfolios along it pf.ef_plot_efrontier() pf.ef.plot_optimal_portfolios() # plotting individual stocks pf.plot_stocks() ``` -------------------------------- ### Display Portfolio Properties Source: https://github.com/fmilthaler/finquant/blob/master/docs/quickstart.rst Retrieves and displays the computed properties of a FinQuant Portfolio object. This includes stock names, time window, risk-free rate, expected return, volatility, Sharpe ratio, skewness, kurtosis, and allocation information. The properties are automatically calculated when the portfolio is built. ```python pf.properties() ``` -------------------------------- ### Compute and Plot Moving Averages Source: https://github.com/fmilthaler/finquant/blob/master/docs/quickstart.rst Calculates and visualizes a band of Exponential Moving Averages (EMAs) for a given stock's price data using the FinQuant library. It supports computing multiple moving averages with different spans and automatically identifies buy/sell signals. The function can optionally plot the results. ```python from finquant.moving_average import compute_ma, ema # get stock data for Disney dis = pf.get_stock("DIS").data.copy(deep=True) spans = [10, 50, 100, 150, 200] # computing and visualising a band of moving averages ma = compute_ma(dis, ema, spans, plot=True) print(ma.tail()) ``` -------------------------------- ### Building a FinQuant Portfolio from Web Data Source: https://github.com/fmilthaler/finquant/blob/master/README.tex.md Demonstrates how to construct a financial portfolio using FinQuant by downloading stock price data from the web using packages like `quandl` or `yfinance`. ```python # Example script: ./example/Example-Build-Portfolio-from-web.py # This is a conceptual example. Actual code requires library imports and specific API calls. # from finquant.portfolio import Portfolio # import pandas as pd # import yfinance as yf # or import quandl # Define stock tickers and date range # tickers = ['AAPL', 'MSFT', 'GOOG'] # start_date = '2020-01-01' # end_date = '2023-01-01' # Download stock data # data = yf.download(tickers, start=start_date, end=end_date)['Adj Close'] # Create a Portfolio instance # pf = Portfolio(data) # print("Portfolio built successfully from web data.") print("Conceptual example for building a portfolio from web data.") ``` -------------------------------- ### Portfolio Analysis with FinQuant Source: https://github.com/fmilthaler/finquant/blob/master/README.tex.md Demonstrates the analysis capabilities of a FinQuant Portfolio instance, including calculating key metrics and visualizing financial indicators like moving averages and Bollinger Bands. ```python # Example script: ./example/Example-Analysis.py # This is a conceptual example. Actual code requires library imports and method calls. # from finquant.portfolio import Portfolio # import pandas as pd # Assuming 'pf' is an already created Portfolio instance # Example: Get portfolio quantities # expected_returns = pf.expreturns # volatility = pf.vola # sharpe_ratio = pf.sharpe # print(f"Expected Returns: {expected_returns}") # print(f"Volatility: {volatility}") # print(f"Sharpe Ratio: {sharpe_ratio}") # Example: Visualize Moving Averages and Bollinger Bands # pf.plot_moving_avg() # pf.plot_bollinger_bands() print("Conceptual example for portfolio analysis and visualization.") ``` -------------------------------- ### Building a FinQuant Portfolio from File Data Source: https://github.com/fmilthaler/finquant/blob/master/README.tex.md Shows how to create a FinQuant financial portfolio by providing your own stock price data, typically read from a file (e.g., CSV). ```python # Example script: ./example/Example-Build-Portfolio-from-file.py # This is a conceptual example. Actual code requires library imports and file reading. # from finquant.portfolio import Portfolio # import pandas as pd # Load stock data from a file (e.g., CSV) # try: # data = pd.read_csv('stock_prices.csv', index_col=0, parse_dates=True) # except FileNotFoundError: # print("Error: stock_prices.csv not found.") # exit() # Create a Portfolio instance # pf = Portfolio(data) # print("Portfolio built successfully from file data.") print("Conceptual example for building a portfolio from file data.") ``` -------------------------------- ### Overlaying Optimization and Monte Carlo Plots in FinQuant Source: https://github.com/fmilthaler/finquant/blob/master/README.tex.md Illustrates how to overlay multiple visualizations in FinQuant, including the Monte Carlo simulation results, the Efficient Frontier, optimal portfolios (Minimum Volatility, Maximum Sharpe Ratio), and individual stock data. ```python # Example script: ./example/Example-Optimisation.py (partially) # This is a conceptual example showing the idea of overlaying plots. # from finquant.portfolio import Portfolio # from finquant.efficient_frontier import EfficientFrontier # Assuming 'pf' is an instance of finquant.portfolio.Portfolio # 1. Plot Monte Carlo run (if available as a method) # pf.plot_monte_carlo_results(n_trials=10000) # 2. Compute and plot the Efficient Frontier # ef = EfficientFrontier(pf.ப்ட, pf.cov_matrix) # ef.plot_efrontier() # 3. Plot optimal portfolios on the same chart # ef.plot_optimal_portfolios() # 4. Plot individual stocks (if available as a method) # pf.plot_individual_stocks() print("Conceptual example for overlaying FinQuant visualizations.") ``` -------------------------------- ### Build Portfolio with Stock Data Source: https://github.com/fmilthaler/finquant/blob/master/README.md Demonstrates how to create a FinQuant Portfolio object by specifying stock names and a date range. This function fetches historical stock price data from the web. The output is a Portfolio instance, which can then be used for further analysis. ```python from finquant.portfolio import build_portfolio names = ['GOOG', 'AMZN', 'MCD', 'DIS'] start_date = '2015-01-01' end_date = '2017-12-31' pf = build_portfolio(names=names, start_date=start_date, end_date=end_date) ``` -------------------------------- ### Efficient Frontier Optimization in FinQuant Source: https://github.com/fmilthaler/finquant/blob/master/README.tex.md Implements portfolio optimization for minimum volatility, maximum Sharpe ratio, and efficient return/volatility targets using numerical solvers. It allows for visualization of the efficient frontier and optimal portfolios. ```python from finquant.efficient_frontier import EfficientFrontier # Assuming 'pf' is an instance of finquant.portfolio.Portfolio # Example: Optimize for minimum volatility robj_min_vol = EfficientFrontier(pf.ப்ட, pf.cov_matrix) min_vol_port = robj_min_vol.minimum_volatility() # Example: Optimize for maximum Sharpe ratio max_sharpe_port = robj_min_vol.maximum_sharpe_ratio() # Example: Optimize for efficient return robj_eff_ret = EfficientFrontier(pf.ப்ட, pf.cov_matrix) ret_target = 0.10 # Example target return eff_ret_port = robj_eff_ret.efficient_return(target_return=ret_target) # Example: Optimize for efficient volatility robj_eff_vol = EfficientFrontier(pf.ப்ட, pf.cov_matrix) vol_target = 0.20 # Example target volatility eff_vol_port = robj_eff_vol.efficient_volatility(target_volatility=vol_target) # Plotting the efficient frontier robj_min_vol.plot_efrontier() # Plotting optimal portfolios robj_min_vol.plot_optimal_portfolios() ``` -------------------------------- ### Perform Portfolio Optimization (Python) Source: https://github.com/fmilthaler/finquant/blob/master/README.md Executes a Monte Carlo simulation for portfolio optimization over 5000 iterations. It then plots the optimization results, the Efficient Frontier, optimal portfolios, and individual stock plots, providing comprehensive insights for investment strategies. ```Python # performs and plots results of Monte Carlo run (5000 iterations) opt_w, opt_res = pf.mc_optimisation(num_trials=5000) # plots the results of the Monte Carlo optimisation pf.mc_plot_results() # plots the Efficient Frontier pf.ef_plot_efrontier() # plots optimal portfolios based on Efficient Frontier pf.ef.plot_optimal_portfolios() # plots individual plots of the portfolio pf.plot_stocks() ``` -------------------------------- ### Build Portfolio Function in FinQuant Source: https://github.com/fmilthaler/finquant/blob/master/docs/portfolio.rst The `build_portfolio` function is a utility within the finquant.portfolio module used to construct a financial portfolio. It likely takes various parameters to define the portfolio's composition and characteristics. Specific input and output details are described in the function's signature and docstrings. ```python def build_portfolio(cash, df, stock_min_len=1, factor_min_len=1, factor_max_len=1, factor_min_weight=0.0, factor_max_weight=1.0, factor_greedy=True, factor_min_weight_fraction=0.0, factor_min_weight_value=0.0, stock_weight=0.0, stock_greedy=True, stock_min_weight_fraction=0.0, stock_min_weight_value=0.0) -> "Portfolio": """ Builds a Portfolio object. :param cash: Cash amount. :type cash: float :param df: DataFrame of factors and stocks prices. :type df: pandas.DataFrame :param stock_min_len: Minimum number of stocks. :type stock_min_len: int, optional :param factor_min_len: Minimum number of factors. :type factor_min_len: int, optional :param factor_max_len: Maximum number of factors. :type factor_max_len: int, optional :param factor_min_weight: Minimum weight for factors. :type factor_min_weight: float, optional :param factor_max_weight: Maximum weight for factors. :type factor_max_weight: float, optional :param factor_greedy: Whether to use greedy algorithm for factor weighting. :type factor_greedy: bool, optional :param factor_min_weight_fraction: Minimum fraction of weight for factors. :type factor_min_weight_fraction: float, optional :param factor_min_weight_value: Minimum value of weight for factors. :type factor_min_weight_value: float, optional :param stock_weight: Weight for stocks. :type stock_weight: float, optional :param stock_greedy: Whether to use greedy algorithm for stock weighting. :type stock_greedy: bool, optional :param stock_min_weight_fraction: Minimum fraction of weight for stocks. :type stock_min_weight_fraction: float, optional :param stock_min_weight_value: Minimum value of weight for stocks. :type stock_min_weight_value: float, optional :return: Portfolio object. :rtype: Portfolio """ pass ``` -------------------------------- ### Monte Carlo Simulation for Portfolio Optimization in FinQuant Source: https://github.com/fmilthaler/finquant/blob/master/README.tex.md Performs Monte Carlo simulations for portfolio optimization to find portfolios with minimum volatility and maximum Sharpe ratio. This method is included for completeness and visualization. ```python from finquant.portfolio import Portfolio # Assuming 'pf' is an instance of finquant.portfolio.Portfolio n_trials = 10000 # Number of Monte Carlo trials # Perform Monte Carlo simulation # The function to perform Monte Carlo simulation and plot results is often part of the Portfolio object or a related module. # Example usage might look like this, assuming a method exists: # pf.monte_carlo_simulation(n_trials=n_trials) # If plotting is integrated: # pf.plot_monte_carlo_optimized_portfolios(n_trials=n_trials) # The exact method call might vary based on the library's structure. # Referencing example scripts is recommended for precise implementation. print(f"Monte Carlo simulation with {n_trials} trials would be performed here.") ``` -------------------------------- ### Compute Moving Average Band with Signals (Python) Source: https://github.com/fmilthaler/finquant/blob/master/README.tex.md This snippet demonstrates how to fetch stock data for a specific ticker (DIS), compute a band of Exponential Moving Averages (EMAs) for various spans, and visualize them with buy/sell signals. It utilizes the `finquant` library for data fetching and moving average computation. ```python import finquant.portfolio as pf from finquant.moving_average import compute_ma, ema # get stock data for disney dis = pf.get_stock("DIS").data.copy(deep=True) spans = [10, 50, 100, 150, 200] ma = compute_ma(dis, ema, spans, plot=True) ``` -------------------------------- ### Plot Bollinger Bands with SMA (Python) Source: https://github.com/fmilthaler/finquant/blob/master/README.tex.md This code snippet illustrates how to retrieve stock data for Disney (DIS) and then plot Bollinger Bands using the Simple Moving Average (SMA). It requires the `finquant` library for stock data retrieval and plotting functions. ```python from finquant.moving_average import plot_bollinger_band, sma import finquant.portfolio as pf # get stock data for disney dis = pf.get_stock("DIS").data.copy(deep=True) span=20 plot_bollinger_band(dis, sma, span) ``` -------------------------------- ### Display Portfolio Data Head Source: https://github.com/fmilthaler/finquant/blob/master/README.md Retrieves and displays the first few rows of the historical stock price data stored within a FinQuant Portfolio object. This is useful for quickly inspecting the loaded data. ```python pf.data.head(3) ``` -------------------------------- ### Plot Bollinger Bands (Python) Source: https://github.com/fmilthaler/finquant/blob/master/README.md Fetches stock data for DIS and plots a Bollinger Band using the Simple Moving Average (SMA). Bollinger Bands are a common tool for measuring market volatility and identifying potential price reversals. ```Python from finquant.moving_average import plot_bollinger_band, sma # get stock data for disney dis = pf.get_stock("DIS").data.copy(deep=True) span=20 plot_bollinger_band(dis, sma, span) ``` -------------------------------- ### Compute and Plot Moving Averages Source: https://github.com/fmilthaler/finquant/blob/master/README.md This snippet shows how to compute moving averages using FinQuant's `compute_ma` and `ema` functions. It is a precursor to plotting band moving averages with buy/sell signals, but this specific code focuses only on the computation aspect. ```python from finquant.moving_average import compute_ma, ema ``` -------------------------------- ### Compute Moving Averages with Signals (Python) Source: https://github.com/fmilthaler/finquant/blob/master/README.md Retrieves stock data for DIS, computes Exponential Moving Averages (EMA) for specified spans, and plots them along with buy/sell signals. This function is useful for technical analysis to identify potential trading opportunities. ```Python dis = pf.get_stock("DIS").data.copy(deep=True) spans = [10, 50, 100, 150, 200] ma = compute_ma(dis, ema, spans, plot=True) ``` -------------------------------- ### Plot Cumulative Returns Source: https://github.com/fmilthaler/finquant/blob/master/README.md Calculates and plots the cumulative returns of the portfolio. It also adds a horizontal line at y=0 for reference, making it easy to visualize the overall performance trend over the specified period. ```python pf.comp_cumulative_returns().plot().axhline(y = 0, color = "black", lw = 3) ``` -------------------------------- ### Portfolio Class in FinQuant Source: https://github.com/fmilthaler/finquant/blob/master/docs/portfolio.rst The `Portfolio` class in `finquant.portfolio` represents and manages a financial portfolio. It likely stores information about assets, their weights, and potentially performance metrics. The class is designed to facilitate various portfolio management operations. ```python class Portfolio: """Portfolio management. :param cash: Cash amount. :type cash: float :param df: DataFrame of factors and stocks prices. :type df: pandas.DataFrame :param factor_min_len: Minimum number of factors. :type factor_min_len: int, optional :param factor_max_len: Maximum number of factors. :type factor_max_len: int, optional :param factor_min_weight: Minimum weight for factors. :type factor_min_weight: float, optional :param factor_max_weight: Maximum weight for factors. :type factor_max_weight: float, optional :param factor_greedy: Whether to use greedy algorithm for factor weighting. :type factor_greedy: bool, optional :param factor_min_weight_fraction: Minimum fraction of weight for factors. :type factor_min_weight_fraction: float, optional :param factor_min_weight_value: Minimum value of weight for factors. :type factor_min_weight_value: float, optional :param stock_weight: Weight for stocks. :type stock_weight: float, optional :param stock_greedy: Whether to use greedy algorithm for stock weighting. :type stock_greedy: bool, optional :param stock_min_weight_fraction: Minimum fraction of weight for stocks. :type stock_min_weight_fraction: float, optional :param stock_min_weight_value: Minimum value of weight for stocks. :type stock_min_weight_value: float, optional """ def __init__(self, cash: float, df: "DataFrame", factor_min_len: int = 1, factor_max_len: int = 1, factor_min_weight: float = 0.0, factor_max_weight: float = 1.0, factor_greedy: bool = True, factor_min_weight_fraction: float = 0.0, factor_min_weight_value: float = 0.0, stock_weight: float = 0.0, stock_greedy: bool = True, stock_min_weight_fraction: float = 0.0, stock_min_weight_value: float = 0.0): pass ``` -------------------------------- ### FinQuant Custom Data Types Source: https://github.com/fmilthaler/finquant/blob/master/docs/developers.rst Defines various custom data types used within the FinQuant library for type hinting and validation. These include array/list-like types, lists of dictionary keys, and numeric types. ```python from typing import Union, List, Dict, Any ARRAY_OR_LIST = Union[list, tuple, Any] ARRAY_OR_DATAFRAME = Union[list, tuple, pd.DataFrame, Any] ARRAY_OR_SERIES = Union[list, tuple, pd.Series, Any] SERIES_OR_DATAFRAME = Union[pd.Series, pd.DataFrame, Any] LIST_DICT_KEYS = List[Dict[str, Any]] FLOAT = float INT = int NUMERIC = Union[INT, FLOAT] ``` -------------------------------- ### FinQuant Type Validation Utility Source: https://github.com/fmilthaler/finquant/blob/master/docs/developers.rst Provides a utility function for type validation within the FinQuant library. This function facilitates the enforcement of expected data types for function arguments and variables. ```python from typing import Type, Any def type_validation(variable: Any, expected_type: Type[Any]) -> None: """Validate the type of a variable.""" if not isinstance(variable, expected_type): raise TypeError(f"Expected type {expected_type.__name__}, but got {type(variable).__name__}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.