def plot_division (division_data):
array__DIVISION = create_attribute_array(division_data, 'Division')
array_YEARMONTH = create_attribute_array(division_data, 'YearMonth')
array_TAVG = create_attribute_array(division_data, 'TAVG')
array_PCP = create_attribute_array(division_data, 'PCP')
plt.subplot(2, 1, 1)
plt.plot(array_YEARMONTH, array_TAVG, 'ko-')
# plt.gca().xaxis.set_major_locator(MonthLocator())
# plt.gcf().autofmt_xdate()
plt.title('Division ' + str(array__DIVISION[0]))
plt.ylabel('TAVG (F)')
plt.subplot(2, 1, 2)
plt.plot(array_YEARMONTH, array_PCP, 'r.-')
# plt.gca().xaxis.set_major_locator(MonthLocator())
# plt.gcf().autofmt_xdate()
plt.xlabel('YEARMONTH')
plt.ylabel('PCP')
plt.show()
# Calculate the mean of an array
python类MonthLocator()的实例源码
markov_stock_analysis v2-4.py 文件源码
项目:markov_stock_analysis
作者: nb5hd
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
def percent_change_as_time_plot(adjusted_df, security):
"""
This function visualizes the percentage change data as a time series plot.
:param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
:param security: <SecurityInfo class> Holds information about the requested security
"""
pct_change_list = adjusted_df['Percentage Change'].tolist()
date_list = adjusted_df.index.values
fig, ax = plt.subplots()
ax.plot(date_list, pct_change_list)
plt.xlabel("Dates")
plt.ylabel("Percentage change from last period")
if security.get_period() == "none":
plt.title("Percentage change in " + security.get_name(), y=1.03)
else:
plt.title("Percentage change in " + security.get_name() + " " + security.get_period() + " data", y=1.03)
ax.xaxis.set_minor_locator(MonthLocator())
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()
markov_stock_forecasting_model_v2-5.py 文件源码
项目:markov_stock_analysis
作者: nb5hd
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def percent_change_as_time_plot(adjusted_df, security):
"""
This function visualizes the percentage change data as a time series plot.
:param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
:param security: <SecurityInfo class> Holds information about the requested security
"""
pct_change_list = adjusted_df['Percentage Change'].tolist()
date_list = adjusted_df.index.values
fig, ax = plt.subplots()
ax.plot(date_list, pct_change_list)
plt.xlabel("Dates")
plt.ylabel("Percentage change from last period")
if security.get_period() == "none":
plt.title("Percentage change in " + security.get_name(), y=1.03)
else:
plt.title("Percentage change in " + security.get_name() + " " + security.get_period() + " data", y=1.03)
ax.xaxis.set_minor_locator(MonthLocator())
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()
markov_stock_analysis v2-2.py 文件源码
项目:markov_stock_analysis
作者: nb5hd
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def percent_change_as_time_plot(adjusted_df):
"""
This function visualizes the percentage change data as a time series plot.
:param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
"""
pct_change_list = adjusted_df['Percentage Change'].tolist()
date_list = adjusted_df.index.values
fig, ax = plt.subplots()
ax.plot(date_list, pct_change_list)
#ax.plot(date_list, adjusted_df["Adjusted Close"])
plt.xlabel("Years")
plt.ylabel("Percentage change from last week")
plt.title("Percentage change in S&P 500 weekly data from 2009 to 2016")
ax.xaxis.set_minor_locator(MonthLocator())
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()
def percent_change_as_time_plot(adjusted_df):
"""
This function visualizes the percentage change data as a time series plot.
:param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
"""
pct_change_list = adjusted_df['Percentage Change'].tolist()
date_list = [dt.datetime.strptime(d, '%Y-%m-%d').date() for d in adjusted_df['Date'].tolist()]
fig, ax = plt.subplots()
ax.plot(date_list, pct_change_list)
plt.xlabel("Years")
plt.ylabel("Percentage change from last week")
plt.title("Percentage change in S&P 500 weekly data from 2009 to 2016")
ax.xaxis.set_minor_locator(MonthLocator())
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()
markov_stock_analysis v2-3.py 文件源码
项目:markov_stock_analysis
作者: nb5hd
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def percent_change_as_time_plot(adjusted_df, security):
"""
This function visualizes the percentage change data as a time series plot.
:param adjusted_df: Pandas DataFrame with columns: Date, Adjusted Close, and Percentage Change.
:param security: <SecurityInfo class> Holds information about the requested security
"""
pct_change_list = adjusted_df['Percentage Change'].tolist()
date_list = adjusted_df.index.values
fig, ax = plt.subplots()
ax.plot(date_list, pct_change_list)
plt.xlabel("Dates")
plt.ylabel("Percentage change from last period")
if security.get_period() == "none":
plt.title("Percentage change in " + security.get_name(), y=1.03)
else:
plt.title("Percentage change in " + security.get_name() + " " + security.get_period() + " data", y=1.03)
ax.xaxis.set_minor_locator(MonthLocator())
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.fmt_xdata = DateFormatter('%Y-%m-%d')
ax.autoscale_view()
fig.autofmt_xdate()
plt.show()
def plotYearly(dictframe, ax, uncertainty, color='#0072B2'):
if ax is None:
figY = plt.figure(facecolor='w', figsize=(10, 6))
ax = figY.add_subplot(111)
else:
figY = ax.get_figure()
##
# Find the max index for an entry of each month
##
months = dictframe.ds.dt.month
ind = []
for month in range(1,13):
ind.append(max(months[months == month].index.tolist()))
##
# Plot from the minimum of those maximums on (this will almost certainly result in only 1 year plotted)
##
ax.plot(dictframe['ds'][min(ind):], dictframe['yearly'][min(ind):], ls='-', c=color)
if uncertainty:
ax.fill_between(dictframe['ds'].values[min(ind):], dictframe['yearly_lower'][min(ind):], dictframe['yearly_upper'][min(ind):], color=color, alpha=0.2)
ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
ax.xaxis.set_major_formatter(FuncFormatter(
lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
ax.xaxis.set_major_locator(months)
ax.set_xlabel('Day of year')
ax.set_ylabel('yearly')
figY.tight_layout()
return figY
def plot_price_series(df, ts_lab1, ts_lab2):
#months = mdates.MonthLocator() # every month
fig, ax = plt.subplots()
ax.plot(df.index, df[ts_lab1], label=ts_lab1)
ax.plot(df.index, df[ts_lab2], label=ts_lab2)
#ax.xaxis.set_major_locator(months)
#ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.grid(True)
fig.autofmt_xdate()
plt.xlabel('Month/Year')
plt.ylabel('Price ($)')
plt.title('%s and %s Daily Prices' % (ts_lab1, ts_lab2))
plt.legend()
plt.show()
def plot_series(ts):
#months = mdates.MonthLocator() # every month
fig, ax = plt.subplots()
ax.plot(ts.index, ts, label=ts.name)
#ax.xaxis.set_major_locator(months)
#ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
#ax.set_xlim(datetime.datetime(2012, 1, 1), datetime.datetime(2013, 1, 1))
ax.grid(True)
fig.autofmt_xdate()
plt.xlabel('Month/Year')
plt.ylabel('Price ($)')
plt.title('Residual Plot')
plt.legend()
plt.plot(ts)
plt.show()
def make_date_ticks(ax, fs=12):
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
years = YearLocator()
months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
yearsFmt = DateFormatter('%Y')
monthsFmt = DateFormatter("%b")
ax.tick_params(axis='x', which='major', labelsize=fs, pad=20)
ax.tick_params(axis='x', which='minor', pad=7)
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
def plot_daily_inf_res(df, symbols=[], plot_top=0):
df = df.copy()
# data_nasdaq_top_100_preprocessed_merge.groupby('SYMBOL')
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
years_fmt = mdates.DateFormatter('%Y')
df['max_pmi_is'] = df[[col for col in df.columns if 'pmi_is' in col]].max(axis=1)
if len(symbols) > 0:
df = df.loc[symbols]
if plot_top > 0:
idx = df.groupby('SYMBOL')['max_pmi_is'].max().sort_values(ascending=False).index[:plot_top].values
print idx
df = df.loc[list(idx)]
# df = df.reindex(index=idx)
fig, ax = plt.subplots(figsize=(15,5))
for key, grp in df.groupby('SYMBOL'):
print "key", key
# grp.reset_index()
# print grp.DATE
ax.plot(grp.DATE.reset_index(drop=True), grp['max_pmi_is'], label=key)
# grp['D'] = pd.rolling_mean(grp['B'], window=5)
# plt.plot(grp['D'], label='rolling ({k})'.format(k=key))
# datemin = (df.DATE.min().year)
# datemax = (df.DATE.max().year + 1)
# print datemin, datemax
# ax.set_xlim(datemin, datemax)
ax.set_ylim(0, 500)
plt.legend(loc='best')
plt.ylabel('PMI IS (-2)')
fig.autofmt_xdate()
plt.show()
def plot_yearly(self, ax=None, uncertainty=True, yearly_start=0):
"""Plot the yearly component of the forecast.
Parameters
----------
ax: Optional matplotlib Axes to plot on. One will be created if
this is not provided.
uncertainty: Optional boolean to plot uncertainty intervals.
yearly_start: Optional int specifying the start day of the yearly
seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
by 1 day to Jan 2, and so on.
Returns
-------
a list of matplotlib artists
"""
artists = []
if not ax:
fig = plt.figure(facecolor='w', figsize=(10, 6))
ax = fig.add_subplot(111)
# Compute yearly seasonality for a Jan 1 - Dec 31 sequence of dates.
days = (pd.date_range(start='2017-01-01', periods=365) +
pd.Timedelta(days=yearly_start))
df_y = self.seasonality_plot_df(days)
seas = self.predict_seasonal_components(df_y)
artists += ax.plot(
df_y['ds'].dt.to_pydatetime(), seas['yearly'], ls='-', c='#0072B2')
if uncertainty:
artists += [ax.fill_between(
df_y['ds'].dt.to_pydatetime(), seas['yearly_lower'],
seas['yearly_upper'], color='#0072B2', alpha=0.2)]
ax.grid(True, which='major', c='gray', ls='-', lw=1, alpha=0.2)
months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
ax.xaxis.set_major_formatter(FuncFormatter(
lambda x, pos=None: '{dt:%B} {dt.day}'.format(dt=num2date(x))))
ax.xaxis.set_major_locator(months)
ax.set_xlabel('Day of year')
ax.set_ylabel('yearly')
return artists
def apply_date_formatting_to_axis(ax):
""" Format x-axis of input plot to a readable date format """
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(0), interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
return ax
def setAxisScaleX(self, x_axis_bins):
"""The setAxisScaleX() method sets the bins for the X axis. Presently,
we assume a date-based axis."""
if self.verboseLogging:
self.logger.threaddebug(u"Constructing the bins for the X axis.")
if x_axis_bins == 'quarter-hourly':
plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 96)))
if x_axis_bins == 'half-hourly':
plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 48)))
elif x_axis_bins == 'hourly':
plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 24)))
elif x_axis_bins == 'hourly_4':
plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 8)))
elif x_axis_bins == 'hourly_8':
plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 4)))
elif x_axis_bins == 'hourly_12':
plt.gca().xaxis.set_major_locator(mdate.HourLocator(interval=4))
plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 2)))
elif x_axis_bins == 'daily':
plt.gca().xaxis.set_major_locator(mdate.DayLocator(interval=1))
plt.gca().xaxis.set_minor_locator(mdate.HourLocator(byhour=range(0, 24, 6)))
elif x_axis_bins == 'weekly':
plt.gca().xaxis.set_major_locator(mdate.DayLocator(interval=7))
plt.gca().xaxis.set_minor_locator(mdate.DayLocator(interval=1))
elif x_axis_bins == 'monthly':
plt.gca().xaxis.set_major_locator(mdate.MonthLocator(interval=1))
plt.gca().xaxis.set_minor_locator(mdate.DayLocator(interval=1))
elif x_axis_bins == 'yearly':
plt.gca().xaxis.set_major_locator(mdate.YearLocator())
plt.gca().xaxis.set_minor_locator(mdate.MonthLocator(interval=12))
def plot_backtest_result_curve(log_file):
data_dict = read_result_from_log(log_file)
#benchmark_dates, benchmark_value = sort_dict_buy_key(data_dict)
portfolio_history_data = pd.DataFrame(data_dict).T
portfolio_history_data.columns = ['total_value', 'cash', 'stock_value', 'bench_value']
dates_ = list(portfolio_history_data.index)
dates_.pop()
dates = []
for d in dates_:
if d == None:
d = config.start_date
date = datetime.datetime.strptime(d, '%Y-%m-%d').date()
dates.append(date)
#dates = [datetime.datetime.strptime(d, '%Y-%m-%d').date() for d in dates if d != None else config.start_date]
total_value = list(portfolio_history_data["total_value"].values)
cash = list(portfolio_history_data["cash"].values)
cash_value = list(portfolio_history_data["stock_value"].values)
bench_value = list(portfolio_history_data["bench_value"].values)
total_value.pop()
bench_value.pop()
# xaxis tick formatter
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
# xaxis ticks
#plt.gca().xaxis.set_major_locator(mdates.MonthLocator())
# figure title and legend
plt.gca().legend()
plt.gca().set(title="event factor backtesting porfolio value",
ylabel = "porfolio total value",
xlabel = "backtesting time")
plt.locator_params(axis='x', nticks=10)
plt.plot(dates, total_value)
plt.plot(dates, bench_value)
plt.gcf().autofmt_xdate()
plt.show()
#data = read_result_from_log(sys.argv[1])
#plot_backtest_result_curve(data)
def make_dateplot(x, y, outname, ylims=None):
fig, ax = plt.subplots()
fig.autofmt_xdate()
ax.plot_date(x, y, ls='', marker='x')
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_minor_locator(DayLocator())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S')
if ylims is not None:
ax.set_ylim(ylims)
fig.savefig(outname, dpi=200)
plt.close(fig)
def back_test_plot(self):
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig = plt.figure()
all_lines = []
ax = fig.add_subplot(111)
ax.set_ylabel('PnL')
has_right_ax = False
if 'quant_index' in self.used_vars or \
'quant_index1' in self.used_vars or \
'quant_index2' in self.used_vars or \
'quant_index3' in self.used_vars:
has_right_ax = True
dates = [ x[0] for x in self.pnls['portfolio'] ]
for v in self.used_vars:
if 'portfolio' in v:
all_lines += ax.plot(dates, [x[1] for x in self.pnls[v]],label=v,linewidth=1)
if has_right_ax:
right_ax = ax.twinx()
for v in self.used_vars:
if 'index' in v:
all_lines += right_ax.plot(dates, self.quant_indices[v],label=v,linewidth=1,ls='dotted')
right_ax.set_ylabel('quant_index')
# format the ticks
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
datemin = min(dates)
datemax = max(dates)
ax.set_xlim(datemin, datemax)
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.grid(True)
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
fig.tight_layout()
plt.legend(all_lines,[l.get_label() for l in all_lines],loc='best')
plt.show()
def proportion_stackplot(df, output=None, xlabel='', ylabel='', title=''):
"""
Pandas has a bug with it's plot(kind='area'). When moving the legend, the colors disappear.
By default with pandas the legend sits on the graph, which is not a desired behavior.
So this function imitates panda's formatting of an area plot, with a working well-placed legend.
Parameters
----------
df : pandas.Dataframe
x must be a date series.
y is any number of columns containing percentages that must add up to 100 for each row.
output : string
the complete output file name
xlabel : string
ylabel : string
title : string
Returns
-------
"""
column_names = df.columns.values
x = df.index.date
column_series_list = []
for cname in column_names:
column_series_list.append(pd.Series(df[cname]).tolist())
fig, ax = plt.subplots()
polys = ax.stackplot(x, column_series_list, alpha=0.8)
ax.set_ylim([0, 100])
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
legends = []
for poly in polys:
legends.append(plt.Rectangle((0, 0), 1, 1, facecolor=poly.get_facecolor()[0]))
# don't try to understand the legend displacement thing here. Believe me. Don't.
plt.figlegend(legends, column_names, loc=7, bbox_to_anchor=(1.2 + legend_displace_factor(column_names), 0.5))
plt.title(title, y=1.08)
date_fmt_year = mDates.DateFormatter('%b\n%Y')
date_fmt_month = mDates.DateFormatter('%b')
ax.xaxis.set_major_locator(mDates.YearLocator())
ax.xaxis.set_major_formatter(date_fmt_year)
ax.xaxis.set_minor_locator(mDates.MonthLocator(bymonth=7))
ax.xaxis.set_minor_formatter(date_fmt_month)
plt.savefig(output, bbox_inches='tight')
plt.close()
def getDatasForOneRouteForOneDepartureDate(route, departureDate):
X = getOneRouteData(datas, route)
minDeparture = np.amin(X[:,8])
maxDeparture = np.amax(X[:,8])
print minDeparture
print maxDeparture
# get specific departure date datas
X = X[np.where(X[:, 8]==departureDate)[0], :]
# get the x values
xaxis = X[:,9] # observed date state
print xaxis
xaxis = departureDate-1-xaxis
print xaxis
tmp = xaxis
startdate = "20151109"
xaxis = [pd.to_datetime(startdate) + pd.DateOffset(days=state) for state in tmp]
print xaxis
# get the y values
yaxis = X[:,12]
# every monday
mondays = WeekdayLocator(MONDAY)
# every 3rd month
months = MonthLocator(range(1, 13), bymonthday=1, interval=01)
days = WeekdayLocator(byweekday=1, interval=2)
monthsFmt = DateFormatter("%b. %d, %Y")
fig, ax = plt.subplots()
ax.plot_date(xaxis, yaxis, 'r--')
ax.plot_date(xaxis, yaxis, 'bo')
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(monthsFmt)
#ax.xaxis.set_minor_locator(mondays)
ax.autoscale_view()
#ax.xaxis.grid(False, 'major')
#ax.xaxis.grid(True, 'minor')
ax.grid(True)
plt.xlabel('Date')
plt.ylabel('Price in Euro')
fig.autofmt_xdate()
plt.show()
"""
# plot
line1, = plt.plot(xaxis, yaxis, 'r--')
line2, = plt.plot(xaxis, yaxis, 'bo')
#plt.legend([line2], ["Price"])
plt.xlabel('States')
plt.ylabel('Price in Euro')
plt.show()
"""