I have over a hundred stocks (actually crypto but that does not matter) I wish to plot, all on the same line plot.
JavaScript
x
16
16
1
PriceTimeList = []
2
# Then I populate the PriceTimeList with dictionaries, one for each stock
3
getData()
4
# I iterate through i, for example, i = "BTC-PERP", i = "APPL-PERP"
5
# Under 'price' key, I have priceList which is a list of closing prices
6
# And I have it similarly or 'time' key
7
PriceTimeList.append({
8
'name': i,
9
'price': priceList,
10
'time': timeList
11
})
12
# I create a dataframe from the list of dictionaries
13
PriceTimeDF = pd.DataFrame(PriceTimeList)
14
# I change the index to use the 'name' column of my dataframe
15
PriceTimeDF = PriceTimeDF.set_index('name')
16
I end up with a dataframe that looks like this:
JavaScript
1
15
15
1
┌──────────────┬──────────────────┬──────────────────────────────────────┐
2
│ │ │ │
3
│ │ price │ time │
4
├──────────────┼──────────────────┼──────────────────────────────────────┤
5
│ │ │ │
6
│ BTC-PERP │ [1,2,3,4,5] │ [1654052651, 1654052690, 1654052699] │
7
│ │ │ │
8
│ APPL-PERP │ [1,2,3,4,5] │ [1654052651, 1654052690, 1654052699] │
9
│ │ │ │
10
│ ETH-PERP │ [1,2,3,4,5] │ [1654052651, 1654052690, 1654052699] │
11
│ │ │ │
12
│ TSLA-PERP │ [1,2,3,4,5] │ [1654052651, 1654052690, 1654052699] │
13
│ │ │ │
14
└──────────────┴──────────────────┴──────────────────────────────────────┘
15
I don’t know how to make a line plot from this dataframe, I don’t even know if it is possible. Is there a way? Or is there a better way I should structure the data?
Advertisement
Answer
It maybe better if you transform the data as shown in example belo.
JavaScript
1
9
1
df = pd.DataFrame({
2
'stock': ['A', 'B'],
3
'price': [[10,20,30,40], [1,2,3,4]],
4
'time': [[1,2,3,4], [1,2,3,4]]
5
})
6
7
df = df.set_index(['stock']).apply(pd.Series.explode).reset_index()
8
df
9
stock | price | time |
---|---|---|
A | 10 | 1 |
A | 20 | 2 |
A | 30 | 3 |
A | 40 | 4 |
B | 1 | 1 |
B | 2 | 2 |
B | 3 | 3 |
B | 4 | 4 |
Then, use plotly.express
to plot the line chart of each stocks by using
JavaScript
1
3
1
import plotly.express as px
2
px.line(df, color='stock', x='time', y='price')
3
Output: