Return results from a loop for varying portfolio weights into a dataframe in Pandas
<p>I am about to create a portfolio of two assets and would like to vary the weights by a loop, with the weights for the first asset from [-0.5, -0.4, ... 0.4, 0.5]
I manage to calculate the risk return points for each of the 11 portfolios by a loop. Nevertheless, the loop creates a new dataframe for each risk/return combination, whereas I would like to create one single dataframe containing all the risk/return points. </p>

<p>Here's my code: </p>

<pre><code>def imply_x (returns, x):
y = 1-x
returns.columns = ["A","B"]
weighted_return = returns.A * x + returns.B * y
name = str(round(x,2)) + "a"
return pd.DataFrame({name: weighted_return})
def frange (start, stop, step):
x = start
while x &lt; stop:
    yield x
    x += step
for x in frange (-0.5,0.6,0.1):
mean_ret = np.mean(imply_x(ret,x))
var_ret = np.percentile(imply_x(ret,x),95)
tuple_ret = pd.DataFrame({"risk": var_ret, "mean": mean_ret})
print((tuple_ret))
</code></pre>

<p>And here's the result</p>

<pre><code>           mean      risk
-0.5a  0.000181  0.018354
           mean      risk
-0.4a  0.000166  0.015611
           mean      risk
-0.3a  0.000151  0.012688
           mean    risk
-0.2a  0.000136  0.0099
           mean      risk
-0.1a  0.000121  0.007454
           mean      risk
-0.0a  0.000106  0.005405
          mean      risk
0.1a  0.000092  0.004576
          mean      risk
0.2a  0.000077  0.005007
          mean      risk
0.3a  0.000062  0.006613
          mean      risk
0.4a  0.000047  0.008738
          mean      risk
0.5a  0.000032  0.011082
</code></pre>

<p>I'd be thankful if anyone helped me on how to paste the results from the loop into one single data frame</p>

<p>You can use <code>pd.concat</code> to create a single dataframe out of them.</p>

<p><a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-objects</a></p>

python loops dataframe weight portfolio