簡體   English   中英

使用python中的帶寬方法重新平衡組合

[英]Portfolio rebalancing with bandwidth method in python

我們需要計算不斷重新平衡的2只股票組合。 讓我們稱他們為A和B.他們都應該有相同的投資組合部分。 因此,如果我在我的投資組合中有100美元,則50美元投資A和50美元投資。由於兩只股票的表現差異很大,他們不會保持相同的權重(3個月后A已經可能值70美元而B降至45 $)。 問題是他們必須將他們在投資組合中的份額保持在一定的容忍帶寬內。 此帶寬為5%。 所以我需要一個功能:如果A> B * 1.05或A * 1.05 <B則重新平衡。

第一部分僅用於以最快的方式獲得一些數據以具有共同的討論基礎並使結果具有可比性,因此您只需復制並粘貼整個代碼即可。

import pandas as pd
from datetime import datetime
import numpy as np


df1 = pd.io.data.get_data_yahoo("IBM", 
                                start=datetime(1970, 1, 1), 
                                end=datetime.today())
df1.rename(columns={'Adj Close': 'ibm'}, inplace=True)

df2 = pd.io.data.get_data_yahoo("F", 
                                start=datetime(1970, 1, 1), 
                                end=datetime.today())
df2.rename(columns={'Adj Close': 'ford'}, inplace=True)

df = df1.join(df2.ford, how='inner')
del df["Open"]
del df["High"]
del df["Low"]
del df["Close"]
del df["Volume"]

現在開始用公式計算每種股票的相對表現:df.ibm / df.ibm [0]。 問題是,一旦我們打破第一個帶寬,我們需要在公式中重置0:df.ibm / df.ibm [0],因為我們重新平衡並需要從該點開始計算。 因此,我們將df.d用於此占位符函數,並在帶寬被破壞時將其設置為等於df.t df.t基本上只計算數據幀的長度,因此可以告訴我們“我們在哪里”。 所以這里開始實際計算:

tol = 0.05 #settintg the bandwidth tolerance
df["d"]= 0 # 
df["t"]= np.arange(len(df))
tol = 0.3

def flex_relative(x):
    if df.ibm/df.ibm.iloc[df.d].values < df.ford/df.ford.iloc[df.d].values * (1+tol):
        return  df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t
    elif df.ibm/df.ibm.iloc[df.d].values > df.ford/df.ford.iloc[df.d].values * (1+tol):
        return df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t
    else:
        return df.ibm/df.ibm.iloc[df.d].values, df.ford/df.ford.iloc[df.d].values



df["ibm_performance"], df["ford_performance"], = df.apply(flex_relative, axis =1)

問題是,我從最后一行代碼中得到這個錯誤,我嘗試用df.apply(flex_relative, axis =1)應用這個函數df.apply(flex_relative, axis =1)

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', u'occurred at index 1972-06-01 00:00:00')問題是錯誤語句的給定選項都沒有解決我的問題,所以我真的不知道該怎么做......

到目前為止我唯一發現的是下面的鏈接,但調用R函數對我來說不起作用,因為我需要將它應用於相當大的數據集,我也可以在這個函數中實現優化,所以它肯定需要是內置於python中。 無論如何,這里是鏈接: 財務Lib與python中的投資組合優化方法

手動(什么不是處理大數據的好方法),我計算出重新平衡的第一個日期是: 03.11.1972 00:00:00

第一次重新平衡時數據框的輸出應如下所示:

                     ibm        ford        d   t   ibm_performance ford_performance
1972-11-01 00:00:00 6,505655    0,387415    0   107 1,021009107 0,959552418
1972-11-02 00:00:00 6,530709    0,398136    0   108 1,017092172 0,933713605
1972-11-03 00:00:00 6,478513    0,411718    0   109 1,025286667 0,902911702 # this is the day, the rebalancing was detected
1972-11-06 00:00:00 6,363683    0,416007    109 110 1,043787536 0,893602752 # this is the day the day the rebalancing is implemented, therefore df.d gets set = df.t = 109
1972-11-08 00:00:00 6,310883    0,413861    109 111 1,052520384 0,898236364
1972-11-09 00:00:00 6,227073    0,422439    109 112 1,066686226 0,879996875

非常感謝你的支持!

@Alexander:是的,重新平衡將在第二天進行。

@maxymoo:如果您在此之后實施此代碼,您將獲得每個股票的投資組合權重,並且它們不會在45%到55%之間。 它相當於75%到25%之間:

df["ford_weight"] = df.ford_prop*df.ford/(df.ford_prop*df.ford+df.ibm_prop*df.ibm) #calculating the actual portfolio weights
df["ibm_weight"] = df.ibm_prop*df.ibm/(df.ford_prop*df.ford+df.ibm_prop*df.ibm)

print df
print df.ibm_weight.min()
print df.ibm_weight.max()
print df.ford_weight.min()
print df.ford_weight.max()

我試了一個小時左右才修好,但沒找到。

我可以做些什么來使這個問題更清楚嗎?

這里的主要思想是以美元而不是比率來工作。 如果您跟蹤ibm和福特股票的股票數量和相對美元價值,那么您可以將重新平衡的標准表達為

mask = (df['ratio'] >= 1+tol) | (df['ratio'] <= 1-tol)

比率等於的地方

    df['ratio'] = df['ibm value'] / df['ford value']

df['ibm value']df['ford value']代表實際的美元價值。


import datetime as DT
import numpy as np
import pandas as pd
import pandas.io.data as PID

def setup_df():
    df1 = PID.get_data_yahoo("IBM", 
                             start=DT.datetime(1970, 1, 1), 
                             end=DT.datetime.today())
    df1.rename(columns={'Adj Close': 'ibm'}, inplace=True)

    df2 = PID.get_data_yahoo("F", 
                             start=DT.datetime(1970, 1, 1), 
                             end=DT.datetime.today())
    df2.rename(columns={'Adj Close': 'ford'}, inplace=True)

    df = df1.join(df2.ford, how='inner')
    df = df[['ibm', 'ford']]
    df['sh ibm'] = 0
    df['sh ford'] = 0
    df['ibm value'] = 0
    df['ford value'] = 0
    df['ratio'] = 0
    return df

def invest(df, i, amount):
    """
    Invest amount dollars evenly between ibm and ford
    starting at ordinal index i.
    This modifies df.
    """
    c = dict([(col, j) for j, col in enumerate(df.columns)])
    halfvalue = amount/2
    df.iloc[i:, c['sh ibm']] = halfvalue / df.iloc[i, c['ibm']]
    df.iloc[i:, c['sh ford']] = halfvalue / df.iloc[i, c['ford']]

    df.iloc[i:, c['ibm value']] = (
        df.iloc[i:, c['ibm']] * df.iloc[i:, c['sh ibm']])
    df.iloc[i:, c['ford value']] = (
        df.iloc[i:, c['ford']] * df.iloc[i:, c['sh ford']])
    df.iloc[i:, c['ratio']] = (
        df.iloc[i:, c['ibm value']] / df.iloc[i:, c['ford value']])

def rebalance(df, tol, i=0):
    """
    Rebalance df whenever the ratio falls outside the tolerance range.
    This modifies df.
    """
    c = dict([(col, j) for j, col in enumerate(df.columns)])
    while True:
        mask = (df['ratio'] >= 1+tol) | (df['ratio'] <= 1-tol)
        # ignore prior locations where the ratio falls outside tol range
        mask[:i] = False
        try:
            # Move i one index past the first index where mask is True
            # Note that this means the ratio at i will remain outside tol range
            i = np.where(mask)[0][0] + 1
        except IndexError:
            break
        amount = (df.iloc[i, c['ibm value']] + df.iloc[i, c['ford value']])
        invest(df, i, amount)
    return df

df = setup_df()
tol = 0.05
invest(df, i=0, amount=100)
rebalance(df, tol)

df['portfolio value'] = df['ibm value'] + df['ford value']
df['ibm weight'] = df['ibm value'] / df['portfolio value']
df['ford weight'] = df['ford value'] / df['portfolio value']

print df['ibm weight'].min()
print df['ibm weight'].max()
print df['ford weight'].min()
print df['ford weight'].max()

# This shows the rows which trigger rebalancing
mask = (df['ratio'] >= 1+tol) | (df['ratio'] <= 1-tol)
print(df.loc[mask])

您可以使用此代碼在每個時間點計算您的投資組合。

i = df.index[0]
df['ibm_prop'] = 0.5/df.ibm.ix[i]
df['ford_prop'] = 0.5/df.ford.ix[i]

while i:
   try:
      i =  df[abs(1-(df.ibm_prop*df.ibm + df.ford_prop*df.ford)) > tol].index[0]
   except IndexError:
      break
   df['ibm_prop'].ix[i:] = 0.5/df.ibm.ix[i]
   df['ford_prop'].ix[i:] = 0.5/df.ford.ix[i]

只是對maxymoo答案的數學改進:

i = df.index[0]
df['ibm_prop'] = df.ibm.ix[i]/(df.ibm.ix[i]+df.ford.ix[i])
df['ford_prop'] = df.ford.ix[i]/(df.ibm.ix[i]+df.ford.ix[i])

while i:
   try:
      i =  df[abs((df.ibm_prop*df.ibm - df.ford_prop*df.ford)) > tol].index[0]
   except IndexError:
      break
   df['ibm_prop'].ix[i:] = df.ibm.ix[i]/(df.ibm.ix[i]+df.ford.ix[i])
   df['ford_prop'].ix[i:] = df.ford.ix[i]/(df.ibm.ix[i]+df.ford.ix[i])

那這個呢:

df["d"]= [0,0,0,0,0,0,0,0,0,0]
df["t"]= np.arange(len(df))
tol = 0.05

def flex_relative(x):
    if df.ibm/df.ibm.iloc[df.d].values < df.ford/df.ford.iloc[df.d].values * (1+tol):
        return  df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t
    elif df.ibm/df.ibm.iloc[df.d].values > df.ford/df.ford.iloc[df.d].values * (1+tol):
        return df.iloc[df.index.get_loc(x.name) - 1]['d'] == df.t

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM