我正在研究基本的交易算法,但我的问题更多地与熊猫有关。
参见代码:
import pandas_datareader as pdr
import datetime
import pandas as pd
import numpy as np
import talib as ta
###########################################GETTING DATA###################################################
#Download Data
aapl = pdr.get_data_yahoo('AAPL', start=datetime.datetime(2010, 9, 1), end=datetime.datetime(2017, 11, 8))
###############################################STRATEGY###################################################
#Initialize the `signals` DataFrame with the `signal` column
signals = pd.DataFrame(index=aapl.index)
signals['signal'] = 0.0
# Add price/Currently using Open Price
signals['Open'] = aapl.Open.values
# Create 10 MA moving average
signals['10 MA'] = ta.SMA(aapl.Close.values,10)
# Create 25 EMA moving average
signals['25 EMA'] = ta.EMA(aapl.Close.values,25)
# Remove Nan rows
signals = signals.dropna()
# Create Buy Signal
signals['signal'] = np.where((signals['Close']>signals['25 EMA']),1.0,0)
#Create Sell Signal
#I want to hold the stock as long as its 1)above the price I paid for it and 2) if it ever gets above the 10 day moving average and later closes beneath it I want to sell
print (signals)
我有一个pandas数据帧(见下文),每次信号列= 1(我的购买信号),这意味着我的购买标准已经满足,但是,尽管这只是一小段数据和信号似乎总是1,但是当我们在数据集中向外移动时,情况并非如此。
最终,购买标准不再符合且信号栏= 0,但有些情况下我仍然想要持有股票并在信号栏中将其保持为1:
1)如果它高于我在
进入交易的价格2)但是如果它已经超过了我购买它之后的10天移动平均线并且在它下方关闭会刺激我卖出
我所要做的就是弄清楚何时购买/持有/卖出股票并在信号栏中表达,以便稍后分析回报。
如果有人有更好的方法来跟踪这些交易,我全都听见了!
signal close 10 MA 25 EMA
Date
2010-10-06 1.0 41.369999 40.995285 39.372343
2010-10-07 1.0 41.477142 40.999571 39.521943
2010-10-08 1.0 41.672855 41.024571 39.713331
2010-10-11 1.0 42.105713 41.084571 39.904174
2010-10-12 1.0 42.201427 41.251428 40.115282
2010-10-13 1.0 42.885715 41.433857 40.327732
2010-10-14 1.0 43.098572 41.699000 40.547687
2010-10-15 1.0 43.919998 42.159285 40.887315
2010-10-18 1.0 45.495716 42.721571 41.236643
2010-10-19 1.0 43.342857 43.015142 41.465582
2010-10-20 1.0 44.142857 43.319999 41.688339
2010-10-21 1.0 44.622856 43.609999 41.882863
2010-10-22 1.0 44.152859 43.801428 42.039895
2010-10-25 1.0 44.155716 43.993999 42.199903
2010-10-26 1.0 43.838570 44.129856 42.338922
2010-10-27 1.0 43.950001 44.239714 42.464829
2010-10-28 1.0 43.992859 44.281571 42.552589
2010-10-29 1.0 43.461430 44.084999 42.586786