如何编写一个循环函数,一次性制作单独的散点图?另外,如何添加最适合的行?

How do I write a loop function that will make separate scatterplots graphs all in one go? Also how do I add a line of best fit?

提问人:rocket 提问时间:11/14/2023 最后编辑:Reinderienrocket 更新时间:11/14/2023 访问量:34

问:

我知道如何制作单独的散点图,但我希望它们都放在一个视图中,并排放置。我还想为此视图中的每个图形添加一行最佳拟合线。我将所有这些股票行情与 SPY 指数进行比较,并显示回归。谢谢!

我尝试将东西放入数组中并创建子图,但这不起作用,所以现在我被卡住了。

import yfinance as yf, matplotlib.pyplot as plt, numpy as np

import pandas_datareader.data as reader 

import statsmodels.api as sm

import seaborn as sns

import pandas as pd

from scipy import stats

from dateutil.relativedelta import *

import getFamaFrenchFactors as gff

import datetime 

from sklearn.linear_model import LinearRegression

import pandas as pd

from xbbg import blp


tickers = ['JPM', 'C', 'BAC', 'MS', 'GS', 'WFC', 'BCS']

weights  = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])

today1= datetime.date.today() 
olddate1 = today1 - datetime.timedelta(weeks=26.5)

df_spy = yf.download('SPY', olddate1, today1)['Adj Close']
                      
today= datetime.date.today()
olddate = today - datetime.timedelta(weeks=26.5)

df = yf.download(tickers, olddate, today)['Adj Close']

fig,ax=plt.subplots(figsize=(10,10), nrows=2, ncols=1, sharex=True)
Scatter1=ax[0].scatter(x=df_spy.pct_change(), y = df[tickers[0]].pct_change(), c=)


plt.rcParams['axes.grid'] = False

plt.scatter(df_spy.pct_change(),df[tickers[0]].pct_change(), alpha =.6, color='blue', s=55)

plt.scatter(df_spy.pct_change(),df[tickers[1]].pct_change(), alpha =.6, color='blue', s=55)

plt.scatter(df_spy.pct_change(),df[tickers[2]].pct_change(), alpha =.6, color='blue', s=55)

plt.scatter(df_spy.pct_change(),df[tickers[3]].pct_change(), alpha =.6, color='blue', s=55)

plt.scatter(df_spy.pct_change(),df[tickers[4]].pct_change(), alpha =.6, color='blue', s=55)

plt.scatter(df_spy.pct_change(),df[tickers[5]].pct_change(), alpha =.6, color='blue', s=55)

plt.scatter(df_spy.pct_change(),df[tickers[6]].pct_change(), alpha =.6, color='blue', s=55)
Python 循环 回归 金融

评论

0赞 furas 11/14/2023
我记得它应该作为参数 - 像 等。但是你创建了,所以你只有 2 个字符的位置。您必须创建更多行或列axplt.scatter( ax=ax[0], ..)plt.scatter( ax=ax[1], ..)plt.subplots(.., nrows=2, ncols=1, ..)

答:

0赞 furas 11/14/2023 #1

使用当前代码,您可以使用更多位置放置绘图,然后使用 、 、 将绘图并排放置plt.subplots(..., nrows=2, ncols=7, ...)ax[0][0].scatter()ax[0][1].scatter()ax[1][6].scatter()

完整的工作代码:

import datetime 
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import yfinance as yf


tickers = ['JPM', 'C', 'BAC', 'MS', 'GS', 'WFC', 'BCS']

weights = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])

today = datetime.date.today() 

olddate = today - datetime.timedelta(weeks=26.5)
df_spy = yf.download('SPY', olddate, today)['Adj Close']
df = yf.download(tickers, olddate, today)['Adj Close']

fig, ax = plt.subplots(figsize=(10,10), nrows=2, ncols=7, sharex=True)

ax[0][0].scatter(x=df_spy.pct_change(), y=df[tickers[0]].pct_change())
ax[0][0].set_title('SPY')

plt.rcParams['axes.grid'] = False

for index, item in enumerate(tickers):
    ax[1][index].scatter(df_spy.pct_change(), df[item].pct_change(), alpha=.6, color='blue', s=55)
    ax[1][index].set_title(item)

#plt.tight_layout()
plt.show()

但这给了空旷的地方。

enter image description here


使用您可以更好地控制绘图并创建一个更大的绘图(上图)和许多小绘图(下图)。plt.subplot(rows, cols, index)

import datetime 
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import yfinance as yf


tickers = ['JPM', 'C', 'BAC', 'MS', 'GS', 'WFC', 'BCS']

weights = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])

today = datetime.date.today() 

olddate = today - datetime.timedelta(weeks=26.5)
df_spy = yf.download('SPY', olddate, today)['Adj Close']
df = yf.download(tickers, olddate, today)['Adj Close']

fig = plt.figure(figsize=(10,10))

ax = plt.subplot(2,1,1)  # (rows, cols, index)
ax.scatter(x=df_spy.pct_change(), y=df[tickers[0]].pct_change())
ax.set_title('SPY')

plt.rcParams['axes.grid'] = False

for index, item in enumerate(tickers):
    ax = plt.subplot(2, 7, index+1+7)  # (rows, cols, index)
    ax.scatter(df_spy.pct_change(), df[item].pct_change(), alpha=.6, color='blue', s=55)
    ax.set_title(item)

#plt.tight_layout()
plt.show()

enter image description here