Mastering Portfolio Analysis with Python: Calculate Risk and Return | Can Python Predict Your Next Million-Dollar Investment?
Predicting Your Portfolio's Future: Unveiling the Code
Hey financial wizards and data enthusiasts! Today, we're diving into the world of Python and portfolio prediction. We'll be dissecting a code script that helps you estimate the future risk and return of your investment choices.
But first, a disclaimer: Predicting the market with absolute certainty is a fool's errand. This script is a tool to inform your decisions, not a magic crystal ball.
Now, let's crack the code!
The script utilizes the nselib
library to access historical stock data from the National Stock Exchange of India (NSE). Here's a breakdown of the key functions:
format_data
: This function takes a list of stock symbols and retrieves their closing prices for the past year. It then cleans and formats the data into a Pandas DataFrame for easy analysis.Expected_risk
: This function calculates the expected risk of your portfolio based on the weights assigned to each stock and their historical covariance (how their prices move together).Expected_return
: This function calculates the expected annual return of your portfolio by averaging the historical returns of each stock, weighted according to your investment allocation. It assumes 247 trading days in a year for simplicity.risk_return_calculation
: This is the heart of the script. It takes your portfolio allocation (a dictionary with symbols as keys and weights as values) and calculates both expected risk and return. It also allows you to choose between calculating returns using raw price changes or logarithmic returns (a more common approach in finance).
Code:
Code Snippet
from nselib import capital_market
import pandas as pd
from tqdm import tqdm
import numpy as np
symbols = {"ntpc":300, "nhpc":200, "itc":100}
def data_modeling(symbols:pd.Series):
filtered_data = pd.DataFrame()
total_itration = len(symbols)
with tqdm(total=total_itration) as progress_bar:
for symbol in symbols.values:
data = capital_market.price_volume_and_deliverable_position_data(symbol=symbol.upper(), period="1Y")
data = data.loc[data["Series"]=="EQ"]
filtered_data[symbol] = data["ClosePrice"].replace(",","").astype("float").values
progress_bar.update()
filtered_data = filtered_data.dropna()
return filtered_data
def expected_risk(weight, cov_matrix):
return np.sqrt(weight.T @ cov_matrix @weight)
def expected_return(weight, return_list):
return np.sum(return_list.mean()*weight)*len(return_list.index)# len(return_list.index) => No. of dayes traded in year
def risk_and_return(portfoliyo:dict): # portfoliyo = {"share_1":amount invested (int), "share_2":amount invested(int), .......}
share_list = pd.Series(portfoliyo.keys()).str.upper()
sum_weights = np.sum(list(portfoliyo.values()))
weights = np.array([(w/sum_weights) for w in list(portfoliyo.values())])#(amount invested / sum of weights), (amount invested 2/ sum of weights), ..........
portfoliyo_data = data_modeling(share_list)
returns = round(np.log(portfoliyo_data/portfoliyo_data.shift(1)),4) # 0.1387, -1.9172, .........
returns = returns.dropna()
covarence_matrix = returns.cov()*len(portfoliyo_data.index)
estimated_risk = expected_risk(weight=weights, cov_matrix=covarence_matrix)
estimated_return = expected_return(weight=weights, return_list=returns)
return round(estimated_risk*100,2), round(estimated_return*100,2)
risk, returns = risk_and_return(symbols)
print(f"\n\nEstimated risk of upcoming year: {risk}%\n",
f"Estimated return of upcoming year: {returns}%")
# Example
# Portfolio should be in the format {"NSE Symbol": Amount_Invested}, where Amount_Invested can be a single number or written as quantity*average_price
# Portfolio = {"advanihotr":4*70.50, "axisbank": 3*1126.34, "harsha":3*515.69, "hdfclife":3*697.69, "nbcc":2*138.17, "ncc":7*326.30,"olaelec":26*88.98}
# Expected_Risk, Expected_Return = Portfolio_Prediction().risk_return_calculation(Portfolio)
# print("Expected Risk/Return for the period of 1 Year", "\n",
# "\nPortfolio Expected Risk: ", Expected_Risk, '\n',
# "Portfolio Expected Return: ", Expected_Return
# )
Using the Script:
- Install required libraries: You'll need
nselib
,pandas
,numpy
, andtqdm
(for progress bar). - Define your portfolio: Create a dictionary where keys are stock symbols and values are the percentage you want to invest in each.
- Run the script: Pass your portfolio dictionary and desired return calculation method (normal or logarithmic) to the
risk_return_calculation
function. - Interpret the results: The function will return two values: expected risk (volatility) and expected annual return.
Remember:
- This script provides estimates based on historical data. Past performance is not a guarantee of future results.
- You should consider your risk tolerance and investment goals when building your portfolio.
- This is a starting point! Explore different libraries and models to further refine your predictions.
The Takeaway:
This code provides a valuable tool for understanding the potential risk and return of your portfolio. While it doesn't guarantee future performance, it empowers you to make informed investment decisions. As always, conduct your own research and never invest more than you can afford to lose.
Happy investing!
Comments
Post a Comment