Mathew K Analytics

Lesson 20 · Real-World Data Analytics

Finance Analytics Portfolio Project in Python: Multi-Asset Report | Data Analytics #20

A complete finance data analysis project: we recompute every headline number from the stock market lessons (volatility, minimum-variance portfolio,…

📓 Full notebook

Download .ipynb

Data Analytics 100, Video 20: Capstone, Building a Real Multi-Asset Portfolio Report#

  • Video twenty of the hundred-video real-world data analytics series, and the capstone of the Finance and Stock Market domain.
  • Recomputing every headline number fresh, from every real dataset used across this domain, into one consolidated real report.
  • Let's get into it.

This capstone is for learners who have worked through the Finance and Stock Market lessons and want to see the whole toolkit applied in one place. The business question is the kind a portfolio manager asks: across the assets we have studied, how risky is each one, does diversification help, does a simple trading rule beat holding, and which companies look like value?

You reload every dataset from this domain: Apple prices (aapl_clean.csv), Tesla prices (tsla_clean.csv), a merged Apple and Tesla return file, a 2007 multi-stock basket in long format (stock and value columns, including the S&P 500 index as GSPC), Ethereum price and on-chain data, and the S&P 500 fundamentals snapshot. Every headline number is recomputed from source rather than copied from earlier notebooks.

In this lesson you will:

  • recompute volatility, minimum-variance weights, backtest results, VaR and drawdowns
  • combine results into a 2x2 matplotlib dashboard, a metrics table and a written summary
  • run checks that confirm your report is complete and saved correctly

Prerequisites: this lesson assumes you have followed videos 11 to 19, or are comfortable with returns, rolling, pivot, covariance and drawdown calculations.

Part 1: Nine Videos, One Real Report#

A capstone report should rest on fresh calculations, because numbers copied from old notebooks can silently go out of date. This step imports pandas, numpy and matplotlib and loads the Apple and Tesla price files with parse_dates so dates become real datetimes. Note the Tesla file uses a lowercase date column and later a lowercase close column, while Apple uses Date and AAPL.Close. Inconsistent column names across sources are very common, and checking them before writing calculations saves debugging time. There is no output here.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
aapl = pd.read_csv('aapl_clean.csv', parse_dates=['Date'])
tsla = pd.read_csv('tsla_clean.csv', parse_dates=['date'])

Part 2: Real Data Foundation Recap#

Before building a report you should know the size of each source, so any surprising number can be traced back. The code loads the merged Apple and Tesla file, the 2007 multi-stock basket, the Ethereum data and the fundamentals snapshot, then prints each length in one tuple. The output (506, 756, 338, 1098, 158, 337) shows 506 Apple days, 756 Tesla days, 338 merged rows, 1,098 multi-stock rows, 158 Ethereum days and 337 companies. The multi-stock file is in long format, one row per stock per date, which is why its count is large.

merged = pd.read_csv('aapl_tsla_merged.csv', parse_dates=['Date'])
multi_stock = pd.read_csv('multi_stock_2007.csv', parse_dates=['Date'])
eth = pd.read_csv('eth_price_onchain.csv', parse_dates=['Date'])
fundamentals = pd.read_csv('sp500_fundamentals.csv')
len(aapl), len(tsla), len(merged), len(multi_stock), len(eth), len(fundamentals)
(506, 756, 338, 1098, 158, 337)

Part 3: Real Apple and Real Tesla, Fresh Volatility#

Annualised volatility is the common language for comparing risk across assets. pct_change().dropna() gives daily returns, .std() measures their spread, and multiplying by np.sqrt(252) scales a daily figure to a trading year. The output (24.3, 44.0) shows Apple at 24.3% and Tesla at 44.0%, so Tesla was roughly 1.8 times as volatile. Notice the Apple figure differs from the 21.8% typed into the crypto lesson's comparison table, a good example of why recomputing beats copying.

aapl_return = aapl['AAPL.Close'].pct_change().dropna()
tsla_return = tsla['close'].pct_change().dropna()
aapl_vol = round(aapl_return.std() * np.sqrt(252) * 100, 1)
tsla_vol = round(tsla_return.std() * np.sqrt(252) * 100, 1)
aapl_vol, tsla_vol
(np.float64(24.3), np.float64(44.0))

Part 4: Real Minimum-Variance Portfolio, Fresh#

A minimum-variance portfolio is the mix of assets with the lowest possible volatility. np.linspace(0, 1, 41) creates 41 Apple weights from 0% to 100% in 2.5% steps. The covariance matrix of daily returns, multiplied by 252 to annualise, feeds the two-asset portfolio variance formula, and np.argmin picks the weight with the smallest volatility. The output (0.8, 21.8) shows the lowest-risk mix is 80% Apple and 20% Tesla, with 21.8% volatility. That is lower than either stock alone, which is diversification at work.

weights_grid = np.linspace(0, 1, 41)
cov_matrix = merged[['AAPL_Return', 'TSLA_Return']].dropna().cov() * 252
portfolio_vols = [np.sqrt(w**2 * cov_matrix.iloc[0,0] + (1-w)**2 * cov_matrix.iloc[1,1] + 2*w*(1-w)*cov_matrix.iloc[0,1]) for w in weights_grid]
min_var_weight = weights_grid[np.argmin(portfolio_vols)]
round(min_var_weight, 2), round(min(portfolio_vols) * 100, 1)
(np.float64(0.8), np.float64(21.8))

Part 5: Real Diversification Benefit, Multi-Asset Set#

Diversification means combining assets so that their ups and downs partly cancel out. pivot turns the long multi-stock table into one column per stock, dropna() keeps only dates where all prices exist, and pct_change() gives returns. mean(axis=1) averages across the four stocks each day to form an equal-weight portfolio. The output (19.6, 25.9) shows the portfolio's volatility at 19.6%, against an average of 25.9% for the individual stocks. Combining four stocks cut risk by about a quarter without picking any winners.

wide_multi = multi_stock.pivot(index='Date', columns='stock', values='value').sort_index().dropna()
multi_returns = wide_multi.pct_change().dropna()
stock_cols = ['AAPL', 'MSFT', 'IBM', 'SBUX']
equal_weight_vol = round(multi_returns[stock_cols].mean(axis=1).std() * np.sqrt(252) * 100, 1)
avg_individual_vol = round(multi_returns[stock_cols].std().mean() * np.sqrt(252) * 100, 1)
equal_weight_vol, avg_individual_vol
(np.float64(19.6), np.float64(25.9))

Part 6: Real Technical Signal Snapshot#

A technical signal snapshot tells a reader where the trend stands right now. The code builds 20-day and 50-day simple moving averages with rolling(...).mean(), then compares their final values with .iloc[-1]. A Python conditional expression returns a readable label rather than True or False. The output is 'Bullish (SMA20 above SMA50)', meaning the short-term average sat above the long-term one at the end of the data. This is a description of the latest trend, not a forecast.

close = aapl['AAPL.Close']
sma20 = close.rolling(20).mean()
sma50 = close.rolling(50).mean()
latest_signal = 'Bullish (SMA20 above SMA50)' if sma20.iloc[-1] > sma50.iloc[-1] else 'Bearish (SMA20 below SMA50)'
latest_signal
'Bullish (SMA20 above SMA50)'

Part 7: Real Backtest Result, Recomputed#

Recomputing the backtest with the report's own settings confirms whether the trading rule actually adds value. The position is the 20/50 crossover signal lagged one day with shift(1) to avoid lookahead bias, diff().abs() flags position changes, and each change is charged 0.1%. Compounding with cumprod() gives the growth of $1. The output `(1.053, 1.059)` shows the strategy turning $1 into $1.053, slightly behind buy-and-hold at $1.059. With these slower moving averages, the crossover no longer beats simply holding.

position = (sma20 > sma50).astype(int).shift(1).fillna(0)
trade_flags = position.diff().abs().fillna(0)
net_strategy_return = position * aapl['AAPL.Close'].pct_change() - trade_flags * 0.001
strategy_growth = round((1 + net_strategy_return.fillna(0)).cumprod().iloc[-1], 3)
buyhold_growth = round((1 + aapl['AAPL.Close'].pct_change().fillna(0)).cumprod().iloc[-1], 3)
strategy_growth, buyhold_growth
(np.float64(1.053), np.float64(1.059))

Part 8: Real Crypto Volatility, Recomputed#

Including crypto in the report shows how far risk can vary across asset classes. The code calculates Ethereum's daily returns and annualises the standard deviation with np.sqrt(365), because crypto trades every day of the year, unlike stocks. The output is 190.8%, the same as in the crypto lesson, which confirms that calculation was reproducible. Mixing 252-day and 365-day conventions is correct here, but it is worth stating in any report so readers do not think it is an error.

eth_return = eth['PriceUSD'].pct_change().dropna()
eth_vol = round(eth_return.std() * np.sqrt(365) * 100, 1)
eth_vol
np.float64(190.8)

Part 9: Real Fundamentals Screen, Recomputed#

Recomputing the value screen keeps the fundamentals part of the report consistent with its source. The code drops rows missing Price/Earnings or Price/Book, then keeps companies with P/E between 0 and 15 and P/B below 3, joining conditions with &. The output, 45, is higher than the 38 found in the fundamentals lesson. The difference comes from cleaning: that lesson dropped rows missing any of nine valuation columns, while this one only requires two. Small changes to cleaning rules can change results, so always state them.

clean_funds = fundamentals.dropna(subset=['Price/Earnings', 'Price/Book'])
value_screen = clean_funds[(clean_funds['Price/Earnings'] < 15) & (clean_funds['Price/Earnings'] > 0) & (clean_funds['Price/Book'] < 3)]
len(value_screen)
45

Part 10: Real VaR and Real Max Drawdown, Recomputed#

VaR and maximum drawdown summarise downside risk in two complementary ways. np.percentile(aapl_return, 5) gives the 95% one-day historical VaR, the loss exceeded on about 5% of days. The drawdown uses cumprod() for growth, cummax() for the running peak, and .min() for the deepest fall. The output (-2.49, -32.1) matches the VaR lesson: about a 2.49% loss on a one-in-twenty bad day, and a worst peak-to-trough fall of about 32%.

aapl_var95 = round(np.percentile(aapl_return, 5) * 100, 2)
cumulative_aapl = (1 + aapl_return).cumprod()
aapl_max_dd = round(((cumulative_aapl - cumulative_aapl.cummax()) / cumulative_aapl.cummax()).min() * 100, 1)
aapl_var95, aapl_max_dd
(np.float64(-2.49), np.float64(-32.1))

Part 11: Building the Real Consolidated Dashboard#

A dashboard puts the key findings on one page for a busy reader. plt.subplots(2, 2) creates a grid of four charts, addressed as axes[row, col]. The panels show volatility by asset as bars, Apple's cumulative growth as a line, the diversification comparison, and strategy versus buy-and-hold growth. chr(10) inserts a line break inside bar labels. The figure is saved to capstone_finance_dashboard.png and closed, so nothing appears inline. Open it and check that each panel tells one clear story.

fig, axes = plt.subplots(2, 2, figsize=(13, 10))
axes[0, 0].bar(['Apple', 'Tesla', 'Ethereum'], [aapl_vol, tsla_vol, eth_vol], color=['steelblue', 'crimson', 'darkorange'])
axes[0, 0].set_title('Real Annualized Volatility (%)')
axes[0, 1].plot(aapl['Date'].iloc[1:], cumulative_aapl, color='steelblue')
axes[0, 1].set_title('Real Apple Cumulative Growth')
axes[1, 0].bar(['Equal-Weight' + chr(10) + 'Portfolio', 'Avg Individual' + chr(10) + 'Stock'], [equal_weight_vol, avg_individual_vol], color=['seagreen', 'gray'])
axes[1, 0].set_title('Real Diversification Benefit (%)')
axes[1, 1].bar(['SMA Crossover' + chr(10) + '(Net)', 'Buy and Hold'], [strategy_growth, buyhold_growth], color=['purple', 'gray'])
axes[1, 1].set_title('Real Growth of $1, Strategy vs Buy-Hold')
plt.tight_layout()
plt.savefig('capstone_finance_dashboard.png', dpi=120)
plt.close()

Part 12: Real Metrics Table#

A metrics table is the reference sheet behind the charts: precise numbers in one place. The code builds a DataFrame with a Metric and a Value column, saves it with to_csv(index=False), and displays it. The output lists ten metrics, including volatility of 24.3% for Apple, 44.0% for Tesla and 190.8% for Ethereum, an 80% minimum-variance Apple weight, 1.053 versus 1.059 growth, and 45 value-screen companies. Mixing units in one column is convenient, so label each metric clearly, as done here with (%) and ($1 to).

metrics_table = pd.DataFrame({'Metric': ['Apple Annualized Vol (%)', 'Tesla Annualized Vol (%)', 'Ethereum Annualized Vol (%)', 'Min-Variance Apple Weight', 'Equal-Weight Portfolio Vol (%)', 'SMA Crossover Net Growth ($1 to)', 'Buy-and-Hold Growth ($1 to)', 'Apple VaR 95% (%)', 'Apple Max Drawdown (%)', 'Value Screen Company Count'], 'Value': [aapl_vol, tsla_vol, eth_vol, round(min_var_weight, 2), equal_weight_vol, strategy_growth, buyhold_growth, aapl_var95, aapl_max_dd, len(value_screen)]})
metrics_table.to_csv('capstone_finance_metrics.csv', index=False)
metrics_table
Metric Value
0 Apple Annualized Vol (%) 24.300
1 Tesla Annualized Vol (%) 44.000
2 Ethereum Annualized Vol (%) 190.800
3 Min-Variance Apple Weight 0.800
4 Equal-Weight Portfolio Vol (%) 19.600
5 SMA Crossover Net Growth ($1 to) 1.053
6 Buy-and-Hold Growth ($1 to) 1.059
7 Apple VaR 95% (%) -2.490
8 Apple Max Drawdown (%) -32.100
9 Value Screen Company Count 45.000

Part 13: Real Written Executive Summary#

An executive summary turns numbers into plain sentences for people who will not read code or charts. The code builds a list of seven lines using f-strings that insert each recomputed value, for example converting the 0.8 weight to 80% Apple and 20% Tesla. The output, 7, just confirms the number of lines. To read the summary itself, run print(chr(10).join(summary_lines)). Generating text from variables means it updates automatically if the data changes.

summary_lines = []
summary_lines.append(f'FINANCE AND STOCK MARKET ANALYTICS - CAPSTONE SUMMARY')
summary_lines.append(f'Apple annualized volatility: {aapl_vol}% | Tesla: {tsla_vol}% | Ethereum: {eth_vol}%')
summary_lines.append(f'Minimum-variance Apple/Tesla portfolio: {round(min_var_weight*100)}% Apple, {round((1-min_var_weight)*100)}% Tesla')
summary_lines.append(f'Four-stock diversification cut volatility from {avg_individual_vol}% average to {equal_weight_vol}% combined')
summary_lines.append(f'SMA crossover strategy grew $1 to ${strategy_growth}, versus ${buyhold_growth} for buy-and-hold')
summary_lines.append(f'Apple one-day VaR at 95% confidence: {aapl_var95}%, maximum drawdown: {aapl_max_dd}%')
summary_lines.append(f'{len(value_screen)} S&P 500 companies passed a simple real value screen (P/E under 15, P/B under 3)')
len(summary_lines)
7

Part 14: Saving the Real Executive Summary#

Saving the summary as a text file means it can be emailed or attached without opening Python. The code opens a file in write mode with with open(..., 'w'), which closes it automatically, and joins the lines with chr(10), a newline character. It then reads the file back and checks it is not empty. The output True confirms content was written. A stronger check would compare saved_summary with the joined text exactly.

with open('capstone_finance_summary.txt', 'w') as f:
    f.write(chr(10).join(summary_lines))
with open('capstone_finance_summary.txt') as f:
    saved_summary = f.read()
len(saved_summary) > 0
True

Part 15: Real Sanity Check, All Metrics Present#

Before sharing a report you should confirm no metric is missing, since a blank cell can undermine trust in the whole document. notna() marks each value as present or missing, and .all() returns True only if every one is present. The output np.True_ confirms all ten metrics have values. Checks like this are quick to write and catch problems such as a failed calculation silently producing NaN.

metrics_table['Value'].notna().all()
np.True_

Part 16: Real Asset Class Volatility Ranking#

Ranking assets by volatility gives an at-a-glance view of relative risk. The code builds a pd.Series from a dictionary and sorts it with sort_values(ascending=False). The output ranks Ethereum first at 190.8%, then Tesla at 44.0% and Apple at 24.3%. Ethereum's volatility was more than four times Tesla's and almost eight times Apple's. Remember that the Ethereum figure covers a short, early period, so it is not directly comparable in time with the stock figures.

vol_ranking = pd.Series({'Apple': aapl_vol, 'Tesla': tsla_vol, 'Ethereum': eth_vol}).sort_values(ascending=False)
vol_ranking
Ethereum    190.8
Tesla        44.0
Apple        24.3
dtype: float64

Part 17: Real Domain Recap, Ten Lessons#

Listing the lessons covered gives the report a clear structure and reminds you how the pieces fit together. The code stores the ten lesson titles in a Python list and counts them with len(). The output, 10, confirms the domain had ten lessons, from acquiring stock data through portfolio theory, technical indicators, risk, backtesting, crypto, fundamentals and VaR to this capstone. A list like this can feed directly into the summary text if you want the report to describe its own scope.

domain_lessons = ['Acquiring Real Stock Data', 'Portfolio Efficient Frontier', 'Technical Indicators', 'Volatility and Rolling Risk', 'Correlation and Diversification', 'Backtesting a Strategy', 'Cryptocurrency Analysis', 'Company Fundamentals', 'VaR and Drawdown', 'This Capstone']
len(domain_lessons)
10

Part 18: Real Total Real Datasets Used#

Recording which data sources fed a report is basic good practice, because it lets others reproduce or question the results. The code lists the five distinct datasets and counts them. The output, 5, counts Apple prices, Tesla prices, the 2007 multi-asset basket, Ethereum data and the fundamentals snapshot. The merged Apple and Tesla file is not counted separately because it is derived from the two price series. In a professional report you would also note each source's date range.

datasets_used = ['Apple daily prices', 'Tesla daily prices', 'Five-asset 2007 basket', 'Ethereum price and on-chain data', 'S&P 500 fundamentals snapshot']
len(datasets_used)
5

Part 19: Real Reload Verification#

Reloading a saved file is the simplest proof that the export worked. The code reads capstone_finance_metrics.csv back with pd.read_csv and compares its row count with the original table. The output True shows all ten rows were saved. Note that after reloading, the Value column comes back as numbers, but any formatting such as percentages exists only in the metric names, which is why clear labelling matters.

reloaded_metrics = pd.read_csv('capstone_finance_metrics.csv')
reloaded_metrics.shape[0] == len(metrics_table)
True

Part 20: Real Final Recap Print#

A final one-line recap closes the report on a memorable figure. The f-string combines the number of datasets, the number of lessons, and the ratio of Ethereum to Apple volatility, rounded to one decimal place. The printed output reads: 5 datasets, 10 lessons, and 7.9 times more volatility in crypto than in Apple stock. Ratios like this communicate scale better than raw percentages for non-specialist readers.

print(f'Capstone complete: {len(datasets_used)} real datasets, {len(domain_lessons)} lessons, spanning {round(eth_vol/aapl_vol,1)}x more volatility in crypto than in Apple stock alone.')
Capstone complete: 5 real datasets, 10 lessons, spanning 7.9x more volatility in crypto than in Apple stock alone.

Part 21: Real Tesla Risk Metrics, Recomputed#

Applying the same risk measures to Tesla lets you compare it fairly with Apple. The code repeats the VaR and drawdown calculation on Tesla's returns. The output (-4.1, -40.1) shows a 95% one-day VaR of -4.1% and a maximum drawdown of -40.1%, against -2.49% and -32.1% for Apple. Tesla's bad days were about 1.6 times worse than Apple's. Writing this logic as a reusable function would avoid repeating the same lines for every asset.

tsla_var95 = round(np.percentile(tsla_return, 5) * 100, 2)
cumulative_tsla = (1 + tsla_return).cumprod()
tsla_max_dd = round(((cumulative_tsla - cumulative_tsla.cummax()) / cumulative_tsla.cummax()).min() * 100, 1)
tsla_var95, tsla_max_dd
(np.float64(-4.1), np.float64(-40.1))

Part 22: Real Correlation Matrix, Recomputed#

Beta measures how much a stock tends to move with the market: 1 means it moves in step, above 1 means it amplifies market moves. The code calculates the full correlation matrix with .corr(), which is stored but not displayed, then computes Microsoft's beta as its covariance with GSPC, the S&P 500 index, divided by the index's variance. The output, 0.951, means Microsoft moved almost one-for-one with the market in this period. Run fresh_corr.round(2) to see the correlation matrix.

fresh_corr = multi_returns.corr()
gspc_beta_msft = round(multi_returns['MSFT'].cov(multi_returns['GSPC']) / multi_returns['GSPC'].var(), 3)
gspc_beta_msft
np.float64(0.951)

Part 23: Real Negative Earnings Count, Recomputed#

Recomputing the count of loss-making companies keeps the fundamentals numbers consistent with the earlier lesson. The code drops rows without Earnings/Share, compares each value with zero, and .sum() counts the True values. The output, 24, matches the fundamentals lesson exactly. When a recomputed figure matches the original, you can be confident the calculation is reproducible; when it differs, as with the value screen, you need to explain why.

eps_clean = fundamentals.dropna(subset=['Earnings/Share'])
negative_eps_count = (eps_clean['Earnings/Share'] < 0).sum()
negative_eps_count
np.int64(24)

Part 24: Real Ethereum Max Drawdown, Recomputed#

Ethereum's maximum drawdown sets the extreme end of the risk range in this report. The code builds cumulative growth from daily returns with cumprod(), measures the gap below the running peak from cummax(), and takes the minimum. The output is -77.7%, matching the crypto lesson. At its worst, early Ethereum had lost more than three quarters of its peak value, a far deeper fall than either stock.

cumulative_eth = (1 + eth_return).cumprod()
eth_max_dd = round(((cumulative_eth - cumulative_eth.cummax()) / cumulative_eth.cummax()).min() * 100, 1)
eth_max_dd
np.float64(-77.7)

Part 25: Real Cross-Asset Drawdown Comparison#

A side-by-side drawdown table shows the worst-case experience for each asset in one view. The code builds a Series from the three maximum drawdowns and sorts it with sort_values(), which puts the most negative first. The output ranks Ethereum at -77.7%, Tesla at -40.1% and Apple at -32.1%. The order matches the volatility ranking, which is common but not guaranteed: a volatile asset with a strong uptrend can have a smaller drawdown than a calmer one in a long decline.

drawdown_comparison = pd.Series({'Apple': aapl_max_dd, 'Tesla': tsla_max_dd, 'Ethereum': eth_max_dd}).sort_values()
drawdown_comparison
Ethereum   -77.7
Tesla      -40.1
Apple      -32.1
dtype: float64

Part 26: Real Best Single Day Across All Assets#

Best single days show the upside extremes that attract investors to volatile assets. The code takes .max() of each asset's daily returns, converts to percentages, and sorts from highest to lowest. The output shows Ethereum's best day at 46.3%, Tesla's at 17.3% and Apple's at 6.5%. Extreme gains and extreme losses usually go together, so a large best day should always be read alongside the worst day.

best_days = pd.Series({'Apple': round(aapl_return.max() * 100, 1), 'Tesla': round(tsla_return.max() * 100, 1), 'Ethereum': round(eth_return.max() * 100, 1)})
best_days.sort_values(ascending=False)
Ethereum    46.3
Tesla       17.3
Apple        6.5
dtype: float64

Part 27: Real Worst Single Day Across All Assets#

Worst single days show the sharpest one-day losses investors had to absorb. The code takes .min() of each asset's returns and sorts with the most negative first. The output shows Ethereum's worst day at -23.7%, Tesla's at -13.9% and Apple's at -6.6%. Comparing with the best days, Apple's range is roughly symmetrical, while Ethereum's best day was about twice the size of its worst, consistent with the positive skew found in the crypto lesson.

worst_days = pd.Series({'Apple': round(aapl_return.min() * 100, 1), 'Tesla': round(tsla_return.min() * 100, 1), 'Ethereum': round(eth_return.min() * 100, 1)})
worst_days.sort_values()
Ethereum   -23.7
Tesla      -13.9
Apple       -6.6
dtype: float64

Part 28: Real Dividend-Paying Share, Recomputed#

The dividend share rounds out the fundamentals section of the report. Here notna() marks companies with a dividend yield, and .mean() on the True and False values gives the share that pay, which is then converted to a percentage. The output, 77.7%, matches the fundamentals lesson. This is a compact alternative to filtering and dividing lengths, and it is worth remembering: the mean of a boolean Series is always a proportion.

pct_paying_dividends = round(fundamentals['Dividend Yield'].notna().mean() * 100, 1)
pct_paying_dividends
np.float64(77.7)

Part 29: Real Total Real Trading Days Analyzed#

A total count of days analysed gives readers a sense of the evidence behind the report. The code adds the Apple, Tesla and Ethereum row counts to the multi-stock rows divided by 5 using integer division //, since that long-format file holds five assets per date. The output is 1,639 days. This is an approximate figure: the five-asset division assumes every date has all five assets, and the Apple and Tesla days overlap in calendar time rather than adding new periods.

total_days_analyzed = len(aapl) + len(tsla) + len(multi_stock) // 5 + len(eth)
total_days_analyzed
1639

Part 30: Real Companies Analyzed Count#

Stating how many companies were covered completes the report's description of its scope. The code counts rows in the fundamentals table with len(). The output, 337, is the number of S&P 500 companies in the snapshot. When presenting this, note that the index has around 500 members, so the analysis covers a large share but not the whole index, which matters for any market-wide claims.

total_companies_analyzed = len(fundamentals)
total_companies_analyzed
337

Wrap-Up: What You Learned#

  • A real capstone earns its name by recomputing headline numbers fresh from source data, not by copying cached results from earlier videos.
  • Stocks, crypto, and company fundamentals are three genuinely different real data shapes, time series, a second time series with far higher volatility, and a real cross-sectional snapshot.
  • Diversification, honest backtesting, and disciplined risk measurement are the real same three ideas that showed up again and again across this entire finance domain.
  • Volatility ranged from around twenty percent for Apple to well over one hundred fifty percent for early Ethereum, a real reminder that risk itself varies by orders of magnitude across asset classes.
  • This real ten-lesson domain used five independently sourced real datasets and zero synthetic data anywhere, real numbers from a real UCI-adjacent retail set all the way through crypto on-chain metrics.
  • Next domain: Marketing and Social Media Analytics, real text data, real engagement metrics, and a genuinely different set of real analytical tools.

Practice on your own

  1. Write a small function that takes a return Series and returns annualised volatility, 95% VaR and maximum drawdown, then use it to rebuild the Apple, Tesla and Ethereum figures in a single DataFrame.
  2. Calculate beta against GSPC for every stock in the multi-stock basket, not just Microsoft, and rank them from highest to lowest.
  3. Rerun the SMA crossover backtest with 10/30-day windows and with a 0.5% cost per trade, and add both results as new rows in the metrics table.

The next domain moves to Marketing and Social Media Analytics, with text data, engagement metrics and a different set of analytical tools.

🧠 Test yourself

Pick an answer to check it. Your best score is saved in this browser.

  1. What is the main idea of this capstone's approach to reporting numbers?

  2. Why does the report annualize Ethereum volatility with sqrt(365) but Apple with sqrt(252)?

  3. How does the capstone find the minimum-variance weight in the Apple/Tesla portfolio?

  4. The capstone builds position = (sma20 > sma50).astype(int).shift(1).fillna(0) and subtracts trade_flags * 0.001. What does the second part model?

  5. The capstone's dashboard compares diversified and undiversified risk. Which result would show a diversification benefit?

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. Given annualized volatilities for three assets as a dict {'Stock': 22.0, 'Stock2': 61.0, 'Crypto': 130.0}, build a sorted Series (highest first) and print the ratio of the highest to the lowest volatility rounded to 1 decimal.

    💡 Hint

    Use pd.Series(...).sort_values(ascending=False).

    ✅ Show solution
    import pandas as pd
    
    vols = pd.Series({'Stock': 22.0, 'Stock2': 61.0, 'Crypto': 130.0}).sort_values(ascending=False)
    print(vols)
    print('Ratio:', round(vols.iloc[0] / vols.iloc[-1], 1))
    
  2. Simulate daily returns for three assets over 400 days (seed 5): 'Stock' normal(0.0004, 0.012), 'Growth' normal(0.0006, 0.022), 'Crypto' normal(0.001, 0.04). Compute annualized vol (use 252 for the first two and 365 for Crypto), 95% historical VaR, and max drawdown for each, and print them as one table in percent.

    💡 Hint

    Build a list of dict rows, then a DataFrame.

    ✅ Show solution
    import numpy as np
    import pandas as pd
    
    rng = np.random.default_rng(5)
    specs = {
        'Stock': (0.0004, 0.012, 252),
        'Growth': (0.0006, 0.022, 252),
        'Crypto': (0.001, 0.04, 365),
    }
    rows = []
    for name, (mu, sd, days) in specs.items():
        r = pd.Series(rng.normal(mu, sd, 400))
        cum = (1 + r).cumprod()
        dd = (cum - cum.cummax()) / cum.cummax()
        rows.append({
            'Asset': name,
            'AnnVol%': round(r.std() * np.sqrt(days) * 100, 1),
            'VaR95%': round(np.percentile(r, 5) * 100, 2),
            'MaxDD%': round(dd.min() * 100, 1),
        })
    print(pd.DataFrame(rows))
    
  3. Build a mini capstone report with synthetic data: two assets A and B (300 days, seed 6; A normal(0.0005, 0.01), B normal(0.0003, 0.02)). Find the minimum-variance weight in A on a 41-point grid, compare the equal-weight (50/50) volatility with the average of the individual volatilities, backtest a 10/30 SMA crossover on a price built from A's returns (0.1% cost, lagged position), and write the key numbers into a list of summary lines that you print.

    💡 Hint

    Combine the covariance formula, a weight grid, and a lagged position with transaction costs.

    ✅ Show solution
    import numpy as np
    import pandas as pd
    
    rng = np.random.default_rng(6)
    a = pd.Series(rng.normal(0.0005, 0.01, 300))
    b = pd.Series(rng.normal(0.0003, 0.02, 300))
    
    # Minimum-variance weight on a grid
    cov = pd.concat([a, b], axis=1).cov() * 252
    grid = np.linspace(0, 1, 41)
    vols = [np.sqrt(w**2 * cov.iloc[0, 0] + (1 - w)**2 * cov.iloc[1, 1]
                    + 2 * w * (1 - w) * cov.iloc[0, 1]) for w in grid]
    w_min = grid[int(np.argmin(vols))]
    
    # Diversification: 50/50 vs average individual volatility
    ew_vol = ((a + b) / 2).std() * np.sqrt(252)
    avg_vol = (a.std() + b.std()) / 2 * np.sqrt(252)
    
    # SMA crossover backtest on A's price
    price = 100 * (1 + a).cumprod()
    signal = (price.rolling(10).mean() > price.rolling(30).mean()).astype(int)
    position = signal.shift(1).fillna(0)
    net = position * price.pct_change() - position.diff().abs().fillna(0) * 0.001
    strategy_growth = (1 + net.fillna(0)).cumprod().iloc[-1]
    buyhold_growth = (1 + price.pct_change().fillna(0)).cumprod().iloc[-1]
    
    lines = [
        f'Min-variance weight in A: {w_min:.2f}',
        f'50/50 vol {ew_vol*100:.1f}% vs average individual vol {avg_vol*100:.1f}%',
        f'SMA strategy growth {strategy_growth:.3f} vs buy-and-hold {buyhold_growth:.3f}',
    ]
    print('\n'.join(lines))
    

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.