我特定fn的代码是:
import pandas as pd
import sys, os, glob
from pandas import Panel
from datetime import datetime
import numpy as np
import scipy as sp
import scipy.optimize as scopt
import scipy.stats as spstats
from scipy.optimize import fmin
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from cvxopt import solvers
def create_portfolio(tickers, weights = None):
if (weights is None):
shares = np.ones(len(tickers)) / len(tickers)
portfolio = pd.DataFrame({'Tickers': tickers, 'Weights': weights}, index = tickers)
return portfolio
def calculate_weighted_portfolio_value(portfolio, returns, name = 'Value'):
total_weights = portfolio.Weights.sum()
weighted_returns = returns * (portfolio.Weights / total_weights)
return pd.DataFrame({name: weighted_returns.sum(axis = 1)})
def plot_portfolio_returns(returns, title = None):
returns.plot(figsize = (12, 8))
plt.xlabel('Year')
plt.ylabel('Returns')
if (title is not None): plt.title(title)
plt.show()
def get_historical_closes(ticker = ['Ticker'], start_date = ['1995-01-01'], end_date = ['2015-12-31']):
dfs = []
d = pd.DataFrame()
for files in glob.glob('/home/manish/Desktop/Equity/subset/*.txt'):
dfs.append(pd.read_csv(files, index_col = ['Date', 'Ticker', 'Close'], names = ['Ticker', 'Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Null'], parse_dates = [1]))
p = pd.concat(dfs)
del p['Null']
del p['Open']
del p['Volume']
del p['High']
del p['Low']
d = p.reset_index(['Ticker', 'Date', 'Close'])
#d = p.reindex(['Date', 'Ticker', 'Close'])
d = d[(d['Ticker'].isin(ticker)) & (d['Date'] > start_date) & (d['Date'] < end_date)]
pivoted = d.pivot_table(index = ['Date'], columns = ['Ticker'])
return pivoted
closes = get_historical_closes(['ASIANPAINT', 'BAYERCROP', 'BLUEDART', 'BOSCHLTD', 'BRITANNIA', 'COALINDIA', 'CUMMINSIND', 'EICHERMOT', 'EMAMILTD', 'GLAXO', 'GODREJCP', 'GSKCONS', 'HDFC', 'HINDUNILVR', 'HONAUT', 'HSI', 'ICRA', 'IVC', 'LAOPALA', 'LT', 'LUPIN', 'MARICO', 'MRF', 'NESTLEIND', 'OFSS', 'PAGEIND', 'PIDILITIND', 'SBIN', 'SUNPHARMA', 'TCS', 'THERMAX', 'TIDEWATER', 'TTKPRESTIG', 'UBL', 'ULTRACEMCO', 'ZEEL'], '1995-01-01', '2015-12-31')
print closes
def calc_daily_returns(pivoted):
return np.log(closes / closes.shift(1))
def calc_annual_returns(daily_returns):
grouped = np.exp(daily_returns.groupby(lambda date: date.year).sum()) - 1
return grouped
#todo Why var is nan?
def calc_portfolio_var(returns, weights = None):
if (weights is None):
weights = np.ones(returns.columns.size) / returns.columns.size
sigma = np.cov(returns.T, ddof = 0)
var = (weights * sigma * weights.T).sum()
return var
def sharpe_ratio(returns, weights = None, risk_free_rate = 0.06):
n = returns.columns.size
if weights is None: weights = np.ones(n) / n
var = calc_portfolio_var(returns, weights)
means = returns.mean()
return (means.dot(weights) - risk_free_rate) / np.sqrt(var)
def negative_sharpe_ratio_n_minus_1_stock(weights, returns, risk_free_rate):
weights2 = sp.append(weights, 1-np.sum(weights))
return negative_sharpe_ratio_n_minus_1_stock(returns, weights2, risk_free_rate)
def optimize_portfolio(returns, risk_free_rate):
maxrec = sys.getrecursionlimit()
w0 = np.ones(returns.columns.size - 1, dtype = float) * 1.0 / returns.columns.size
try:
w1 = fmin(negative_sharpe_ratio_n_minus_1_stock, w0, args = (returns, risk_free_rate))
final_w = sp.append(w1, 1 - np.sum(w1))
final_sharpe = sharpe_ratio(returns, final_w, risk_free_rate)
return (final_w, final_sharpe)
except RuntimeError as runerr:
print runerr
import sys
sys.setrecursionlimit(20000)
daily_returns = calc_daily_returns(closes)
annual_returns = calc_annual_returns(daily_returns)
calc_portfolio_var(annual_returns)
sharpe_ratio(annual_returns)
sharpe_ratio
optimize_portfolio(daily_returns, 0.06)
我收到错误:超出最大递归深度...我尝试设置更高的递归限制,但无济于事。如果有人使用cvxopt或任何其他方法建议任何其他语法,我可能也会感兴趣。