Issue
I have a long list of Tickers and Weights that look something like this.
SP500 = ['MSFT', 'AAPL', 'AMZN', 'TSLA', 'GOOGL', 'GOOG', 'FB']
weight500 = [6, 5.9, 3, 2.5, 2.3, 2.1, 2]
I also have a list of screened stock tickers.
portfolio = ['MSFT', 'GOOGL', 'GOOG']
I need to get the index's of the portfolio stocks in the SP500 list and then use that to get their corresponding weight, which I then want to put in a dataframe.
I'm to create the dataframe by having 3 lists: index's, portfolio (stock name), weight.
This is how I plan on doing that:
EDIT: Adding the code itself as requested
import pandas as pd
index = [0, 4, 5]
portfolio = ['MSFT', 'GOOGL', 'GOOG']
weights = [6, 2.3, 2.1]
df = pd.DataFrame(list(zip(index, portfolio, weights)),
columns =['index', 'portfolio', 'weights'])
df
I'm struggling with putting these lists together. Now I can get the required information of individual stocks manually like this...
x = input('stock from portfolio:')
index = SP500.index(x)
print(index) #index
print(x) #ticker name
print(W500[index]) #weight
#For input MSFT
>> 0
>> MSFT
>> 6
I'm struggling with doing this for each stock in the list "portfolio" and putting all of the results into the three lists. I get that I have to loop through the "portfolio" list and basically do what I've just shown you, but I can't put all the steps together.
Does anyone have any tips as to how I could go about coding this? (and maybe also briefly explain the logic behind any potential solutions you have in mind).
Solution
Instead of manually doing you can use a loop.
SP500 = ['MSFT', 'AAPL', 'AMZN', 'TSLA', 'GOOGL', 'GOOG', 'FB']
weight500 = [6, 5.9, 3, 2.5, 2.3, 2.1, 2]
x = input('stock from portfolio:')
combined_lst = zip(SP500,weight500)
for i, info in enumerate(combined_lst):
if info[0] == x:
print(i)
print(x)
print(info[1])
break
OUTPUT
stock from portfolio:MSFT
0
MSFT
6
AND
Instead of manually putting index and weight and then converting it in a DataFrame you can manually do this.
import pandas as pd
SP500 = ['MSFT', 'AAPL', 'AMZN', 'TSLA', 'GOOGL', 'GOOG', 'FB']
weight500 = [6, 5.9, 3, 2.5, 2.3, 2.1, 2]
portfolio = ['MSFT', 'GOOGL', 'GOOG']
lst = []
for a in portfolio:
index = SP500.index(a)
weight = weight500[index]
lst.append([index,a,weight])
df = pd.DataFrame(lst)
print(df)
OUTPUT
Answered By - Sharim Iqbal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.