# 用python炒股

1、市场----买卖什么

2、头寸规模----买卖多少

3、入市----何时买入

4、止损----何时退出亏损的头寸

5、止盈----何时退出盈利的头寸

6、离市----何时离市

python环境安装

pipinstall tushare

importpandasaspdimporttushareasts# 通过股票代码获取股票数据,这里没有指定开始及结束日期df = ts.get_k_data("300104")# 查看前十条数据df.head()# 查看后十条数据df.tail()# 将数据的index转换成date字段对应的日期df.index = pd.to_datetime(df.date)# 将多余的date字段删除df.drop("date", inplace=True, axis=1)

# 计算5,15,50日的移动平均线, MA5, MA15, MA50days = [5,15,50]formain days:    column_name ="MA{}".format(ma)    df[column_name] = pd.rolling_mean(df.close,ma)# 计算浮动比例df["pchange"] = df.close.pct_change()# 计算浮动点数df["change"] = df.close.diff()

df[["close","MA5","MA15","MA50"]].plot(figsiz=(10,18))

k线图

importmatplotplib.pyplotaspltfrommatplotlib.daetimportDateFormatterfrommatplotlib.financeimportdate2num, candlestick_ohlcdefcandlePlot(data, title=""):data["date"] = [date2num(pd.to_datetime(x))forxindata.index]    dataList = [tuple(x)forxindata[        ["date","open","high","low","close"]].values]    ax = plt.subplot()    ax.set_title(title)    ax.xaxis.set_major_formatter(DateFormatter("%y-%m-%d"))    candlestick_ohlc(ax, dataList, width=0.7, colorup="r", colordown="g")    plt.setp(plt.gca().get_xticklabels(), rotation=50,            horizontalalignment="center")    fig = plt.gcf()    fig.set_size_inches(20,15)    plt.grid(True)candlePlot(df)

# 导入相关模块importtushareastsimportpandasaspd# 获取数据df = ts.get_k_data("000725")# 处理数据df.index = pd.to_datetime(df.date)df.drop("date", axis=1, inplace=True)# 计算浮动比例df["pchange"] = df.close.pct_change()# 计算浮动点数df["change"] = df.close.diff()# 查看当前数据数据前五行open  close  high    low      volume    code  pchange  changedate2015-07-204.2644.2344.3424.16513036186.0000725NaN    NaN2015-07-214.1364.1954.2744.0968776773.0000725-0.009211-0.0392015-07-224.1754.1464.2144.0679083703.0000725-0.011681-0.0492015-07-234.1364.2544.2834.09612792734.00007250.0260490.1082015-07-244.2244.1364.2544.10613009620.0000725-0.027739-0.118# 设定回撤值withdraw =0.03# 设定突破值breakthrough =0.03# 设定账户资金account =10000# 持有仓位手数position =0defbuy(bar):globalaccount, position    print("{}: buy {}".format(bar.date, bar.close))# 一手价格one = bar.close *100position = account // one    account = account - (position * one)defsell(bar):globalaccount, position# 一手价格print("{}: sell {}".format(bar.date, bar.close))    one = bar.close *100account += position * one    position =0print("开始时间投资时间: ", df.iloc[0].date)fordateindf.index:    bar = df.loc[date]ifbar.pchangeandbar.pchange > breakthroughandposition ==0:        buy(bar)elifbar.pchangeandbar.pchange < withdrawandposition >0:        sell(bar)print("最终可有现金: ", account)print("最终持有市值: ", position * df.iloc[-1].close *100)

frompyalgotradeimportstrategyfrompyalgotradeimporttechnicalfrompyalgotrade.barfeedimportyahoofeed# 自定义事件窗口类classDiffEventWindow(technical.EventWindow):def__init__(self, period):assert(period >0)        super(DiffEventWindow, self).__init__(period)        self.__value =NonedefonNewValue(self, dateTime, value):super(DiffEventWindow, self).onNewValue(dateTime, value)ifself.windowFull():            lastValue = self.getValues()[0]            nowValue = self.getValues()[1]            self.__value = (nowValue - lastValue) / lastValuedefgetValue(self):returnself.__value# 自定义指标classDiff(technical.EventBasedFilter):def__init__(self, dataSeries, period, maxLen=None):super(Diff, self).__init__(dataSeries, DiffEventWindow(period), maxLen)# 定义自己的策略classMyStrategy(strategy.BacktestingStrategy):def__init__(self, feed, instrument, diffPeriod=2):# 传入feed及初始账户资金super(MyStrategy, self).__init__(feed,10000)        self.__instrument = instrument        self.__position =Noneself.setUseAdjustedValues(True)        self.__prices = feed[instrument].getPriceDataSeries()        self.__diff = Diff(self.__prices, diffPeriod)        self.__break =0.03self.__withdown =-0.03defgetDiff(self):returnself.__diffdefonEnterCanceled(self, position):self.__position =NonedefonEnterOk(self, position):execInfo = position.getEntryOrder().getExecutionInfo()        self.info("BUY at \$%.2f"% (execInfo.getPrice()))defonExitOk(self, position):execInfo = position.getExitOrder().getExecutionInfo()        self.info("SELL at \$%.2f"% (execInfo.getPrice()))        self.__position =NonedefonExitCanceled(self, position):# If the exit was canceled, re-submit it.self.__position.exitMarket()defonBars(self, bars):account = self.getBroker().getCash()        bar = bars[self.__instrument]ifself.__positionisNone:            one = bar.getPrice() *100oneUnit = account // oneifoneUnit >0andself.__diff[-1] > self.__break:                self.__position = self.enterLong(self.__instrument, oneUnit *100,True)elifself.__diff[-1] < self.__withdownandnotself.__position.exitActive():            self.__position.exitMarket()defrunStrategy():# 下载数据jdf = ts.get_k_data("000725")# 新建Adj Close字段jdf["Adj Close"] =jdf.close# 将tushare下的数据的字段保存为pyalgotrade所要求的数据格式jdf.columns = ["Date","Open","Close","High","Low","Volume","code","Adj Close"]# 将数据保存成本地csv文件jdf.to_csv("jdf.csv", index=False)    feed = yahoofeed.Feed()    feed.addBarsFromCSV("jdf","jdf.csv")    myStrategy = MyStrategy(feed,"jdf")    myStrategy.run()    print("Final portfolio value: \$%.2f"% myStrategy.getResult())runStrategy()

2015-07-30 00:00:00 strategy [INFO] BUY at\$3.782015-07-31 00:00:00 strategy [INFO] SELL at\$3.572015-08-05 00:00:00 strategy [INFO] BUY at\$3.732015-08-06 00:00:00 strategy [INFO] SELL at\$3.56...2018-02-13 00:00:00 strategy [INFO] BUY at\$5.45Final portfolio value:\$7877.30