本文整理汇总了Python中pandas.io.data.DataReader.pct_change方法的典型用法代码示例。如果您正苦于以下问题:Python DataReader.pct_change方法的具体用法?Python DataReader.pct_change怎么用?Python DataReader.pct_change使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pandas.io.data.DataReader
的用法示例。
在下文中一共展示了DataReader.pct_change方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Individual_screener
# 需要导入模块: from pandas.io.data import DataReader [as 别名]
# 或者: from pandas.io.data.DataReader import pct_change [as 别名]
class Individual_screener():
"""
This class will store the relevant information and functions for the
signal detection of entry points of one Strategy in one Security
"""
def __init__(self, symbol, to_date=dt.datetime.today()):
self.data = False
self.symbol = symbol
self.to_date = to_date
self.from_date = self.to_date.replace(to_date.year - 1)
self.signal = False
self.get_prices_yahoo()
def get_prices_yahoo(self):
"""
It get prices data from yahoo (last year)
"""
try:
self.df_prices = DataReader(self.symbol, "yahoo", self.from_date,
self.to_date)
self.df_prices['pct Adj Close'] = self.df_prices.pct_change()['Adj Close']
self.data = True
except Exception, e:
print e
sleep(5)
示例2: Simulation
# 需要导入模块: from pandas.io.data import DataReader [as 别名]
# 或者: from pandas.io.data.DataReader import pct_change [as 别名]
class Simulation():
"""
Class that will store all data and functions related to a simulation
"""
def __init__(self, symbol, from_date=None, to_date=None):
"""
If dates not entered it will take a default to determine ######### TODO
"""
self.symbol = symbol
self.from_date = from_date
self.to_date = to_date
self.df_prices = pd.DataFrame()
self.open = None # Price of current open trade
self.close = None # Price of current closed trade
self.status = 'out' # 'out' not invested, 'in' invested
self.signal = False # It will get records in which the signal activates
self.max_open = 0.0 # Max individual investment (for % profit calculation)
### Measures
self.nperiods = 0
self.ntrades = 0
self.abs_profit = 0.0 # Accumulated abs_profit ($ value gained/loss)
# self.pct_simple_profit = 0.0 # Profit over max investment (without reinvestment)
self.pct_compound_profit = 1.0 # Profit over max investment (with reinvestment)
# self.pct_annual_simple_profit = 0.0 # Annualized simple profit
# self.pct_annual_compound_profit = 0.0 # Annualized compound profit
self.volatility = 0.0 # Volatility of returns (annualized)
self.sharpe = 0.0 # Sharpe ratio (Rf = 0)
self.drawdown = 0.0 # It will store the worst abs_profit
### Years calculation
d_from_date = date(int(from_date[0:4]), int(from_date[4:6]), int(from_date[6:8]))
d_to_date = date(int(to_date[0:4]), int(to_date[4:6]), int(to_date[6:8]))
self.years = (d_to_date-d_from_date).days/365.0
self.profit_trades = []
def get_prices_yahoo(self):
"""
It get prices data from yahoo
"""
try:
self.df_prices = DataReader(self.symbol, "yahoo", self.from_date,
self.to_date)
self.df_prices['pct Adj Close'] = self.df_prices.pct_change()['Adj Close']
except Exception, e:
print e
raise
示例3: DataReader
# 需要导入模块: from pandas.io.data import DataReader [as 别名]
# 或者: from pandas.io.data.DataReader import pct_change [as 别名]
import pandas as pd
from datetime import datetime
from pandas.io.data import DataReader
pd.set_printoptions(max_rows=2000)
aapl = DataReader("AAPL", "yahoo", datetime(2010, 1, 1), datetime(2012, 10, 30))
returns = aapl.pct_change()
def f(x):
if x > 0.01:
return 1
elif x < -0.01:
return -1
else:
return 0
frame = returns.applymap(f)
frame['UP'] = frame['Adj Close'] == 1
frame['DOWN'] = frame['Adj Close'] == -1
frame['NONE'] = frame['Adj Close'] ==0
from lxml import etree
import datetime
from dateutil.parser import parse
path = "http://www.google.com/finance/company_news?q=NASDAQ:AAPL&output=rss&num=500"
root = etree.parse(path)
myRoot = root.getroot()
news={}
示例4: DataReader
# 需要导入模块: from pandas.io.data import DataReader [as 别名]
# 或者: from pandas.io.data.DataReader import pct_change [as 别名]
AAPL['Daily Return'] = AAPL['Adj Close'].pct_change()
AAPL['Daily Return'].plot(figsize=(10, 4), legend=True, linestyle='--', marker='o')
plt.show()
sns.distplot(AAPL['Daily Return'].dropna(), bins=100, color='purple')
plt.show()
AAPL['Daily Return'].hist(bins=100)
plt.show()
closing_df = DataReader(tech_list, 'yahoo', start, end)['Adj Close']
print(closing_df.head())
tech_rets = closing_df.pct_change()
print(tech_rets.head())
sns.jointplot('GOOG', 'GOOG', tech_rets, kind = 'scatter', color='seagreen')
plt.show()
sns.jointplot('GOOG', 'MSFT', tech_rets, kind='scatter')
plt.show()
sns.pairplot(tech_rets.dropna())
plt.show()
returns_fig = sns.PairGrid(tech_rets.dropna())
returns_fig.map_upper(plt.scatter, color='purple')
returns_fig.map_lower(sns.kdeplot, cmap='cool_d')
returns_fig.map_diag(plt.hist, bins=30)
示例5: DataReader
# 需要导入模块: from pandas.io.data import DataReader [as 别名]
# 或者: from pandas.io.data.DataReader import pct_change [as 别名]
from pandas.io.data import DataReader
code_names = {
'005930.KS':'Samsung Elec', '005380.KS':'Hyundai Motor','000660.KS':'SK Hynix', '015760.KS':'kor elect',
'012330.KS':'Hyundai Mobis', '005490.KS':'POSCO', '017670.KS':'SK tele','^KS11':'KOSPI',
'035420.KS':'NAVER','055550.KS':'sinhan','032830.KS':'samsung life', '000270.KS':'Kia', '090430.KS':'AmoreF',
'090430.KS':'LG chemi','105560.KS':'KB','000810.KS':'samsung fire', '034220.KS':'LG display', '033780.KS':'KT&G',
'051900.KS':'LG health','003550.KS':'LG','034730.KS':'SK cnc', '066570.KS':'LG elec', '002790.KS':'AmoreG',
'009540.KS':'Samsung shi','006400.KS':'Samsung SDI','086280.KS':'Hy globis', '096770.KS':'SK ino', '000830.KS':'Samsung c&t'}
df = DataReader(code_names.keys(), 'yahoo', start='2014-03-01', end='2015-02-28')
df = df['Adj Close']
df = df.rename(columns=code_names)
changes = df.pct_change()
chg_corr = changes.corr()
chg_corr
plt.figure(figsize=(16,8))
plt.scatter(changes.mean(), changes.std())
plt.xlabel('returns')
plt.ylabel('risk')
for label, x, y in zip(changes.columns, changes.mean(), changes.std()):
plt.annotate( label,xy=(x, y), xytext=(30, -30),
textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
plt.show()
示例6: DataReader
# 需要导入模块: from pandas.io.data import DataReader [as 别名]
# 或者: from pandas.io.data.DataReader import pct_change [as 别名]
currency.loc[:, ('Daily Return')] = currency[[0]].pct_change()
currencyfig3 = currency[[4]].plot(figsize=(10,4), legend=True, linestyle='--', marker='o')
currencyfig3 = currencyfig3.get_figure()
currencyfig3.savefig('currencyfig3.png')
currencyfig4 = sns.distplot(currency[['Daily Return']].dropna(), color='purple')
currencyfig4 = currencyfig4.get_figure()
currencyfig4.savefig('currencyfig4.png')
closing_df = DataReader(fred_currencies, 'fred', start, end)
print '\nDaily Close Snapshot'
print '\n', closing_df.head()
fred_ret = closing_df.pct_change()
print '\nDaily Return Snapshot\n'
print '\n', fred_ret.head()
print "\nSee how currency pairs correlate...\n"
currency1 = raw_input("Enter Currency 1: ")
if currency1 == 'DEXUSEU':
currency1 = fred_ret[['DEXUSEU']].dropna()
currency1.rename(columns = {'DEXUSEU':'Return'}, inplace = True)
elif currency1 == 'DEXUSAL':
currency1 = fred_ret[['DEXUSAL']].dropna()
currency1.rename(columns = {'DEXUSAL':'Return'}, inplace = True)
elif currency1 == 'DEXUSUK':
currency1 = fred_ret[['DEXUSUK']].dropna()
currency1.rename(columns = {'DEXUSUK':'Return'}, inplace = True)
示例7: datetime
# 需要导入模块: from pandas.io.data import DataReader [as 别名]
# 或者: from pandas.io.data.DataReader import pct_change [as 别名]
prices = pdweb.get_data_yahoo(['CVX','XOM','BP'],start = datetime.datetime(2011,1,1),
end = datetime.datetime(2014,1,1))['Adj Close']
volume = pdweb.get_data_yahoo(['CVX','XOM','BP'],start = datetime.datetime(2011,1,1),
end = datetime.datetime(2014,1,1))['Volume']
rets = prices.pct_change() # returns percent change across columns. Row[1] - Row[0]/Row[0]
%matplotlib inline # plots within Jupyter notebook
prices.plot() # line plot
# A better more advanced way
my_list = ['FB', 'AMZN' , 'NFLX', 'GOOG']
end = datetime.now()
start = datetime(end.year-1, end.month, end.day)
for stock in my_list:
globals()[stock] = DataReader(stock,'yahoo', start, end) #globals ensures that the variable is available outside the for loop
# if you just need one column ... say closing price (for example)
closing_df = DataReader(my_list,'yahoo', start, end)['Adj Close']
dlyReturns_df = closing_df.pct_change().dropna()
## correlations
corr = rets.corr() # returns corelation matrix between columns
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.corrplot(rets,annot = False,diag_names=False)
示例8: Simulation
# 需要导入模块: from pandas.io.data import DataReader [as 别名]
# 或者: from pandas.io.data.DataReader import pct_change [as 别名]
#.........这里部分代码省略.........
self.pct_compound_profit = 1.0 # Profit over max investment (with reinvestment)
self.volatility = 0.0 # Volatility of returns (annualized)
self.sharpe = 0.0 # Sharpe ratio (Rf = 0)
self.drawdown = 0.0 # It will store the worst abs_profit
self.df_result = pd.DataFrame()
## 2. Years calculation
d_from_date = date(int(from_date[0:4]), int(from_date[4:6]), int(from_date[6:8]))
d_to_date = date(int(to_date[0:4]), int(to_date[4:6]), int(to_date[6:8]))
self.years = (d_to_date-d_from_date).days/365.0
self.profit_trades = []
## 3. Get prices
### RNA 04/09/2014 Including prices download from IB, this function will be launch manually
#self.get_prices_yahoo()
### END RNA 04/09/2014
def apply_strategy(self, strategy):
"""
It will apply the selected strategy to this simulation.
Strategy in this case is a class with all the information it requires
"""
# 0. In case there is no data, nothing is done
if not self.data: return 0
# 1. Initialization of variables
count = 0
status = 'out'
s_record = pd.Series()
pct_profit_temp = 0.0
self.nperiods = len(self.df_prices.index)-1
# 2. Loop through all the prices
for pos in range(self.nperiods):
currclose = self.df_prices.ix[pos]['Adj Close']
change = self.df_prices.ix[pos]['pct Adj Close']
# 3. Check if we are in or out
if self.status == 'out':
# 4. Check strategy entry condition
if strategy.check_entry(self.df_prices, pos): ## If performance issue send less
self.open_trade(currclose)
elif self.status == 'in':
# 5. Add profit for measures
pct_profit_temp += change
# 6. Check stratey exit condition
if strategy.check_exit(self.df_prices, pos):
self.close_trade(currclose, pct_profit_temp)
pct_profit_temp = 0.0
# 3. Log
s_record["date"]=str(self.df_prices.index[pos])
s_record["price"]=str(currclose)
s_record["change"]=change
s_record["status"]=self.status
s_record["abs_profit"]=self.abs_profit
s_record["signal"]=self.signal
self.df_result = self.df_result.append(s_record, ignore_index=True)
columns = ['date', 'price', 'change', 'status', 'abs_profit', 'signal']
self.df_result = self.df_result[columns]
prevclose = currclose
self.signal = False
# 3. Print result
# print "The result is:" + str(self.abs_profit)
# print "The log is:"
# print df_result
def close_trade(self, close, pct_profit_trade):
self.close = close
self.abs_profit += self.close - self.open
self.pct_compound_profit = np.sqrt((1+self.pct_compound_profit)*(1+pct_profit_trade)) - 1.0
self.status = 'out'
self.ntrades += 1
self.profit_trades.append(pct_profit_trade)
if self.abs_profit < self.drawdown: # Calculation of drawdown
self.drawdown = self.abs_profit
def get_prices_yahoo(self):
"""
It get prices data from yahoo
"""
try:
self.df_prices = DataReader(self.symbol, "yahoo", self.from_date,
self.to_date)
self.df_prices['pct Adj Close'] = self.df_prices.pct_change()['Adj Close']
self.data = True
except Exception, e:
print e
sleep(20)