主页 > 苹果下载imtoken教程 > Python+熊猫 | 分析比特币与股市的关系
Python+熊猫 | 分析比特币与股市的关系
- 点击上方“中国统计网”订阅我吧! -
通过我们使用 Python 和 Pandas 技术的分析,我们将能够在本文中回答这个问题。 首先,我们将使用免费 API 检索过去几年的比特币和股票价格。 然后我们将计算股市与比特币价格之间的相关性。 最后,我们将通过相关矩阵图绘制相关性来结束我们的分析。
自从比特币问世以来,我一直想知道比特币在我们的经济中扮演什么角色。 以下是对潜在角色的三个猜想:
让我们用 Python 看看吧!
使用 Python 检索股票市场价格和比特币价格
为了获取我们分析的数据,我将使用 financialmodelingprep API 来检索比特币价格。 他们还免费提供库存数据,但为了向您展示获取数据的两种不同方式,我将使用 Pandas DataReader 来检索库存数据。
作为我们市场数据的代理,我们将使用标准普尔 500 指数。 标准普尔 500 指数是衡量在美国上市的 500 家最大公司的股票表现的指数。 我们将使用 Pandas DataReader 下载 SP500 价格和美联储经济数据 (FRED) 作为来源。
如果您以前从未使用过 Pandas DataReader 和 Pandas,则需要安装该软件包。 您可以使用 pip 命令来执行此操作。
pip install pandas_datareader
#Pandas data reader may not work with the latest Pandas version,
therefore, I recommend you to install Pandas version 0.24:
pip install pandas==0.24.2
太好了,现在我们可以使用 Python 检索数据了。 首先,我们将提取过去十年的 S&P500 股票价格。 请注意,我们可以通过使用 web.DataReader 并指定系列名称(即 sp500 )和提供者(即 fred )轻松地从名为 SP500 的 Pandas 系列中获取数据。
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2020, 2, 10)
SP500 = web.DataReader(['sp500'], 'fred', start, end)
print(SP500)
上面的代码行将返回 Below S&P 500 系列,其中包含过去 10 年的 S&P 价格:
检索比特币价格
我们将使用 financialmodelingprep API。 我们将向 API 端点发出 http get 请求比特币的股票数据分析,该端点将返回包含 BTC 历史价格的字典:
import requests
#BTCUSD contains a dictionary
BTCUSD = requests.get(
'https://financialmodelingprep.com/api/v3/historical-price-full/crypto/BTCUSD')
BTCUSD = BTCUSD.json()
BTCUSD = BTCUSD['historical']
我们分析字典中包含的关键历史。
print(BTCUSD)
[{'date': '2020-02-15',
'open': 10315.651367,
'high': 10341.555664,
'low': 10226.138672,
'close': 10244.959961,
'adjClose': 10244.959961,
'volume': 42347495424.0,
'unadjustedVolume': 42347495424.0,
'change': 70.69141,
'changePercent': 0.685,
'vwap': 10270.88477,
'label': 'February 15, 20',
'changeOverTime': 0.00685},
{'date': '2020-02-14',
'open': 10211....
....
...]}
现在通过查看 BTCUSD 变量的内容,我们可以看到 BTCUSD 是一个字典列表,列表中的每个元素都是包含比特币价格的不同日期。 BTC 价格存储在关键收盘价之下。
例如,我们看到 2 月 15 日,比特币的价格为 10,244 美元。
我们需要将字典列表转换为 Pandas DataFrame。 我们可以使用 pd.DataFrame.from_dict() 轻松做到这一点:
BTC = pd.DataFrame.from_dict(BTCUSD)
BTC.set_index('date',inplace=True)
#Keep only the close column
BTC = BTC[['close']]
#Rename the column name to BTC
BTC.columns = ['BTC']
BTC
最后,我们在两个 Pandas DataFrame 中有 BTC 和 S&P 500 的价格。 现在我们只需要将它们合并在一起。 对我们来说幸运的是,使用 Python 和 Pandas 可以轻松做到这一点。
我们可以使用 pd.merge 将两个 DataFrame 连接到索引上,因为索引包含日期。 因此,我们希望在匹配日加入标准普尔 500 指数和 BTC 的价格。
我们可以传递等于 True 的 right_index 和 left_index 作为参数,让 Pandas 知道我们想要使用该索引进行合并。
SP500BTC = BTC.merge(SP500, how='inner',right_index = True,
left_index=True)
#Drop NA since we have nan values for weekends.
S&P500 only trades business days
SP500BTC.dropna(inplace=True)
print(SP500BTC)
比特币与标准普尔 500 指数价格之间的关系
很好,我们的数据已准备好进行分析。 现在我们可以继续寻找股票和比特币价格之间的关系。
为此,我们可以使用 pandas dataframe.corr() 来查找 Pandas DataFrame 列的相关性:
correlation = SP500BTC.corr()
print(correlation)
###Result:
BTC sp500
BTC 1.000000 0.834106
sp500 0.834106 1.000000
如何解释 BTC 与标普 500 的相关性?
相关矩阵的取值范围是-1到1。越接近+1意味着两个变量在同一个方向上移动的越近。 值为 0 表示变量之间没有关系。 负相关表明变量朝不同的方向移动。 越接近-1,反比关系越强。
通过检查我们的结果,我们发现比特币价格与标准普尔 500 指数之间存在 0.83 的强正相关性。这意味着当股市价格上涨时,我们可以预期比特币也会随之上涨。
from statsmodels import api as sm
import matplotlib.pyplot as plt
sm.graphics.plot_corr(correlation,xnames=list(correlation.columns))
plt.show()
情节的红色意味着这种关系是牢固和积极的。 我们还可以使用 linregression 和 scipy.stats 检查这种关系是否具有统计显着性:
#statistically significant?
from scipy.stats import linregress
linregress(SP500BTC['sp500'],SP500BTC['BTC'])
#H0: BTC and Stock prices are not related
#Results:
LinregressResult(slope=8.956910705798713, intercept=-18068.59091142212,
rvalue=0.8341059841835341, pvalue=0.0, stderr=0.1673358700767462)
由于我们的 p 值小于 0.05,我们可以拒绝 H0,因此比特币的股票数据分析,我们可以从统计上说比特币和股票价格一起移动。
结尾
使用 Python 和 Pandas,我们分析了股市与比特币价格之间的关系。 根据我们的分析结果,可以说 BTC 和标准普尔 500 指数的价格走势相同。
了解这种关系是否也处于经济衰退周期中将会很有趣。 为了做这个分析,我们可能需要等待一段时间,因为过去几年我们一直生活在扩张性经济中。
请参阅下面的完整脚本:
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2020, 2, 10)
SP500 = web.DataReader(['sp500'], 'fred', start, end)
import requests
BTCUSD = requests.get('https://financialmodelingprep.com/api/v3/historical-price-full/crypto/BTCUSD')
BTCUSD = BTCUSD.json()
BTCUSD = BTCUSD['historical']
BTC = pd.DataFrame.from_dict(BTCUSD)
BTC.set_index('date',inplace=True)
BTC = BTC[['close']]
BTC.columns = ['BTC']
SP500BTC = BTC.merge(SP500,how='inner',right_index = True,
left_index=True)
SP500BTC.dropna(inplace=True)
correlation = SP500BTC.corr()
print(correlation)
from statsmodels import api as sm
import matplotlib.pyplot as plt
sm.graphics.plot_corr(correlation,xnames=list(correlation.columns))
plt.show()
#statistically significant?
from scipy.stats import linregress
linregress(SP500BTC['sp500'],SP500BTC['BTC'])
结尾。