AI in Finance: Quantitative Analysis and Algorithmic Trading
Apply machine learning to financial markets and analysis
AI in Finance: Quantitative Analysis
Applications of AI in Finance
Sentiment Analysis for Markets
python
from transformers import pipeline
import pandas as pdFinancial sentiment analysis
sentiment_pipeline = pipeline(
"text-classification",
model="ProsusAI/finbert" # Trained on financial text
)news_headlines = [
"Apple reports record quarterly earnings",
"Bitcoin crashes 20% amid regulatory fears",
"Fed raises interest rates unexpectedly"
]
for headline in news_headlines:
result = sentiment_pipeline(headline)[0]
print(f"{headline[:50]}... -> {result['label']}: {result['score']:.3f}")
Price Prediction with LSTM
python
import yfinance as yf
import numpy as np
from sklearn.preprocessing import MinMaxScaler
import torch.nn as nnDownload historical data
data = yf.download('AAPL', start='2020-01-01', end='2024-01-01')
prices = data['Close'].valuesNormalize
scaler = MinMaxScaler()
scaled_prices = scaler.fit_transform(prices.reshape(-1, 1))Create sequences for LSTM
def create_sequences(data, seq_len=60):
X, y = [], []
for i in range(seq_len, len(data)):
X.append(data[i-seq_len:i, 0])
y.append(data[i, 0])
return np.array(X), np.array(y)
Portfolio Optimization
python
import scipy.optimize as optdef optimize_portfolio(returns: pd.DataFrame, risk_tolerance: float) -> dict:
n = len(returns.columns)
def negative_sharpe(weights):
portfolio_return = np.sum(returns.mean() * weights) * 252
portfolio_std = np.sqrt(
np.dot(weights.T, np.dot(returns.cov() * 252, weights))
)
return -(portfolio_return - 0.02) / portfolio_std # Risk-free: 2%
constraints = [{'type': 'eq', 'fun': lambda x: np.sum(x) - 1}]
bounds = [(0, 1)] * n
result = opt.minimize(
negative_sharpe,
x0=np.ones(n) / n,
bounds=bounds,
constraints=constraints
)
return dict(zip(returns.columns, result.x))
Risk Management with AI
Regulatory Considerations
Also available in 中文.