Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Create a code for portfolio rotation

I am trying to resolve this problem: I have a dataframe where in each rows I have the assets (true)that every month I buy for my portfolio. And another dataframe with the prices of all the assets. How can i do to code in python and create a portfolio that every month buy and sell the selected assets?

this is the dataframe Portfolio with the assets(cell True) to buy every month (I buy the last date of the month and sell the last date of the month after) and the dataframe 'stocks' with the close price of all the assets for the dates I need.

df=portfolio

  Date                      gld   spy  tlt   qqq    

2012-01-31 0 0 0 0
2012-02-29 True 0 0 True
2012-03-31 0 True 0 True
2012-04-30 0 True 0 True
2012-05-31 0 0 True True
2012-06-30 0 0 True True
2012-07-31 0 True 0 True
2012-08-31 0 True True 0
2012-09-30 True 0 0 True

df=stocks

date gld spy tlt qqq

2012-01-31 155.919998 110.244629 98.649094 52.541271
2012-02-29 169.559998 114.542015 98.678558 56.345661
2012-03-31 166.610001 119.090157 96.314247 59.946907
2012-04-30 162.940002 123.181374 93.626793 63.128780
2012-05-31 161.320007 122.226082 97.105934 61.852337
2012-06-30 157.500000 111.300957 108.948509 55.877071
2012-07-31 155.089996 119.166779 105.715599 59.658237
2012-08-31 155.139999 120.109573 108.087280 59.899284
2012-09-30 164.479996 123.112556 107.089935 63.125572
2012-10-31 172.289993 126.683434 104.870216 63.658878
2012-11-30 166.070007 125.349434 103.125450 61.241573
2012-12-31 166.130005 124.138336 105.279198 61.055622
2013-01-31 163.169998 129.093277 101.194321 62.826088
2013-02-28 161.449997 133.671555 98.009041 63.256145
2013-03-31 152.440002 134.440491 101.075859 62.994381
2013-04-30 154.669998 138.536224 100.860710 64.189705
2013-05-31 141.110001 140.515976 105.873268 65.960770
2013-06-30 136.509995 145.904724 98.229164 68.762642
2013-07-31 121.129997 144.008301 94.705444 67.410301
2013-08-31 126.610001 152.308197 90.600891 71.950691
2013-09-30 136.419998 146.712448 89.857086 71.349068
2013-10-31 124.589996 151.866791 91.458282 75.127335
2013-11-30 126.949997 158.027924 92.041725 78.078506
2013-12-31 117.580002 161.902130 89.829407 80.595940
2014-01-31 118.000000 164.936356 89.111214 82.54505

I would like to obtain a new column with this values= in row1 portfolio value=initial capital+initial capital*(price assets month1-price assets month2)\price asstes month1 in rows 2 portfolio value=portfolio value+portfolio value*(price asset month2-price assets month3)\price assets month2

etc etc i suppose for simplicity to divide in equal part the capital for the asset in portfolio ie 0.5 if i have 2 asset or 0,25 if i have 4 assets