使用Pandas识别财务数据中的极值

时间:2016-01-14 20:46:38

标签: python numpy pandas matplotlib scipy

我每天都有S& P 500价格和国债收益率。最终目标是在S& P的修正期间确定国债的表现,图形和数学。校正是从最后一个峰值下降了几个百分点,%是一个可变参数。

import urllib2, pandas as pd, numpy as np, matplotlib.pyplot as plt, scipy as sp

correction = 0.1    # define % decline from peak to constitute market correction

sp_data = urllib2.urlopen('http://real-chart.finance.yahoo.com/table.csv?s=%5EGSPC&a=00&b=3&c=1950&d=00&e=14&f=2016&g=d&ignore=.csv')
df1 = pd.read_csv(sp_data)
df1 = df1[['Date','Close']]
df1 = df1.rename(columns = {'Close':'S&P_500'})

t_bill_data = urllib2.urlopen('http://real-chart.finance.yahoo.com/table.csv?s=%5ETNX&a=00&b=2&c=1962&d=00&e=14&f=2016&g=d&ignore=.csv')
df2 = pd.read_csv(t_bill_data)
df2 = df2[['Date','Close']]
df2 = df2.rename(columns = {'Close':'T_Bill'})

df3 = pd.merge(df1, df2, on='Date', how='outer')

df3['Date'] = pd.to_datetime(df3['Date'], format='%Y-%m-%d')
df3 = df3.set_index('Date')

df3.describe()
df3.plot(kind='line',title='S&P 500 vs. 10 yr T-Bill',subplots=True)

如何识别并将df分配到不同的S& P校正周期? (允许图形图和摘要统计数据集中于独特的时间段。因此,我可以确定S& P修正和国债之间的相关性。)Scipy对tools全局或局部最小值和最大值具有identifying - - 是否有一种pythonic方法来定制这些以识别纠正时期?

1 个答案:

答案 0 :(得分:2)

我将从纯粹的熊猫角度回答你的问题(而不是使用urlib或numpy),因为Pandas专门用于解决在检索和修改财务数据时出现的几乎任何实际问题。

<强> 1。如何识别不同时期的S&amp; P修正?

让我们将修正定义为近期(比如90天)峰值的20%或更多市场下跌:

import pandas as pd
from pandas_datareader import data
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (15,5)

def bear_market(symbol, window=90, correction = .2):
    return pd.rolling_apply(symbol, window, lambda x: x[-1]/x.max() < (1-correction))

spx = data.get_data_yahoo('^GSPC', start = '1970-01-01')
tnx = data.get_data_yahoo('^TNX', start = '1970-01-01')
spx_bear = bear_market(spx['Close'])

data_df = pd.DataFrame({'SP500': spx['Close'],
                        'Bonds': tnx['Close'],
                        'Bear market': spx_bear})

data_df.tail()


    Bear market Bonds   SP500
Date            
2016-01-11  0   2.158   1923.670044
2016-01-12  0   2.102   1938.680054
2016-01-13  0   2.066   1890.280029
2016-01-14  0   2.098   1921.839966
2016-01-15  0   2.033   1880.329956

您可以使用windowcorrection参数来获取更正的不同“版本”。

<强> 2。作图

plot_df = data_df['2008':'2009']

_, ax = plt.subplots()
ax2 = ax.twinx()

plot_df['Bonds'].plot(ax=ax)
plot_df['Bear market'].plot(ax=ax2, style='r--', ylim=[-.1, 1.1])
ax.set_title('Treasuries Performance during SP500 Corrections');

enter image description here

第3。子集和摘要统计

最后,将有两种方法来探索生成的数据集:使用pandas .groupby()或简单的子集。在这两种情况下,我们都需要退货,而不是价格:

ret_df = pd.DataFrame({'SP500': spx['Close'].pct_change(),
                       'Bonds': tnx['Close'].pct_change(),
                       'Bear market': spx_bear})

ret_df.groupby('Bear market').agg('mean')

    Bonds   SP500
Bear market     
0   0.000042    0.000430
1   -0.002679   -0.003261


ret_df[ret_df['Bear market'] == 1][['Bonds','SP500']].corr()
    Bonds   SP500
Bonds   1.000000    0.253068
SP500   0.253068    1.000000

这对您的问题有帮助吗?

修改

你会在代码中多次看到“熊”。原因是我从我的小项目中借用了这个代码来识别“熊市”的时期,但如果你忽略单词“bear”和值“-20%”,这个代码适用于任何更正,这是定义熊市。