Learn how to use pandas for financial data analysis and fetch real market data using yfinance and pandas_datareader.
Understanding pandas DataFrame basics for financial data.
import pandas as pd
import numpy as np
# Create a DataFrame with stock data
data = {
'Symbol': ['AAPL', 'MSFT', 'GOOGL'],
'Price': [190.50, 375.00, 140.50],
'Shares': [100, 50, 75]
}
df = pd.DataFrame(data)
# Calculate position values
df['Position Value'] = df['Price'] * df['Shares']
# Basic statistics
print(df.describe()) # Summary statistics
print(df.groupby('Symbol').sum()) # Group by symbol
📚 Can't access the link? Use Perplexity.ai and search for "pandas DataFrame tutorial for finance"
Using yfinance and pandas_datareader to get real market data.
import yfinance as yf
import pandas_datareader as pdr
# Download Apple stock data
aapl = yf.download('AAPL',
start='2023-01-01',
end='2023-12-31')
# Calculate daily returns
aapl['Returns'] = aapl['Adj Close'].pct_change()
# Get multiple stocks using pandas_datareader
tickers = ['AAPL', 'MSFT', 'GOOGL']
portfolio = pdr.get_data_yahoo(tickers,
start='2023-01-01',
end='2023-12-31')['Adj Close']
# Calculate correlation matrix
correlation = portfolio.corr()
Working with financial time series in pandas.
# Resample data to monthly frequency
monthly = aapl['Adj Close'].resample('M').last()
# Calculate moving averages
aapl['MA50'] = aapl['Adj Close'].rolling(window=50).mean()
aapl['MA200'] = aapl['Adj Close'].rolling(window=200).mean()
# Generate trading signals
aapl['Signal'] = np.where(aapl['MA50'] > aapl['MA200'], 1, -1)
# Calculate returns by time period
returns = {
'Daily': aapl['Returns'].mean(),
'Monthly': aapl['Returns'].resample('M').mean(),
'Annual': aapl['Returns'].resample('Y').mean()
}
Use these prompts to enhance your learning: