optimization.py 文件源码

python
阅读 17 收藏 0 点赞 0 评论 0

项目:machine-learning-for-trading 作者: arjun-joshua 项目源码 文件源码
def optimize_portfolio(sd=dt.datetime(2008,1,1), ed=dt.datetime(2009,1,1), \
    syms=['GOOG','AAPL','GLD','XOM'], gen_plot=False):
    start_val = 1000000
    daily_rf = 0
    samples_per_year = 252
    # Read in adjusted closing prices for given symbols, date range
    dates = pd.date_range(sd, ed)
    prices_all = get_data(syms, dates)  # automatically adds SPY
    prices = prices_all[syms]  # only portfolio symbols
    prices_SPY = prices_all['SPY']  # only SPY, for comparison later

    # find the allocations for the optimal portfolio
    allocGuess = np.ones(len(syms), dtype = 'float32') / len(syms)
    setBnds = tuple( [(0,1) for x,y in enumerate(allocGuess)] )#create tuple of (0,1) tuples
    # 'constraints' below constrains allocations to sum to 1 
    # and 'setBnds' forces each allocation to lie in (0,1)
    srMax = spo.minimize(cost, allocGuess, bounds = setBnds, \
            constraints = ({ 'type': 'eq', 'fun': lambda inputs: 1.0 - np.sum(inputs) }), \
            args = (prices,start_val,daily_rf,samples_per_year,), \
            method = 'SLSQP', options = {'disp': True})
    allocs = srMax.x

    portVal = get_portfolio_value(prices, allocs, start_val)
    cr, adr, sddr, sr = get_portfolio_stats(portVal, daily_rf, samples_per_year)

    # Compare daily portfolio value with SPY using a normalized plot
    if gen_plot:
        df_temp = pd.concat([portVal, prices_SPY], keys=['Portfolio', 'SPY'], axis=1)
        plot_normalized_data(df_temp, 'Optimized portfolio values', 'date', \
                             'normalized price')

    return allocs, cr, adr, sddr, sr
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号