Financial Portfolio Comparison
Tags: python, pandas, yfinance, beginners
Published: 2023-09-26 16:02:13

In this post, I will talk about the two portfolio comparison software I wrote. My goal is to be useful to those who develop software about financial markets. The libraries I use in the code are yfinance, pandas and matplotlib respectively.

First, let's start with the first code. This Python code is used to compare the performance of a specific portfolio (We call it Bayford Commodity Portfolio) and the GSCI Index over a specific period.

```
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from datetime import datetime

index = yf.Ticker("GD=F") # 
index_data = index.history(period="max")
symbols = ["SB=F", "ZL=F", "KC=F", "ZS=F", "ZO=F", "OJ=F"]

data = {}
for symbol in symbols:
    stock = yf.Ticker(symbol)
    stock_data = stock.history(period="max")
    data[symbol] = stock_data['Close']

portfolio_index = pd.DataFrame(data).mean(axis=1)

end_date = datetime.today().strftime('%Y-%m-%d')
start_date = "2022-09-26"
index_comparison = index_data.loc[start_date:end_date]
portfolio_comparison = portfolio_index.loc[start_date:end_date]

gsci_return = (index_comparison['Close'][-1] - index_comparison['Close'][0])/index_comparison['Close'][0]

portfolio_return = (portfolio_comparison[-1] - portfolio_comparison[0])/portfolio_comparison[0]

print(f"GSCI INDEX: {gsci_return:.2%}")
print(f"BAYFORD COMMODITY PORTFOLIO: {portfolio_return:.2%}")

index_normalized = index_comparison['Close']/index_comparison['Close'][0]
portfolio_normalized = portfolio_comparison/portfolio_comparison[0]

plt.style.use('dark_background')
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(index_normalized, label="GSCI INDEX")
ax.plot(portfolio_normalized, label="BAYFORD COMMODITY PORTFOLIO")
text = plt.text(0.5, 0.5, 'BAYFORD ANALYTICS', fontsize=40, color='gray', ha='center', va='center', alpha=0.5, transform=ax.transAxes)
plt.savefig('myfigure.png', dpi=900)
plt.legend()
plt.show()
```

Using the yfinance library, I pulled historical data of specific stocks and the GSCI Index. I used this data to create a portfolio that included the average of the closing prices of stocks over a specific period. Then, I calculated the return of both the GSCI Index and the portfolio created exactly 1 year ago to date. Then, I normalized these two portfolio data so that we could see the difference more easily when we visualized them. Normalizing does not change the result, but it does change how easily we can see the result on the graph. Therefore, especially if the chart is long-term, it is much easier to make comparisons as the price change is larger. Finally, I took help from the matplotlib library to visualize these two returns.

Now there is the second code. This code, like the other one, shows the difference between portfolios.

```
import yfinance as yf
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt

symbols = ["SB=F", "ZL=F", "KC=F", "ZS=F", "ZO=F", "OJ=F"]
weights = [1/6, 1/6, 1/6, 1/6, 1/6, 1/6]

start_date = "2022-09-26"
end_date = "2023-09-26"

data = yf.download(symbols, start=start_date, end=end_date)['Adj Close']

daily_returns = data.pct_change()

portfolio_returns = daily_returns.dot(weights)

total_return = (portfolio_returns + 1).prod() - 1

print(f"Portfolio Return: {total_return:.2%}")

index = yf.Ticker("GD=F") # 
index_data = index.history(start=start_date, end=end_date)

index_return = (index_data['Close'][-1] - index_data['Close'][0])/index_data['Close'][0]

print(f"GSCI Index Return: {index_return:.2%}")

# Creating a graph
portfolio_normalized = (portfolio_returns + 1).cumprod()
index_normalized = index_data['Close']/index_data['Close'][0]

fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(index_normalized, label="GSCI INDEX")
ax.plot(portfolio_normalized, label="BAYFORD COMMODITY PORTFOLIO")
text = plt.text(0.5, 0.5, 'BAYFORD ANALYTICS', fontsize=40, color='gray', ha='center', va='center', alpha=0.5, transform=ax.transAxes)
plt.savefig('myfigure.png', dpi=900)
plt.legend()
plt.show()

```

Both codes compare the performance of a particular portfolio and the GSCI Index. However, these codes use different calculation methods, which leads to different results. In the first code, portfolio return is calculated as the average of closing prices of stocks over a given period. This assumes each stock has equal weight in the portfolio. In the second code, the portfolio return is calculated as the average of the daily return (percentage change) of each stock. This assumes that each stock has a certain weight in the portfolio. These weights are often based on an investment strategy or risk tolerance. These two different calculation methods represent different investment strategies and risk tolerances and therefore produce different results. The first method represents an investment strategy in which all stocks are equally important, while the second method represents an investment strategy that gives greater weight to certain stocks.

I hope these projects will help those who want to develop portfolio management software at the entry level.