The code works as intended but I believe it is very inefficient. The calculation of weights is simple, but I imagine this would be silly, for example, a 100 asset portfolio. The first problem is that my code returns to the beginning of the loop if the weight for y is entered incorrectly. Help with this would be amazing.
Secondly, as alluded to above, this is an inefficient approach. Someone entering 100 weights would not repeat this process. Any ideas where I could find some help for this approach would be great.
r_x=0.15
r_y=0.21
while True:
try: w_x=float(input("Enter the weight of stock x in your portfolio: "))
except ValueError:
print("Please enter the weight using numbers")
continue
else:
if w_x<0 or w_x>1: #seperating it instead of doing it altogether corrected this error for me
print("Please enter the number as a decimal. Remember, your maximum investment is 100%.")
continue
try: w_y=float(input("Enter the weight of stock y in your portoflio: "))
except ValueError:
print("Please enter the weight using numbers")
else:
if w_y<0 or w_y>1:
print("Please enter the numbers as a decimal. Remember, your maximum investment is 100%.")
continue
else:
if w_x+w_y<0 or w_x+w_y>1:
print("Remember, the total weight of the portfolio is 100%. The weights should add to 1.")
continue
else:
r_p=r_x*w_x+r_y*w_y
r_p=r_p*100
print("The total return on your portoflio is %.2f"%r_p +"%")
break
csv
module in the standard library. A CSV file can be created using a text editor or saved from Excel. Excel files can also be read directly, but it is a bit more involved and requires a 3rd-party library. \$\endgroup\$