python股票数据分析_用 Python 做股市数据分析(一)

from matplotlib.dates import DateFormatter, WeekdayLocator,\

DayLocator, MONDAY

from matplotlib.finance import candlestick_ohlc

def pandas_candlestick_ohlc(dat, stick = "day", otherseries = None):

"""

:param dat: pandas DataFrame object with datetime64 index, and float columns "Open", "High", "Low", and "Close", likely created via DataReader from "yahoo"

:param stick: A string or number indicating the period of time covered by a single candlestick. Valid string inputs include "day", "week", "month", and "year", ("day" default), and any numeric input indicates the number of trading days included in a period

:param otherseries: An iterable that will be coerced into a list, containing the columns of dat that hold other series to be plotted as lines

This will show a Japanese candlestick plot for stock data stored in dat, also plotting other series if passed.

"""

mondays = WeekdayLocator(MONDAY) # major ticks on the mondays

alldays = DayLocator() # minor ticks on the days

dayFormatter = DateFormatter('%d') # e.g., 12

# Create a new DataFrame which includes OHLC data for each period specified by stick input

transdat = dat.loc[:,["Open", "High", "Low", "Close"]]

if (type(stick) == str):

if stick == "day":

plotdat = transdat

stick = 1 # Used for plotting

elif stick in ["week", "month", "year"]:

if stick == "week":

transdat["week"] = pd.to_datetime(transdat.index).map(lambda x: x.isocalendar()[1]) # Identify weeks

elif stick == "month":

transdat["month"] = pd.to_datetime(transdat.index).map(lambda x: x.month) # Identify months

transdat["year"] = pd.to_datetime(transdat.index).map(lambda x: x.isocalendar()[0]) # Identify years

grouped = transdat.groupby(list(set(["year",stick]))) # Group by year and other appropriate variable

plotdat = pd.DataFrame({"Open": [], "High": [], "Low": [], "Close": []}) # Create empty data frame containing what will be plotted

for name, group in grouped:

plotdat = plotdat.append(pd.DataFrame({"Open": group.iloc[0,0],

"High": max(group.High),

"Low": min(group.Low),

"Close": group.iloc[-1,3]},

index = [group.index[0]]))

if stick == "week": stick = 5

elif stick == "month": stick = 30

elif stick == "year": stick = 365

elif (type(stick) == int and stick >= 1):

transdat["stick"] = [np.floor(i / stick) for i in range(len(transdat.index))]

grouped = transdat.groupby("stick")

plotdat = pd.DataFrame({"Open": [], "High": [], "Low": [], "Close": []}) # Create empty data frame containing what will be plotted

for name, group in grouped:

plotdat = plotdat.append(pd.DataFrame({"Open": group.iloc[0,0],

"High": max(group.High),

"Low": min(group.Low),

"Close": group.iloc[-1,3]},

index = [group.index[0]]))

else:

raise ValueError('Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer')

# Set plot parameters, including the axis object ax used for plotting

fig, ax = plt.subplots()

fig.subplots_adjust(bottom=0.2)

if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('730 days'):

weekFormatter = DateFormatter('%b %d') # e.g., Jan 12

ax.xaxis.set_major_locator(mondays)

ax.xaxis.set_minor_locator(alldays)

else:

weekFormatter = DateFormatter('%b %d, %Y')

ax.xaxis.set_major_formatter(weekFormatter)

ax.grid(True)

# Create the candelstick chart

candlestick_ohlc(ax, list(zip(list(date2num(plotdat.index.tolist())), plotdat["Open"].tolist(), plotdat["High"].tolist(),

plotdat["Low"].tolist(), plotdat["Close"].tolist())),

colorup = "black", colordown = "red", width = stick * .4)

# Plot other series (such as moving averages) as lines

if otherseries != None:

if type(otherseries) != list:

otherseries = [otherseries]

dat.loc[:,otherseries].plot(ax = ax, lw = 1.3, grid = True)

ax.xaxis_date()

ax.autoscale_view()

plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

plt.show()

pandas_candlestick_ohlc(apple)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值