On this tutorial, we dive deep into the superior capabilities of OpenBB to carry out complete portfolio evaluation and market intelligence. We begin by establishing a tech-focused portfolio, fetching historic market information, and computing key efficiency metrics. We then discover superior technical indicators, sector-level efficiency, market sentiment, and correlation-based danger evaluation. Alongside the way in which, we combine visualizations and insights to make the evaluation extra intuitive and actionable, guaranteeing that we cowl each the quantitative and qualitative facets of funding decision-making. Take a look at the Full Codes right here.
!pip set up openbb[all] --quiet
import warnings
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import openbb
from openbb import obb
pd.set_option('show.max_columns', None)
pd.set_option('show.width', 1000)
print("🚀 Superior OpenBB Monetary Evaluation Tutorial")
print("=" * 60)
We start by putting in and importing OpenBB together with important Python libraries for information evaluation and visualization. We configure our surroundings to suppress warnings, set show choices for pandas, and prepare to carry out superior monetary evaluation. Take a look at the Full Codes right here.
print("n📊 1. BUILDING AND ANALYZING A TECH PORTFOLIO")
print("-" * 50)
tech_stocks = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'NVDA']
initial_weights = [0.25, 0.20, 0.25, 0.15, 0.15]
end_date = datetime.now().strftime('%Y-%m-%d')
start_date = (datetime.now() - timedelta(days=365)).strftime('%Y-%m-%d')
portfolio_data = {}
portfolio_returns = pd.DataFrame()
successful_stocks = []
print(f"Fetching information from {start_date} to {end_date}...")
for i, image in enumerate(tech_stocks):
attempt:
information = obb.fairness.value.historic(image=image, start_date=start_date, end_date=end_date)
df = information.to_df()
if df.index.duplicated().any():
df = df[~df.index.duplicated(keep='first')]
portfolio_data[symbol] = df
returns = df['close'].pct_change().dropna()
portfolio_returns[symbol] = returns
successful_stocks.append(image)
print(f"✅ {image}: {len(df)} days of information")
besides Exception as e:
print(f"❌ Error fetching {image}: {str(e)}")
if successful_stocks:
successful_indices = [tech_stocks.index(stock) for stock in successful_stocks]
portfolio_weights = [initial_weights[i] for i in successful_indices]
total_weight = sum(portfolio_weights)
portfolio_weights = [w/total_weight for w in portfolio_weights]
print(f"n📋 Portfolio composition (normalized weights):")
for inventory, weight in zip(successful_stocks, portfolio_weights):
print(f" {inventory}: {weight:.1%}")
else:
portfolio_weights = []
print("n📈 2. PORTFOLIO PERFORMANCE ANALYSIS")
print("-" * 50)
if not portfolio_returns.empty and portfolio_weights:
weighted_returns = (portfolio_returns * portfolio_weights).sum(axis=1)
annual_return = weighted_returns.imply() * 252
annual_volatility = weighted_returns.std() * np.sqrt(252)
sharpe_ratio = annual_return / annual_volatility if annual_volatility > 0 else 0
max_drawdown = (weighted_returns.cumsum().increasing().max() - weighted_returns.cumsum()).max()
print(f"Portfolio Annual Return: {annual_return:.2%}")
print(f"Portfolio Volatility: {annual_volatility:.2%}")
print(f"Sharpe Ratio: {sharpe_ratio:.3f}")
print(f"Max Drawdown: {max_drawdown:.2%}")
print("n📊 Particular person Inventory Efficiency:")
for inventory in successful_stocks:
stock_return = portfolio_returns[stock].imply() * 252
stock_vol = portfolio_returns[stock].std() * np.sqrt(252)
print(f"{inventory}: Return {stock_return:.2%}, Volatility {stock_vol:.2%}")
else:
print("❌ No legitimate portfolio information obtainable for evaluation")
We construct a tech portfolio, fetch a 12 months of costs with OpenBB, compute normalized weights and each day returns, then consider efficiency, annual return, volatility, Sharpe, max drawdown, and evaluation stock-wise stats in actual time. Take a look at the Full Codes right here.
print("n🔍 3. ADVANCED TECHNICAL ANALYSIS")
print("-" * 50)
image="NVDA"
attempt:
price_data = obb.fairness.value.historic(image=image, start_date=start_date, end_date=end_date)
df = price_data.to_df()
df['SMA_20'] = df['close'].rolling(window=20).imply()
df['SMA_50'] = df['close'].rolling(window=50).imply()
df['EMA_12'] = df['close'].ewm(span=12).imply()
df['EMA_26'] = df['close'].ewm(span=26).imply()
df['MACD'] = df['EMA_12'] - df['EMA_26']
df['MACD_signal'] = df['MACD'].ewm(span=9).imply()
delta = df['close'].diff()
acquire = (delta.the place(delta > 0, 0)).rolling(window=14).imply()
loss = (-delta.the place(delta < 0, 0)).rolling(window=14).imply()
rs = acquire / loss
df['RSI'] = 100 - (100 / (1 + rs))
df['BB_middle'] = df['close'].rolling(window=20).imply()
bb_std = df['close'].rolling(window=20).std()
df['BB_upper'] = df['BB_middle'] + (bb_std * 2)
df['BB_lower'] = df['BB_middle'] - (bb_std * 2)
current_price = df['close'].iloc[-1]
current_rsi = df['RSI'].iloc[-1]
macd_signal = "BUY" if df['MACD'].iloc[-1] > df['MACD_signal'].iloc[-1] else "SELL"
price_vs_sma20 = "Above" if current_price > df['SMA_20'].iloc[-1] else "Beneath"
print(f"n{image} Technical Evaluation:")
print(f"Present Worth: ${current_price:.2f}")
print(f"RSI (14): {current_rsi:.2f} ({'Overbought' if current_rsi > 70 else 'Oversold' if current_rsi < 30 else 'Impartial'})")
print(f"MACD Sign: {macd_signal}")
print(f"Worth vs SMA(20): {price_vs_sma20}")
besides Exception as e:
print(f"Error in technical evaluation: {str(e)}")
print("n🏭 4. SECTOR ANALYSIS & STOCK SCREENING")
print("-" * 50)
sectors = {
'Know-how': ['AAPL', 'GOOGL', 'MSFT'],
'Electrical Automobiles': ['TSLA', 'RIVN', 'LCID'],
'Semiconductors': ['NVDA', 'AMD', 'INTC']
}
sector_performance = {}
for sector_name, shares in sectors.objects():
sector_returns = []
for inventory in shares:
attempt:
information = obb.fairness.value.historic(image=inventory, start_date=start_date, end_date=end_date)
df = information.to_df()
if df.index.duplicated().any():
df = df[~df.index.duplicated(keep='first')]
returns = df['close'].pct_change().dropna()
sector_returns.append(returns.imply() * 252)
besides Exception as e:
print(f"❌ Did not fetch {inventory}: {str(e)}")
proceed
if sector_returns:
avg_return = np.imply(sector_returns)
sector_performance[sector_name] = avg_return
print(f"{sector_name}: {avg_return:.2%} common annual return")
print("n📰 5. MARKET SENTIMENT ANALYSIS")
print("-" * 50)
for image in successful_stocks[:2]:
attempt:
information = obb.information.firm(image=image, restrict=3)
news_df = information.to_df()
print(f"n{image} Latest Information Headlines:")
for idx, row in news_df.iterrows():
print(f"• {row.get('title', 'N/A')[:80]}...")
break
besides Exception as e:
print(f"Information not obtainable for {image}: {str(e)}")
We run superior technical evaluation on NVDA, calculating SMAs, EMAs, MACD, RSI, and Bollinger Bands, to gauge momentum and potential entry/exit alerts. We then display sectors by annualized returns throughout Know-how, EVs, and Semiconductors, and we pull contemporary firm headlines to fold market sentiment into our thesis. Take a look at the Full Codes right here.
print("n⚠️ 6. RISK ANALYSIS")
print("-" * 50)
if not portfolio_returns.empty and len(portfolio_returns.columns) > 1:
correlation_matrix = portfolio_returns.corr()
print("nPortfolio Correlation Matrix:")
print(correlation_matrix.spherical(3))
portfolio_var = np.dot(portfolio_weights, np.dot(correlation_matrix *
(portfolio_returns.std().values.reshape(-1,1) *
portfolio_returns.std().values.reshape(1,-1)),
portfolio_weights))
portfolio_risk = np.sqrt(portfolio_var) * np.sqrt(252)
print(f"nPortfolio Danger (Volatility): {portfolio_risk:.2%}")
print("n📊 7. CREATING PERFORMANCE VISUALIZATIONS")
print("-" * 50)
if not portfolio_returns.empty:
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
fig.suptitle('Portfolio Evaluation Dashboard', fontsize=16)
cumulative_returns = (1 + portfolio_returns).cumprod()
cumulative_returns.plot(ax=axes[0,0], title="Cumulative Returns", alpha=0.7)
axes[0,0].legend(bbox_to_anchor=(1.05, 1), loc="higher left")
rolling_vol = portfolio_returns.rolling(window=30).std() * np.sqrt(252)
rolling_vol.plot(ax=axes[0,1], title="30-Day Rolling Volatility", alpha=0.7)
axes[0,1].legend(bbox_to_anchor=(1.05, 1), loc="higher left")
weighted_returns.hist(bins=50, ax=axes[1,0], alpha=0.7)
axes[1,0].set_title('Portfolio Returns Distribution')
axes[1,0].axvline(weighted_returns.imply(), shade="pink", linestyle="--", label="Imply")
axes[1,0].legend()
if len(correlation_matrix) > 1:
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', heart=0, ax=axes[1,1])
axes[1,1].set_title('Correlation Matrix')
plt.tight_layout()
plt.present()
print("n🎯 8. INVESTMENT SUMMARY & RECOMMENDATIONS")
print("-" * 50)
print("Portfolio Evaluation Full!")
print(f"✅ Analyzed {len(successful_stocks)} shares")
print(f"✅ Calculated {len(sector_performance)} sector performances")
print(f"✅ Generated technical indicators and danger metrics")
if not portfolio_returns.empty and len(successful_stocks) > 0:
best_performer = portfolio_returns.imply().idxmax()
worst_performer = portfolio_returns.imply().idxmin()
print(f"🏆 Greatest Performer: {best_performer}")
print(f"📉 Worst Performer: {worst_performer}")
print("n💡 Key Insights:")
print("• Diversification throughout tech sectors reduces portfolio danger")
print("• Technical indicators assist determine entry/exit factors")
print("• Common rebalancing maintains goal allocations")
print("• Monitor correlations to keep away from focus danger")
print("n🔧 Subsequent Steps:")
print("• Backtest totally different allocation methods")
print("• Add basic evaluation metrics")
print("• Implement automated alerts for technical alerts")
print("• Discover ESG and factor-based screening")
print("n" + "="*60)
print("OpenBB Superior Tutorial Full! 🎉")
print("Go to https://openbb.co for extra options and documentation")
We quantify portfolio danger through correlations and annualized volatility, visualize efficiency with cumulative returns, rolling volatility, return distribution, and a correlation heatmap, then conclude with greatest/worst performers, key insights (diversification, alerts, rebalancing), and concrete subsequent steps like backtesting, including fundamentals, alerts, and ESG screening.
In conclusion, we have now efficiently leveraged OpenBB to construct, analyze, and visualize a diversified portfolio whereas extracting sector insights, technical alerts, and danger metrics. We see how combining efficiency statistics with market sentiment and superior visualizations empowers us to make knowledgeable funding choices. This strategy permits us to repeatedly monitor and refine our methods, guaranteeing that we stay agile in altering market circumstances and assured within the data-driven selections we make.
Sana Hassan, a consulting intern at Marktechpost and dual-degree pupil at IIT Madras, is enthusiastic about making use of expertise and AI to handle real-world challenges. With a eager curiosity in fixing sensible issues, he brings a contemporary perspective to the intersection of AI and real-life options.