2015年5月25日 星期一

由證交所與櫃買中心下載的csv檔直接轉入Access資料庫

' 由證交所與櫃買中心下載的csv檔直接轉入Access資料庫
Function importDaily()
Call A11Import
Call RSTAImport
End Function
--------------------------------------------------------------------------------
Function RSTAimp1(source)
' --- 匯入一個上櫃csv檔到主檔stk
Dim fs2 As New Scripting.FileSystemObject
Dim RsStk As Recordset
Dim RsStkId As Recordset
Dim inpFi As TextStream
Dim lines As Integer
Dim s1 As String
Dim yy As String, mm As String, dd As String
Dim sdate As String
Dim aa
Dim i As Integer
Dim s2 As String
Dim isdel As Boolean
Dim ch
Set inpFi = fs2.OpenTextFile(source)
Set RsStk = CurrentDb.OpenRecordset("select * from stk")
lines = 0
Do While Not inpFi.AtEndOfStream
lines = lines + 1
s1 = inpFi.ReadLine
If lines = 1 Then
yy = Mid(s1, 1, 2)
mm = Mid(s1, InStr(s1, "年") + 1, 2)
dd = Mid(s1, InStr(s1, "月") + 1, 2)
sdate = (1911 + yy) & "/" & mm & "/" & dd
Debug.Print sdate
End If
If InStr(s1, "上櫃家數") <> 0 Then
Exit Do
End If
If lines >= 3 Then
'**************************************
isdeli = False
s2 = ""
For i = 1 To Len(s1)
ch = Mid(s1, i, 1)
If Mid(s1, i, 1) = """" Then
isdeli = Not isdeli
Else
If isdeli Then
If ch <> "," Then
s2 = s2 & ch
End If
Else
s2 = s2 & ch
End If
End If
Next
s2 = Replace(s2, "--", "00")
'Debug.Print s2
'*************************************
aa = Split(s2, ",")
If UBound(aa) < 9 Then
Debug.Print s1
ElseIf Len(aa(0)) = 4 Then
'代號0,名稱1,收盤2 ,漲跌3,開盤4 ,最高5 ,最低6,均價7 ,成交股數8
RsStk.AddNew
RsStk("dte") = CDate(sdate)
RsStk("stockid") = aa(0)
RsStk("price") = aa(2)
RsStk("p_open") = aa(4)
RsStk("p_high") = aa(5)
RsStk("p_low") = aa(6)
s2 = Replace(aa(8), ",", "")
s2 = Replace(s2, """", "")
RsStk("vol") = s2
RsStk.Update
'--- 同時更新股票代號檔
Set RsStkId = CurrentDb.OpenRecordset("select * from stkid where stockid='" & aa(0) & "'")
If RsStkId.EOF Then
DoCmd.RunSQL ("insert into stkid values('" & aa(0) & "','" & aa(1) & "','2')")
End If
End If
End If
Loop
RsStk.Close
Debug.Print source
End Function
--------------------------------------------------------------------------------
Function RSTAImport()
'--- 將dirImport內的所有 RSTA*.csv上櫃檔匯入到主檔 stk,同時將該檔移到 dircomplete
Dim fs As New Scripting.FileSystemObject
Dim outFi As TextStream, errFi As TextStream
Dim dirImport As String, dirComplete As String
Dim fi As File
Dim strRoot As String
Dim fo_root As Folder
Dim fo_Dir As Folder
Dim ext As String
Dim source As String, Target As String, stockId As String
strRoot = CurrentProject.path
dirImport = strRoot & "\import"
dirComplete = strRoot & "\complete"
Set outFi = fs.CreateTextFile(strRoot & "\" & "log.txt", True)
Set errFi = fs.CreateTextFile(strRoot & "\" & "errlog.txt", True)
Set fo_root = fs.GetFolder(strRoot)
If Not fs.FolderExists(dirImport) Then
MsgBox "請將欲轉入之xls 放在" & dirImport
Exit Function
End If
If Not fs.FolderExists(dirComplete) Then
fs.CreateFolder (dirComplete)
End If
Set fo_Dir = fs.GetFolder(dirImport)
For Each fi In fo_Dir.Files
ext = Mid(fi.Name, InStr(fi.Name, "."), 4)
If Left(fi.Name, 4) = "RSTA" And LCase(ext) = ".csv" Then
Debug.Print fi.Name
source = fi.path
Target = dirComplete & "\" & fi.Name
fs.CopyFile source, Target, True
Call RSTAimp1(source)
fs.DeleteFile source
End If
Next
outFi.Close
errFi.Close
Debug.Print "Done!RSTA*.csv Import" & vbCrLf & " 檔案已經搬移到" & dirComplete
End Function
--------------------------------------------------------------------------------
Function A11imp1(source)
' --- 匯入一個上櫃csv檔到主檔stk
Dim fs2 As New Scripting.FileSystemObject
Dim RsStk As Recordset
Dim RsStkId As Recordset
Dim inpFi As TextStream
Dim s1 As String
Dim yy As String, mm As String, dd As String
Dim sdate As String
Dim aa
Dim i As Integer
Dim s2 As String
Dim isBegin As Boolean
Dim isdelim As Boolean
Dim lines, ch
Set inpFi = fs2.OpenTextFile(source)
Set RsStk = CurrentDb.OpenRecordset("select * from stk")
isBegin = False
lines = 0
Do While Not inpFi.AtEndOfStream
s1 = inpFi.ReadLine
If Not isBegin And InStr(s1, "每日收盤行情") <> 0 Then
isBegin = True
yy = Mid(s1, 1, 2)
mm = Mid(s1, InStr(s1, "年") + 1, 2)
dd = Mid(s1, InStr(s1, "月") + 1, 2)
sdate = (1911 + yy) & "/" & mm & "/" & dd
Debug.Print sdate
inpFi.SkipLine ' 標題欄
ElseIf isBegin Then
'--- 解決字串中的,號,如"200,450,000"==> 200450000
If Mid(s1, 1, 1) > "0" Then
lines = lines + 1
'If lines > 5 Then
' Exit Do
'End If
'**************************************
isdeli = False
s2 = ""
For i = 1 To Len(s1)
ch = Mid(s1, i, 1)
If Mid(s1, i, 1) = """" Then
isdeli = Not isdeli
Else
If isdeli Then
If ch <> "," Then
s2 = s2 & ch
End If
Else
s2 = s2 & ch
End If
End If
Next
s2 = Replace(s2, "--", "00")
'Debug.Print s2
'*************************************
aa = Split(s2, ",")
If UBound(aa) < 8 Or Len(aa(0)) > 4 Then
'Debug.Print s2
Else
'證券代號0,證券名稱1,成交股數2,成交筆數3,成交金額4,開盤價5,最高價6,最低價7,收盤價8
RsStk.AddNew
RsStk("dte") = CDate(sdate)
RsStk("stockid") = aa(0)
RsStk("price") = "0" & aa(8)
RsStk("p_open") = aa(5)
RsStk("p_high") = aa(6)
RsStk("p_low") = aa(7)
s2 = Replace(aa(2), ",", "")
s2 = Replace(s2, """", "")
RsStk("vol") = s2
RsStk.Update
'--- 同時更新股票代號檔
Set RsStkId = CurrentDb.OpenRecordset("select * from stkid where stockid='" & aa(0) & "'")
If RsStkId.EOF Then
DoCmd.RunSQL ("insert into stkid values('" & aa(0) & "','" & aa(1) & "','1')")
End If
End If
End If
End If
Loop
RsStk.Close
Debug.Print source
End Function
--------------------------------------------------------------------------------
Function A11Import()
'--- 將dirImport內的所有 A11*.csv上市檔匯入到主檔 stk,同時將該檔移到 dircomplete
Dim fs As New Scripting.FileSystemObject
Dim outFi As TextStream, errFi As TextStream
Dim dirImport As String, dirComplete As String
Dim fi As File
Dim strRoot As String
Dim fo_root As Folder
Dim fo_Dir As Folder
Dim ext As String
Dim source As String, Target As String, stockId As String
strRoot = CurrentProject.path
dirImport = strRoot & "\import"
dirComplete = strRoot & "\complete"
Set outFi = fs.CreateTextFile(strRoot & "\" & "log.txt", True)
Set errFi = fs.CreateTextFile(strRoot & "\" & "errlog.txt", True)
Set fo_root = fs.GetFolder(strRoot)
If Not fs.FolderExists(dirImport) Then
MsgBox "請將欲轉入之xls 放在" & dirImport
Exit Function
End If
If Not fs.FolderExists(dirComplete) Then
fs.CreateFolder (dirComplete)
End If
Set fo_Dir = fs.GetFolder(dirImport)
For Each fi In fo_Dir.Files
ext = Mid(fi.Name, InStr(fi.Name, "."), 4)
If Left(fi.Name, 3) = "A11" And LCase(ext) = ".csv" Then
Debug.Print fi.Name
source = fi.path
Target = dirComplete & "\" & fi.Name
fs.CopyFile source, Target, True
Call A11imp1(source)
fs.DeleteFile source
End If
Next
outFi.Close
errFi.Close
Debug.Print "Done!A11*.csv Import" & vbCrLf & " 檔案已經搬移到" & dirComplete
End Function
End Function
view raw csvToAccess.vba hosted with ❤ by GitHub

2015年5月24日 星期日

三重濾網交易策略

inputs: TradeProfit(0.04),TradeStopLoss(0.01) ;
Inputs: OverBought(95),OverSold(5),BuyLength(35),SellLength(45);
vars: IsBalanceDay(False),MP(0),KB(0),KS(0);
if DayOfMonth(Date) &gt; 14 and DayOfMonth(Date) &lt; 22 and DayOfWeek(Date)= 3 then &nbsp;IsBalanceDay = True
else IsBalanceDay =False ;
MP = MarketPosition ;
{ ----- Preparation of Trade Setup -----}
{------- 1st Time Frame 60 min ------}
Condition1 = Macd(Close,12,26) of Data3 &gt; Macd(Close,12,26)[1] of Data3 ;
Condition2 = Macd(Close,12,26) of Data3 &lt; Macd(Close,12,26)[1] of Data3 ;
{------- 2nd Time Frame 12 mim ------}
Condition3 = FastK(9) of Data2 &lt; OverBought and SlowD(9)of Data2 &lt; OverBought ;
Condition4 = FastK(9) of Data2 &gt; OverSold and SlowD(9)of Data2 &gt; OverSold ;
{------- 3rd Time Frame 5 minutes ------}
Condition5 = Close of Data1 &gt; Average(Close of Data1,BuyLength) ;
Condition6 = Close of Data1 &lt; Average(Close of Data1,SellLength) ;
if Date &lt;&gt; Date[1] then Begin
KB = 0 ;
KS = 0 ;
end;
if (KB+KS)&lt; 1 then Begin
if Condition1 and Condition3 and Condition5 and KB &lt; 1 then Begin
Buy ("LB") at Market;
KB = KB +1 ;
end;
if Condition2 and Condition4 and Condition6 and KS &lt; 1 then Begin
Sell ("SS") at Market;
KS = KS +1 ;
end;
end;
if MP &gt; 0 then Begin
if MP &gt; 0 and High &gt; EntryPrice*(1 + TradeProfit) then ExitLong at EntryPrice*(1 + TradeProfit) stop;
if MP &gt; 0 and Low &lt; EntryPrice*(1 - TradeStopLoss) then ExitLong at EntryPrice *(1- TradeStopLoss) stop;
end;
{ ----- Exit of Short Trade -----}
if MP &lt; 0 then Begin
if MP &lt; 0 and Low &lt; EntryPrice*(1 - TradeProfit) then ExitShort at EntryPrice*(1 - TradeProfit) stop;
if MP &lt; 0 and High &gt; EntryPrice*(1 + TradeStopLoss) then ExitShort at EntryPrice*(1 + TradeStopLoss) stop;
end;
{ ----- Balance on DayClose -----}
if MP &lt;&gt; 0 and time &gt; 1335 then Begin
if MP &gt; 0 then exitlong at market;
if MP &lt; 0 then exitshort at market;
end;
{ ----- Balance on Monthly BalanceDay -----}
if IsBalanceDay then Begin
if MP &lt;&gt; 0 and time= 1315 then Begin
if MP &gt; 0 then ExitLong at market ;
if MP &lt; 0 then ExitShort at market ;
end ;
end;

2015年5月22日 星期五

TA-Lib Usage (STOCH)

# This algorithm uses talib's STOCH function to determine entry and exit points.
# When the stochastic oscillator dips below 10, the stock is determined to be oversold
# and a long position is opened. The position is exited when the indicator rises above 90
# because the stock is thought to be overbought.
# Because this algorithm uses the history function, it will only run in minute mode.
# We will constrain the trading to once per day at market open in this example.
import talib
import numpy as np
import pandas as pd
# Setup our variables
def initialize(context):
context.stocks = symbols('SPY', 'AAPL', 'GLD', 'AMZN')
# Set the percent of the account to be invested per stock
context.long_pct_per_stock = 1.0 / len(context.stocks)
# Create a variable to track the date change
context.date = None
def handle_data(context, data):
todays_date = get_datetime().date()
# Do nothing unless the date has changed
if todays_date == context.date:
return
# Set the new date
context.date = todays_date
# Load historical data for the stocks
high = history(30, '1d', 'high')
low = history(30, '1d', 'low')
close = history(30, '1d', 'close_price')
# Iterate over our list of stocks
for stock in context.stocks:
current_position = context.portfolio.positions[stock].amount
slowk, slowd = talib.STOCH(high[stock],
low[stock],
close[stock],
fastk_period=5,
slowk_period=3,
slowk_matype=0,
slowd_period=3,
slowd_matype=0)
# get the most recent value
slowk = slowk[-1]
slowd = slowd[-1]
# If either the slowk or slowd are less than 10, the stock is
# 'oversold,' a long position is opened if there are no shares
# in the portfolio.
if slowk < 10 or slowd < 10 and current_position <= 0:
order_target_percent(stock, context.long_pct_per_stock)
# If either the slowk or slowd are larger than 90, the stock is
# 'overbought' and the position is closed.
elif slowk > 90 or slowd > 90 and current_position >= 0:
order_target(stock, 0)
view raw STOCH_talib.py hosted with ❤ by GitHub

TA-Lib Usage (RSI)

# This example algorithm uses the Relative Strength Index indicator as a buy/sell signal.
# When the RSI is over 70, a stock can be seen as overbought and it's time to sell.
# When the RSI is below 30, a stock can be seen as oversold and it's time to buy.
# Because this algorithm uses the history function, it will only run in minute mode.
# We will constrain the trading to once per day at market open in this example.
import talib
# Setup our variables
def initialize(context):
context.stocks = symbols('MMM', 'SPY', 'GE')
context.max_cash_per_stock = 100000.0 / len(context.stocks)
context.LOW_RSI = 30
context.HIGH_RSI = 70
# Create a variable to track the date change
context.date = None
def handle_data(context, data):
todays_date = get_datetime().date()
# Do nothing unless the date has changed
if todays_date == context.date:
return
# Set the new date
context.date = todays_date
cash = context.portfolio.cash
# Load historical data for the stocks
prices = history(15, '1d', 'price')
# Use pandas dataframe.apply to get the last RSI value
# for for each stock in our basket
rsi = prices.apply(talib.RSI, timeperiod=14).iloc[-1]
# Loop through our list of stocks
for stock in context.stocks:
current_position = context.portfolio.positions[stock].amount
# RSI is above 70 and we own shares, time to sell
if rsi[stock] > context.HIGH_RSI and current_position > 0:
order_target(stock, 0)
log.info('{0}: RSI is at {1}, selling {2} shares'.format(
stock.symbol, rsi[stock], current_position
))
# RSI is below 30 and we don't have any shares, time to buy
elif rsi[stock] < context.LOW_RSI and current_position == 0:
# Use floor division to get a whole number of shares
target_shares = cash // data[stock].price
order_target(stock, target_shares)
log.info('{0}: RSI is at {1}, buying {2} shares.'.format(
stock.symbol, rsi[stock], target_shares
))
# record the current RSI values of each stock
record(ge_rsi=rsi[symbol('GE')],
spy_rsi=rsi[symbol('SPY')],
mmm_rsi=rsi[symbol('MMM')])
view raw RSI_talib.py hosted with ❤ by GitHub

TA-Lib Usage (MACD)

# This example algorithm uses the Moving Average Crossover Divergence (MACD) indicator as a buy/sell signal.
# When the MACD signal less than 0, the stock price is trending down and it's time to sell.
# When the MACD signal greater than 0, the stock price is trending up it's time to buy.
# Because this algorithm uses the history function, it will only run in minute mode.
# We will constrain the trading to once per day at market open in this example.
import talib
import numpy as np
import pandas as pd
# Setup our variables
def initialize(context):
context.stocks = symbols('MMM', 'SPY', 'GOOG_L', 'PG', 'DIA')
context.pct_per_stock = 1.0 / len(context.stocks)
# Create a variable to track the date change
context.date = None
def handle_data(context, data):
todays_date = get_datetime().date()
# Do nothing unless the date has changed and its a new day.
if todays_date == context.date:
return
# Set the new date
context.date = todays_date
# Load historical data for the stocks
prices = history(40, '1d', 'price')
# Create the MACD signal and pass in the three parameters: fast period, slow period, and the signal.
# This is a series that is indexed by sids.
macd = prices.apply(MACD, fastperiod=12, slowperiod=26, signalperiod=9)
# Iterate over the list of stocks
for stock in context.stocks:
current_position = context.portfolio.positions[stock].amount
# Close position for the stock when the MACD signal is negative and we own shares.
if macd[stock] < 0 and current_position > 0:
order_target(stock, 0)
# Enter the position for the stock when the MACD signal is positive and
# our portfolio shares are 0.
elif macd[stock] > 0 and current_position == 0:
order_target_percent(stock, context.pct_per_stock)
record(goog=macd[symbol('GOOG_L')],
spy=macd[symbol('SPY')],
mmm=macd[symbol('MMM')])
# Define the MACD function
def MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9):
'''
Function to return the difference between the most recent
MACD value and MACD signal. Positive values are long
position entry signals
optional args:
fastperiod = 12
slowperiod = 26
signalperiod = 9
Returns: macd - signal
'''
macd, signal, hist = talib.MACD(prices,
fastperiod=fastperiod,
slowperiod=slowperiod,
signalperiod=signalperiod)
return macd[-1] - signal[-1]
view raw MACD_talib.py hosted with ❤ by GitHub



TA-Lib Usage (Bollinger Bands)

# This algorithm uses the talib Bollinger Bands function to determine entry entry
# points for long and short positions.
# When the price breaks out of the upper Bollinger band, a short position
# is opened. A long position is opened when the price dips below the lower band.
# Because this algorithm uses the history function, it will only run in minute mode.
# We will constrain the trading to once per day at market open in this example.
import talib
import numpy as np
import pandas as pd
# Setup our variables
def initialize(context):
context.stock = symbol('SPY')
# Create a variable to track the date change
context.date = None
def handle_data(context, data):
todays_date = get_datetime().date()
# Do nothing unless the date has changed
if todays_date == context.date:
return
# Set the new date
context.date = todays_date
current_position = context.portfolio.positions[context.stock].amount
price=data[context.stock].price
# Load historical data for the stocks
prices = history(15, '1d', 'price')
upper, middle, lower = talib.BBANDS(
prices[context.stock],
timeperiod=10,
# number of non-biased standard deviations from the mean
nbdevup=2,
nbdevdn=2,
# Moving average type: simple moving average here
matype=0)
# If price is below the recent lower band and we have
# no long positions then invest the entire
# portfolio value into SPY
if price <= lower[-1] and current_position <= 0:
order_target_percent(context.stock, 1.0)
# If price is above the recent upper band and we have
# no short positions then invest the entire
# portfolio value to short SPY
elif price >= upper[-1] and current_position >= 0:
order_target_percent(context.stock, -1.0)
record(upper=upper[-1],
lower=lower[-1],
mean=middle[-1],
price=price,
position_size=current_position)



TA-Lib Usage (ATR)

# This strategy was taken from http://www.investopedia.com/articles/trading/08/atr.asp
# The idea is to use ATR to identify breakouts, if the price goes higher than
# the previous close + ATR, a price breakout has occurred. The position is closed when
# the price goes 1 ATR below the previous close.
# This algorithm uses ATR as a momentum strategy, but the same signal can be used for
# a reversion strategy, since ATR doesn't indicate the price direction.
# Because this algorithm uses the history function, it will only run in minute mode.
# entry and exit points for trading the SPY.
import talib
import numpy as np
import pandas as pd
# Setup our variables
def initialize(context):
context.stock = symbol('SPY')
# Create a variable to track the date change
context.date = None
# Algorithm will only take long positions.
# It will stop if encounters a short position.
set_long_only()
def handle_data(context, data):
# We will constrain the trading to once per day at market open in this example.
todays_date = get_datetime().date()
# Do nothing unless the date has changed and it's a new day.
if todays_date == context.date:
return
# Set the new date
context.date = todays_date
# Track our position
current_position = context.portfolio.positions[context.stock].amount
record(position_size=current_position)
# Load historical data for the stocks
high = history(30, '1d', 'high')
low = history(30, '1d', 'low')
close = history(30, '1d', 'close_price')
# Calculate the ATR for the stock
atr = talib.ATR(high[context.stock],
low[context.stock],
close[context.stock],
timeperiod=14)[-1]
price=data[context.stock].price
# Use the close price from 2 days ago because we trade at market open
prev_close = close.iloc[-3][context.stock]
# An upside breakout occurs when the price goes 1 ATR above the previous close
upside_signal = price - (prev_close + atr)
# A downside breakout occurs when the previous close is 1 ATR above the price
downside_signal = prev_close - (price + atr)
# Enter position when an upside breakout occurs. Invest our entire portfolio to go long.
if upside_signal > 0 and current_position <= 0:
order_target_percent(context.stock, 1.0)
# Exit position if a downside breakout occurs
elif downside_signal > 0 and current_position >= 0:
order_target_percent(context.stock, 0.0)
record(upside_signal=upside_signal,
downside_signal=downside_signal,
ATR=atr)
view raw ATR_talib.py hosted with ❤ by GitHub



Batch Transform

# This is the standard Quantopian function that initializes your data and 
# variables. In it, we define how large of a 'bet' we're making (in dollars) and what 
# stock we're working with.
def initialize(context):
    # we will be trading in AMZN and WMT shares
    context.stocks = symbols('AMZN', 'WMT')
    context.bet_amount = 100000
    context.long = 0

# This is the standard Quantopian event handling function. This function is 
# run once for each bar of data.  In this example, it the min and max 
# prices for the trailing window.  If the price exceeds the recent high, it 
# goes short; if the price dips below the recent low, it goes long. The algo
# is a contrarian/mean reversion bet.
def handle_data(context, data):
    # Until our batch transform's datapanel is full, it will return None.  Once
    # the datapanel is full, then we have a max and min to work with.
    rval = minmax(data)
    
    if rval is None:
        return
    
    maximums, minimums = rval
    
    for stock in context.stocks:
        cur_max = maximums[stock]
        cur_min = minimums[stock]
        cur_price = data[stock].price
        cur_position = context.portfolio.positions[stock]
           
        order_direction = calculate_direction(stock, cur_min, cur_max, cur_price, cur_position)
        order_amount = calculate_order_amount(context, stock, order_direction, cur_price)
        
        # Optional: uncomment the log line below if you're looking for more detail about what's 
        # going on.  It will log all the information that is a 'moving part' of this
        # algorithm. Note: if you're doing a full backtest it's a lot of log lines!
        logmsg = '\n{s}: max {m} min {i} price {p} position amount {l}\nordering {n} shares'
        log.info(logmsg.format(
            s=stock, 
            m=cur_max, 
            i=cur_min, 
            p=cur_price, 
            l=cur_position.amount,
            n=order_amount
        ))
        
        order(stock, order_amount)
        
# Here we do our test to see if we should buy or sell or do nothing.  This is
# the main part of the algorithm. Once we establish a position (long or short)
# we use the context.long variable to remember which we took.
def calculate_direction(stock, cur_min, cur_max, cur_price, cur_position):
    if cur_max is not None and cur_position.amount <= 0 and cur_price >= cur_max:
        return -1
    elif cur_min is not None and cur_position.amount >= 0 and cur_price <= cur_min:
        return 1
    
    return 0
   
# This method is purely for order management. It calculates and returns an 
# order amount to place binary bets.
# If signal_val is -1, get to a short position of -1 * context.bet_size
# If signal_val is 1, get to a long position of context.bet_size
def calculate_order_amount(context, stock, signal_val, cur_price):
    current_amount = context.portfolio.positions[stock].amount
    abs_order_amount = int(context.bet_amount / cur_price) 
    
    if signal_val == -1:
        return (-1 * abs_order_amount) - current_amount
    elif signal_val == 1:
        return abs_order_amount - current_amount
    else:
        return 0        
            
# This is our batch transform decorator/declaration. We set the 
# refresh_period and length of the window.  In this case, once per day we're loading 
# the last 10 trading days and evaluating them.
@batch_transform(refresh_period=1, window_length=10)
def minmax(datapanel):
    # We are looking for the min and the max price to return. Just because it's interesting
    # we also are logging the current price. 
    prices_df = datapanel['price']
    min_price = prices_df.min()
    max_price = prices_df.max()

    if min_price is not None and max_price is not None:
        return (max_price, min_price)
    else:
        return None

History

# Standard Deviation Using History
# Use history() to calculate the standard deviation of the days' closing
# prices of the last 10 trading days, including price at the time of 
# calculation.
def initialize(context):
    # this example works on Apple's data
    context.aapl = symbol('AAPL')

def handle_data(context, data):
    # use history to pull the last 10 days of price
    price_history = history(bar_count=10, frequency='1d', field='price')
    # calculate the standard deviation using std()
    std = price_history.std()
    # record the standard deviation as a custom signal
    record(std=std[context.aapl])

Portfolio Allocation

def initialize(context):
    context.stocks = symbols('CERN', 'DLTR') 

def handle_data(context, data):
    # This will order as many shares as needed to
    # achieve the desired portfolio allocation.
    # In our case, we end up with 20% allocation for
    # one stock and 80% allocation for the other stock.
    order_target_percent(context.stocks[0], .2)
    order_target_percent(context.stocks[1], .8)

    # Plot portfolio allocations
    pv = float(context.portfolio.portfolio_value)
    portfolio_allocations = []
    for stock in context.stocks:
        pos = context.portfolio.positions[stock]
        portfolio_allocations.append(
            pos.last_sale_price * pos.amount / pv * 100
        )

    record(perc_stock_0=portfolio_allocations[0],
           perc_stock_1=portfolio_allocations[1])

TA-Lib Usage (RSI)

# This example algorithm uses the Relative Strength Index indicator as a buy/sell signal.
# When the RSI is over 70, a stock can be seen as overbought and it's time to sell.
# When the RSI is below 30, a stock can be seen as oversold and it's time to buy.
# Because this algorithm uses the history function, it will only run in minute mode.
# We will constrain the trading to once per day at market open in this example.
import talib
import numpy as np
import math
# Setup our variables
def initialize(context):
context.max_notional = 100000
context.intc = symbol('INTC') # Intel
context.LOW_RSI = 30
context.HIGH_RSI = 70
def handle_data(context, data):
#Get a trailing window of data
prices = history(15, '1d', 'price')
# Use pandas dataframe.apply to get the last RSI value
# for for each stock in our basket
rsi_data = prices.apply(talib.RSI, timeperiod=14).iloc[-1]
intc_rsi = rsi_data[context.intc]
# check how many shares of Intel we currently own
current_intel_shares = context.portfolio.positions[context.intc].amount
# until 14 time periods have gone by, the rsi value will be numpy.nan
# RSI is above 70 and we own GOOG, time to close the position.
if intc_rsi > context.HIGH_RSI and current_intel_shares > 0:
order_target(context.intc, 0)
log.info('RSI is at ' + str(intc_rsi) + ', selling ' + str(current_intel_shares) + ' shares')
# RSI is below 30 and we don't have any Intel stock, time to buy.
elif intc_rsi < context.LOW_RSI and current_intel_shares == 0:
num_shares = math.floor(context.max_notional / data[context.intc].close_price)
order(context.intc, num_shares)
log.info('RSI is at ' + str(intc_rsi) + ', buying ' + str(num_shares) + ' shares')
# record the current RSI value and the current price of INTC.
record(intcRSI=intc_rsi, intcPRICE=data[context.intc].close_price)
view raw RSI2_talib.py hosted with ❤ by GitHub



Custom Slippage

# Our custom slippage model
class PerStockSpreadSlippage(slippage.SlippageModel):

    # We specify the constructor so that we can pass state to this class, but this is optional.
    def __init__(self, spreads):
        # Store a dictionary of spreads, keyed by sid.
        self.spreads = spreads

    def process_order(self, trade_bar, my_order):
        spread = self.spreads[my_order.sid]
   
        # In this model, the slippage is going to be half of the spread for 
        # the particular stock
        slip_amount = spread / 2
        # Compute the price impact of the transaction. Size of price impact is 
        # proprotional to order size. 
        # A buy will increase the price, a sell will decrease it. 
        new_price = trade_bar.price + (slip_amount * my_order.direction)

        log.info('executing order ' + str(trade_bar.sid) + ' stock bar price: ' + \
                 str(trade_bar.price) + ' and trade executes at: ' + str(new_price))

        # Create the transaction using the new price we've calculated.
        return slippage.create_transaction(
            trade_bar,
            my_order,
            new_price,
            my_order.amount
        )

def initialize(context):
    # Provide the bid-ask spread for each of the securities in the universe.
    spreads = {
        sid(24): 0.05,
        sid(3766): 0.08
    }
   
    # Initialize slippage settings given the parameters of our model
    set_slippage(PerStockSpreadSlippage(spreads))


def handle_data(context, data):
    # We want to own 100 shares of each stock in our universe
    for stock in data:
            order_target(stock, 100)
            log.info('placing market order for ' + str(stock.symbol) + ' at price ' \
                     + str(data[stock].price))

Fetcher

import pandas

def rename_col(df):
    df = df.rename(columns={'New York 15:00': 'price'})
    df = df.rename(columns={'Value': 'price'})
    df = df.fillna(method='ffill')
    df = df[['price', 'sid']]
    # Correct look-ahead bias in mapping data to times   
    df = df.tshift(1, freq='b')
    log.info(' \n %s ' % df.head())
    return df
    
def initialize(context):
    # import the external data
    fetch_csv('https://www.quandl.com/api/v1/datasets/JOHNMATT/PALL.csv?trim_start=2012-01-01',
        date_column='Date',
        symbol='palladium',
        pre_func = preview,
        post_func=rename_col,
        date_format='%Y-%m-%d')

    fetch_csv('https://www.quandl.com/api/v1/datasets/BUNDESBANK/BBK01_WT5511.csv?trim_start=2012-01-01',
        date_column='Date',
        symbol='gold',
        pre_func = preview,
        post_func=rename_col,
        date_format='%Y-%m-%d')
    
    # Tiffany
    context.stock = symbol('TIF')

def preview(df):
    log.info(' \n %s ' % df.head())
    return df    

def handle_data(context, data):
    # Invest 10% of the portfolio in Tiffany stock when the price of gold is low.
    # Decrease the Tiffany position to 5% of portfolio when the price of gold is high.

    if (data['gold'].price < 1600):
       order_target_percent(context.stock, 0.10)
    if (data['gold'].price > 1750):
       order_target_percent(context.stock, 0.05)

    #record the variables   
    if 'price' in data['palladium']:
       record(palladium=data['palladium'].price, gold=data['gold'].price)

Record Variables

# This initialize function sets any data or variables that you'll use in
# your algorithm.
def initialize(context):
context.stock = symbol('BA') # Boeing
# Now we get into the meat of the algorithm.
def handle_data(context, data):
# Create a variable for the price of the Boeing stock
context.price = data[context.stock].price
# Create variables to track the short and long moving averages.
# The short moving average tracks over 20 days and the long moving average
# tracks over 80 days.
short = data[context.stock].mavg(20)
long = data[context.stock].mavg(80)
# If the short moving average is higher than the long moving average, then
# we want our portfolio to hold 500 stocks of Boeing
if (short > long):
order_target(context.stock, +500)
# If the short moving average is lower than the long moving average, then
# then we want to sell all of our Boeing stocks and own 0 shares
# in the portfolio.
elif (short < long):
order_target_value(context.stock, 0)
# Record our variables to see the algo behavior. You can record up to
# 5 custom variables. To see only a certain variable, deselect the
# variable name in the custom graph in the backtest.
record(short_mavg = short,
long_mavg = long,
goog_price = context.price)
view raw initialize.py hosted with ❤ by GitHub



Set Universe

# This is the standard Quantopian function that initializes your data and
# variables. In it, we define how large of a 'bet' we're making (in dollars) and what
# stock we're working with.
def initialize(context):
# we want to try this on a range of highly liquid stocks
set_universe(universe.DollarVolumeUniverse(98, 99))
context.bet_amount = 1000
context.count = 20
# This is the standard Quantopian event handling function. This function is
# run once for each bar of data. In this example, it the min and max
# prices for the trailing window. If the price exceeds the recent high, it
# goes short; if the price dips below the recent low, it goes long. The algo
# is a contrarian/mean reversion bet.
def handle_data(context, data):
# Until our batch transform's datapanel is full, it will return None. Once
# the datapanel is full, then we have a max and min to work with.
prices = history(bar_count=10, frequency='1d', field='price')
ranking = sort_returns(prices)
if ranking is not None:
column_name = ranking.columns[0]
# bottom quantile to go long
bottom = ranking[-1*context.count:]
longs = bottom[bottom[column_name] < 0]
# top quantile to go short
top = ranking[:context.count]
shorts = top[top[column_name] > 0]
for stock in data.keys():
if stock in longs.index:
amount = calculate_order_amount(context, stock, 1, data[stock].price)
elif stock in shorts.index:
amount = calculate_order_amount(context, stock, -1, data[stock].price)
else:
amount = calculate_order_amount(context, stock, 0, data[stock].price)
order(stock, amount)
# This method is purely for order managment. It calculates and returns an
# order amount to place binary bets.
# If signal_val is -1, get to a short position of -1 * context.bet_size
# If signal_val is 1, get to a long position of context.bet_size
def calculate_order_amount(context, stock, signal_val, cur_price):
current_amount = context.portfolio.positions[stock].amount
abs_order_amount = int(context.bet_amount / cur_price)
if signal_val == -1:
return (-1 * abs_order_amount) - current_amount
elif signal_val == 1:
return abs_order_amount - current_amount
elif signal_val == 0:
return -1 * current_amount
else:
return 0
def sort_returns(prices):
shifted_prices = prices.shift(9)
returns = (prices - shifted_prices) / shifted_prices
# use a slice operator to get the most recent returns
last_returns = returns[-1:]
last_date = last_returns.index[-1]
sorted_returns = last_returns.T.sort(columns=last_date, ascending=0)
return sorted_returns
view raw SetUniverse.py hosted with ❤ by GitHub



Basic Algorithm

# For this example, we're going to write a simple momentum script.
# When the stock goes up quickly, we're going to buy;
# when it goes down we're going to sell.
# Hopefully we'll ride the waves.
# To run an algorithm in Quantopian, you need two functions:
# initialize and handle_data.
def initialize(context):
# The initialize function sets any data or variables that
# you'll use in your algorithm.
# For instance, you'll want to define the security
# (or securities) you want to backtest.
# You'll also want to define any parameters or values
# you're going to use later.
# It's only called once at the beginning of your algorithm.
# In our example, we're looking at Apple.
# If you re-type this line you'll see
# the auto-complete that is available for security.
context.security = symbol('AAPL')
# The handle_data function is where the real work is done.
# This function is run either every minute
# (in live trading and minute backtesting mode)
# or every day (in daily backtesting mode).
def handle_data(context, data):
# We've built a handful of useful data transforms for you to use,
# such as moving average.
# To make market decisions, we're calculating the stock's
# moving average for the last 5 days and its current price.
average_price = data[context.security].mavg(5)
current_price = data[context.security].price
# Another powerful built-in feature of the Quantopian backtester is the
# portfolio object. The portfolio object tracks your positions, cash,
# cost basis of specific holdings, and more. In this line, we calculate
# the current amount of cash in our portfolio.
cash = context.portfolio.cash
# Here is the meat of our algorithm.
# If the current price is 1% above the 5-day average price
# AND we have enough cash, then we will order.
# If the current price is below the average price,
# then we want to close our position to 0 shares.
if current_price > 1.01*average_price and cash > current_price:
# Need to calculate how many shares we can buy
number_of_shares = int(cash/current_price)
# Place the buy order (positive means buy, negative means sell)
order(context.security, +number_of_shares)
log.info("Buying %s" % (context.security.symbol))
elif current_price < average_price:
# Sell all of our shares by setting the target position to zero
order_target(context.security, 0)
log.info("Selling %s" % (context.security.symbol))
# You can use the record() method to track any custom signal.
# The record graph tracks up to five different variables.
# Here we record the Apple stock price.
record(stock_price=data[context.security].price)



Multiple Security Example

# This example runs the same momentum play as the first sample
# (https://www.quantopian.com/help#sample-basic), but this time it uses more
# securities during the backtest.
# Important note: All securities in an algorithm must be traded for the
# entire length of the backtest. For instance, if you try to backtest both
# Google and Facebook against 2011 data you will get an error; Facebook
# wasn't traded until 2012.
# First step is importing any needed libraries.
import datetime
import pytz
def initialize(context):
# Here we initialize each stock.
# By calling symbols('AAPL', 'IBM', 'CSCO') we're storing the Security objects.
context.stocks = symbols('AAPL', 'IBM', 'CSCO')
context.vwap = {}
context.price = {}
# Setting our maximum position size, like previous example
context.max_notional = 1000000.1
context.min_notional = -1000000.0
# Initializing the time variables we use for logging
# Convert timezone to US EST to avoid confusion
est = pytz.timezone('EST')
context.d=datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=est)
def handle_data(context, data):
# Initializing the position as zero at the start of each frame
notional=0
# This runs through each stock. It computes
# our position at the start of each frame.
for stock in context.stocks:
price = data[stock].price
notional = notional + context.portfolio.positions[stock].amount * price
tradeday = data[stock].datetime
# This runs through each stock again. It finds the price and calculates
# the volume-weighted average price. If the price is moving quickly, and
# we have not exceeded our position limits, it executes the order and
# updates our position.
for stock in context.stocks:
vwap = data[stock].vwap(3)
price = data[stock].price
if price < vwap * 0.995 and notional > context.min_notional:
order(stock,-100)
notional = notional - price*100
elif price > vwap * 1.005 and notional < context.max_notional:
order(stock,+100)
notional = notional + price*100
# If this is the first trade of the day, it logs the notional.
if (context.d + datetime.timedelta(days=1)) < tradeday:
log.debug(str(notional) + ' - notional start ' + tradeday.strftime('%m/%d/%y'))
context.d = tradeday



基本面選股分析 Fundamental Data Algorithm

"""
Trading Strategy using Fundamental Data
1. Filter the top 50 companies by market cap
2. Find the top two sectors that have the highest average PE ratio
3. Every month exit all the positions before entering new ones at the month
4. Log the positions that we need
"""
import pandas as pd
import numpy as np
def initialize(context):
# Dictionary of stocks and their respective weights
context.stock_weights = {}
# Count of days before rebalancing
context.days = 0
# Number of sectors to go long in
context.sect_numb = 2
# Sector mappings
context.sector_mappings = {
101.0: "Basic Materials",
102.0: "Consumer Cyclical",
103.0: "Financial Services",
104.0: "Real Estate",
205.0: "Consumer Defensive",
206.0: "Healthcare",
207.0: "Utilites",
308.0: "Communication Services",
309.0: "Energy",
310.0: "Industrials",
311.0: "Technology"
}
# Rebalance monthly on the first day of the month at market open
schedule_function(rebalance,
date_rule=date_rules.month_start(),
time_rule=time_rules.market_open())
def rebalance(context, data):
# Exit all positions before starting new ones
for stock in context.portfolio.positions:
if stock not in context.fundamental_df and stock in data:
order_target_percent(stock, 0)
log.info("The two sectors we are ordering today are %r" % context.sectors)
# Create weights for each stock
weight = create_weights(context, context.stocks)
# Rebalance all stocks to target weights
for stock in context.fundamental_df:
if stock in data:
if weight != 0:
log.info("Ordering %0.0f%% percent of %s in %s"
% (weight * 100,
stock.symbol,
context.sector_mappings[context.fundamental_df[stock]['morningstar_sector_code']]))
order_target_percent(stock, weight)
def before_trading_start(context):
"""
Called before the start of each trading day.
It updates our universe with the
securities and values found from get_fundamentals.
"""
num_stocks = 50
# Setup SQLAlchemy query to screen stocks based on PE ratio
# and industry sector. Then filter results based on
# market cap and shares outstanding.
# We limit the number of results to num_stocks and return the data
# in descending order.
fundamental_df = get_fundamentals(
query(
# put your query in here by typing "fundamentals."
fundamentals.valuation_ratios.pe_ratio,
fundamentals.asset_classification.morningstar_sector_code
)
.filter(fundamentals.valuation.market_cap != None)
.filter(fundamentals.valuation.shares_outstanding != None)
.order_by(fundamentals.valuation.market_cap.desc())
.limit(num_stocks)
)
# Find sectors with the highest average PE
sector_pe_dict = {}
for stock in fundamental_df:
sector = fundamental_df[stock]['morningstar_sector_code']
pe = fundamental_df[stock]['pe_ratio']
# If it exists add our pe to the existing list.
# Otherwise don't add it.
if sector in sector_pe_dict:
sector_pe_dict[sector].append(pe)
else:
sector_pe_dict[sector] = []
# Find average PE per sector
sector_pe_dict = dict([(sectors, np.average(sector_pe_dict[sectors]))
for sectors in sector_pe_dict if len(sector_pe_dict[sectors]) > 0])
# Sort in ascending order
sectors = sorted(sector_pe_dict, key=lambda x: sector_pe_dict[x], reverse=True)[:context.sect_numb]
# Filter out only stocks with that particular sector
context.stocks = [stock for stock in fundamental_df
if fundamental_df[stock]['morningstar_sector_code'] in sectors]
# Initialize a context.sectors variable
context.sectors = [context.sector_mappings[sect] for sect in sectors]
# Update context.fundamental_df with the securities (and pe_ratio) that we need
context.fundamental_df = fundamental_df[context.stocks]
update_universe(context.fundamental_df.columns.values)
def create_weights(context, stocks):
"""
Takes in a list of securities and weights them all equally
"""
if len(stocks) == 0:
return 0
else:
weight = 1.0/len(stocks)
return weight
def handle_data(context, data):
"""
Code logic to run during the trading day.
handle_data() gets called every bar.
"""
# track how many positions we're holding
record(num_positions = len(context.portfolio.positions))



Sample Algorithm for a Basic Strategy

# For this example, we're going to write a simple momentum script.
# When the stock goes up quickly, we're going to buy;
# when it goes down we're going to sell.
# Hopefully we'll ride the waves.
# To run an algorithm in Quantopian, you need two functions:
# initialize and handle_data.
def initialize(context):
# The initialize function sets any data or variables that
# you'll use in your algorithm.
# For instance, you'll want to define the security
# (or securities) you want to backtest.
# You'll also want to define any parameters or values
# you're going to use later.
# It's only called once at the beginning of your algorithm.
# In our example, we're looking at Apple.
# If you re-type this line you'll see
# the auto-complete that is available for security.
context.security = symbol('AAPL')
# The handle_data function is where the real work is done.
# This function is run either every minute
# (in live trading and minute backtesting mode)
# or every day (in daily backtesting mode).
def handle_data(context, data):
# We've built a handful of useful data transforms for you to use,
# such as moving average.
# To make market decisions, we're calculating the stock's
# moving average for the last 5 days and its current price.
average_price = data[context.security].mavg(5)
current_price = data[context.security].price
# Another powerful built-in feature of the Quantopian backtester is the
# portfolio object. The portfolio object tracks your positions, cash,
# cost basis of specific holdings, and more. In this line, we calculate
# the current amount of cash in our portfolio.
cash = context.portfolio.cash
# Here is the meat of our algorithm.
# If the current price is 1% above the 5-day average price
# AND we have enough cash, then we will order.
# If the current price is below the average price,
# then we want to close our position to 0 shares.
if current_price > 1.01*average_price and cash > current_price:
# Need to calculate how many shares we can buy
number_of_shares = int(cash/current_price)
# Place the buy order (positive means buy, negative means sell)
order(context.security, +number_of_shares)
log.info("Buying %s" % (context.security.symbol))
elif current_price < average_price:
# Sell all of our shares by setting the target position to zero
order_target(context.security, 0)
log.info("Selling %s" % (context.security.symbol))
# You can use the record() method to track any custom signal.
# The record graph tracks up to five different variables.
# Here we record the Apple stock price.
record(stock_price=data[context.security].price)
view raw BasicTrader.py hosted with ❤ by GitHub

Sample Algorithm for Live Trading 2

'''
This algorithm defines a long-only equal weight portfolio and rebalances it at a user-specified frequency
NOTE: This algo is intended to run in minute-mode simulation and is compatible with LIVE TRADING.
'''
# Import the libraries we will use here
import datetime
import pytz
import pandas as pd
def initialize(context):
# This initialize function sets any data or variables
# that you'll use in your algorithm.
# You'll also want to define any parameters or values
# you're going to use.
# In our example, we're looking at 9 sector ETFs.
context.secs = symbols('XLY', # XLY Consumer Discrectionary SPDR Fund
'XLF', # XLF Financial SPDR Fund
'XLK', # XLK Technology SPDR Fund
'XLE', # XLE Energy SPDR Fund
'XLV', # XLV Health Care SPRD Fund
'XLI', # XLI Industrial SPDR Fund
'XLP', # XLP Consumer Staples SPDR Fund
'XLB', # XLB Materials SPDR Fund
'XLU') # XLU Utilities SPRD Fund
# Change this variable if you want to rebalance less frequently
context.Rebalance_Days = 1
# These other variables are used in the algorithm for leverage, trade time, etc.
context.rebalance_date = None
context.weights = 0.99/len(context.secs)
context.rebalance_hour_start = 10
context.rebalance_hour_end = 15
# These are the default commission and slippage settings. Change them to fit your
# brokerage fees. These settings only matter for backtesting. When you trade this
# algorithm, they are moot - the brokerage and real market takes over.
set_commission(commission.PerTrade(cost=0.03))
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))
def handle_data(context, data):
# Get the current exchange time, in the exchange timezone
exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')
# If it's a rebalance day (defined in intialize()) then rebalance:
if context.rebalance_date == None or exchange_time > context.rebalance_date + datetime.timedelta(days=context.Rebalance_Days):
# Do nothing if there are open orders:
if has_orders(context):
print('has open orders - doing nothing!')
return
rebalance(context, data, exchange_time)
def rebalance(context, data, exchange_time):
# Only rebalance if we are in the user specified rebalance time-of-day window
if exchange_time.hour < context.rebalance_hour_start or exchange_time.hour > context.rebalance_hour_end:
return
# Do the rebalance. Loop through each of the stocks and order to the target
# percentage. If already at the target, this command doesn't do anything.
# A future improvement could be to set rebalance thresholds.
for sec in context.secs:
order_target_percent(sec, context.weights, limit_price=None, stop_price=None)
context.rebalance_date = exchange_time
log.info("Rebalanced to target portfolio weights at %s" % str(exchange_time))
def has_orders(context):
# Return true if there are pending orders.
has_orders = False
for sec in context.secs:
orders = get_open_orders(sec)
if orders:
for oo in orders:
message = 'Open order for {amount} shares in {stock}'
message = message.format(amount=oo.amount, stock=sec)
log.info(message)
has_orders = True
return has_orders

Sample Algorithm for Live Trading

'''
This algorithm defines a long-only equal weight portfolio and rebalances it at a user-specified frequency
NOTE: This algo is intended to run in minute-mode simulation and is compatible with LIVE TRADING.
'''
# Import the libraries we will use here
import datetime
import pytz
import pandas as pd
def initialize(context):
# This initialize function sets any data or variables
# that you'll use in your algorithm.
# You'll also want to define any parameters or values
# you're going to use.
# In our example, we're looking at 9 sector ETFs.
context.secs = symbols('XLY', # XLY Consumer Discrectionary SPDR Fund
'XLF', # XLF Financial SPDR Fund
'XLK', # XLK Technology SPDR Fund
'XLE', # XLE Energy SPDR Fund
'XLV', # XLV Health Care SPRD Fund
'XLI', # XLI Industrial SPDR Fund
'XLP', # XLP Consumer Staples SPDR Fund
'XLB', # XLB Materials SPDR Fund
'XLU') # XLU Utilities SPRD Fund
# Change this variable if you want to rebalance less frequently
context.Rebalance_Days = 1
# These other variables are used in the algorithm for leverage, trade time, etc.
context.rebalance_date = None
context.weights = 0.99/len(context.secs)
context.rebalance_hour_start = 10
context.rebalance_hour_end = 15
# These are the default commission and slippage settings. Change them to fit your
# brokerage fees. These settings only matter for backtesting. When you trade this
# algorithm, they are moot - the brokerage and real market takes over.
set_commission(commission.PerTrade(cost=0.03))
set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))
def handle_data(context, data):
# Get the current exchange time, in the exchange timezone
exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')
# If it's a rebalance day (defined in intialize()) then rebalance:
if context.rebalance_date == None or exchange_time > context.rebalance_date + datetime.timedelta(days=context.Rebalance_Days):
# Do nothing if there are open orders:
if has_orders(context):
print('has open orders - doing nothing!')
return
rebalance(context, data, exchange_time)
def rebalance(context, data, exchange_time):
# Only rebalance if we are in the user specified rebalance time-of-day window
if exchange_time.hour < context.rebalance_hour_start or exchange_time.hour > context.rebalance_hour_end:
return
# Do the rebalance. Loop through each of the stocks and order to the target
# percentage. If already at the target, this command doesn't do anything.
# A future improvement could be to set rebalance thresholds.
for sec in context.secs:
order_target_percent(sec, context.weights, limit_price=None, stop_price=None)
context.rebalance_date = exchange_time
log.info("Rebalanced to target portfolio weights at %s" % str(exchange_time))
def has_orders(context):
# Return true if there are pending orders.
has_orders = False
for sec in context.secs:
orders = get_open_orders(sec)
if orders:
for oo in orders:
message = 'Open order for {amount} shares in {stock}'
message = message.format(amount=oo.amount, stock=sec)
log.info(message)
has_orders = True
return has_orders

2015年5月17日 星期日

抓取網頁資料值應用

Public Class TSE
'取得國內上市證券編碼與名稱
Private ListUrl1 As String = "http://203.74.228.63/t40/C_public.jsp?strMode=2"
'取得國內證券編碼與名稱
Public Function GetStkNoListAll() As ArrayList
'存放移除html標籤後且要抓取的範圍
Dim idAr As New ArrayList
'取得上市股票證券編碼之網頁原始碼
Dim page As String = GetWebPage(ListUrl1, "")
'證券編碼與名稱對照表的陣列
Dim tempAr As ArrayList = RemoveHtmlTag(page, vbCrLf)
'取得上市股票證券編碼
Dim startIndex As Integer = tempAr.IndexOf("上市股票及權利證書") + 1
Dim endIndex As Integer = tempAr.IndexOf("上市認購(售)權證")
'取得編號及名稱
For i As Integer = startIndex To endIndex - 1
Dim s() As String = Split(tempAr(i), " ")
idAr.Add(s(0).Trim & " " & s(1).Trim)
Next
Return idAr
End Function
'取得網頁HTML
Private Shared Function GetWebPage(ByVal URL As String, Optional ByVal proxy As String = "") As String
Dim proxyObject As System.Net.WebProxy
Dim proxyString As String
'啟用錯誤處理常式,並指定常式在程序中的位置
On Error GoTo err
'準備讀取資料,Create Function會傳回 WebRequest 類別的子代
Dim MyRequest As System.Net.HttpWebRequest = System.Net.WebRequest.Create(URL)
'讀取registry看看是否需要設定 proxy
proxyString = proxy
If proxyString <> "" Then
'設定proxy
proxyObject = New System.Net.WebProxy(proxyString, True)
MyRequest.Proxy = proxyObject
End If
'讀取遠端網頁 GetResponse 方法會傳回包含來自網際網路資源之回應的 WebResponse 物件
Dim MyWebResponse As System.Net.WebResponse = MyRequest.GetResponse()
Dim MyStream As IO.Stream
MyStream = MyWebResponse.GetResponseStream
'StreamReader 是為特定編碼方式的字元輸入而設計,而 Stream 類別則是為位元組輸入和輸出而設計。使用 StreamReader 來從標準文字檔讀取資訊行。
'使用預設的編碼方式 --> System.Text.Encoding.Default 為 ANSI 編碼方式
Dim StreamReader As New IO.StreamReader(MyStream, System.Text.Encoding.Default)
'資料流從目前位置到末端的其餘字串。如果目前位置位於資料流末端,則傳回空字串 ("")。
GetWebPage = StreamReader.ReadToEnd()
err:
If Err.Number <> 0 Then GetWebPage = Nothing
MyRequest = Nothing
MyWebResponse = Nothing
MyStream = Nothing
StreamReader = Nothing
proxyObject = Nothing
End Function
'去除html的標記
Private Function RemoveHtmlTag(ByVal html As String, ByVal del As String) As ArrayList
'記得要Add Reference → Microsoft.mshtml
Dim doc As mshtml.IHTMLDocument2 = New mshtml.HTMLDocumentClass
'嘗試寫入網頁資料
Try
'避開語法問題
html = Replace(html, "<SCRIPT", "<!-- <SCRIPT")
html = Replace(html, "</SCRIPT>", "</SCRIPT> -->")
html = Replace(html, "<script>", "<!-- <script>")
html = Replace(html, "</script>", "</script> -->")
html = Replace(html, "<script ", "<!-- <script ")
doc.write(html)
'innerText,去除html標記以後的文字 之後根據換行做分割
Dim item() As String = Split(Doc.body.innerText, del)
'將文字內容用ArrayList存放
Dim ar As New ArrayList
For i As Integer = 0 To item.Length - 1
ar.Add(item(i).Trim)
Next
Return ar
Catch ex As Exception
MsgBox("選擇的股票無交易訊息!", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly)
Return Nothing
End Try
End Function
End Class
'而在.aspx檔做測試的部份:
'先在頁面上加入一個listbox以及一個button
button_Click事件:
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim arrSource As ArrayList = TSE.GetStkNoList '讀取資料
ListBox1.DataSource = arrSource '顯示資料
ListBox1.DataBind()
End Sub
view raw Webdata.vba hosted with ❤ by GitHub

2015年5月16日 星期六

海龜程式

vars: N(0),StopLoss(1),DV(0),BB(0),AccountBalance(0),DollarRisk(0),LTT(0),
Tracker(0),LastTrade(0),HBP(0),LBP(0); input: InitialBalance(10000000); 
{/// Turtle 20-Day Breakout Replica //////////////////////////////////////}
if marketposition = 0 then begin
BB = 0;
N = AvgTrueRange(20); DV = N*BigPointValue;
AccountBalance = InitialBalance;
DV = N * BigPointValue;
{AccountBalance = InitialBalance + netprofit;}
DollarRisk = AccountBalance * .01;
LTT = IntPortion(DollarRisk/DV);
StopLoss = 2 * DV * LTT;
if LastTrade = -1 then begin
buy LTT shares next bar highest(h,20) or higher;
buy LTT shares next bar highest(h,20) + (0.5*N) or higher;
buy LTT shares next bar highest(h,20) + (1.0*N) or higher;
buy LTT shares next bar highest(h,20) + (1.5*N) or higher;
Sell LTT shares next bar lowest(l,20) or lower;
Sell LTT shares next bar lowest(l,20) - (0.5*N) or lower;
Sell LTT shares next bar lowest(l,20) - (1.0*N) or lower;
Sell LTT shares next bar lowest(l,20) - (1.5*N) or lower;
end;
if LastTrade = 1 then begin
buy LTT shares next bar highest(h,55) or higher;
buy LTT shares next bar highest(h,55) + (0.5*N) or higher;
buy LTT shares next bar highest(h,55) + (1.0*N) or higher;
buy LTT shares next bar highest(h,55) + (1.5*N) or higher;
Sell LTT shares next bar lowest(l,55) or lower;
Sell LTT shares next bar lowest(l,55) - (0.5*N) or lower;
Sell LTT shares next bar lowest(l,55) - (1.0*N) or lower;
Sell LTT shares next bar lowest(l,55) - (1.5*N) or lower;
end;
end;
{// PREVIOUS TRADE TRACKER}
if HBP = 0 and h > highest(h,19)[1] then begin
Tracker = 1; HBP = h; LBP = 0;
end;
if LBP = 0 and l < lowest(l,19)[1] then begin
Tracker = -1; LBP = l; HBP = 0;
end;
if Tracker = 1 then begin
if l < HBP - (2*N) then LastTrade = -1;
if h > HBP + (4*N) then LastTrade = 1;
end;
if Tracker = -1 then begin
if h > LBP + (2*N) then LastTrade = -1;
if l < LBP - (4*N) then LastTrade = 1;
end;
{// LONG 20 }
if LastTrade = -1 and marketposition = 1 then begin
BB = BB + 1;
if currentcontracts = LTT then begin
buy LTT shares next bar highest(h,20)[BB] + (0.5*N) or higher;
buy LTT shares next bar highest(h,20)[BB] + (1.0*N) or higher;
buy LTT shares next bar highest(h,20)[BB]+ (1.5*N) or higher;
end;
if currentcontracts = LTT * 2 then begin
buy LTT shares next bar highest(h,20)[BB] + (1.0*N) or higher;
buy LTT shares next bar highest(h,20)[BB] + (1.5*N) or higher;
end;
if currentcontracts = LTT * 3 then
buy LTT shares next bar highest(h,20)[BB] + (1.5*N) or higher;
end;
{// LONG 55}
if LastTrade = 1 and marketposition = 1 then begin
BB = BB + 1;
if currentcontracts = LTT then begin
buy LTT shares next bar highest(h,55)[BB] + (0.5*N) or higher;
buy LTT shares next bar highest(h,55)[BB] + (1.0*N) or higher;
buy LTT shares next bar highest(h,55)[BB]+ (1.5*N) or higher;
end;
if currentcontracts = LTT * 2 then begin
buy LTT shares next bar highest(h,55)[BB] + (1.0*N) or higher;
buy LTT shares next bar highest(h,55)[BB] + (1.5*N) or higher;
end;
if currentcontracts = LTT * 3 then
buy LTT shares next bar highest(h,55)[BB] + (1.5*N) or higher;
end;
ExitLong ("out-S") next bar lowest(l,10) or lower;
{// SHORT 20 }
if LastTrade = -1 and marketposition = -1 then begin
BB = BB + 1;
if currentcontracts = LTT then begin
Sell LTT shares next bar lowest(l,20)[BB] - (0.5*N) or lower;
Sell LTT shares next bar lowest(l,20)[BB] - (1.0*N) or lower;
Sell LTT shares next bar lowest(l,20)[BB] - (1.5*N) or lower;
end;
if currentcontracts = LTT * 2 then begin
Sell LTT shares next bar lowest(l,20)[BB] - (1.0*N) or lower;
Sell LTT shares next bar lowest(l,20)[BB] - (1.5*N) or lower;
end;
if currentcontracts = LTT * 3 then 
Sell LTT shares next bar lowest(l,20)[BB] - (1.5*N) or lower; 
end;
{// SHORT 55 }
if LastTrade = 1 and marketposition = -1 then begin
BB = BB + 1;
if currentcontracts = LTT then begin
Sell LTT shares next bar lowest(l,55)[BB] - (0.5*N) or lower;
Sell LTT shares next bar lowest(l,55)[BB] - (1.0*N) or lower;
Sell LTT shares next bar lowest(l,55)[BB] - (1.5*N) or lower;
end;
if currentcontracts = LTT * 2 then begin
Sell LTT shares next bar lowest(l,55)[BB] - (1.0*N) or lower;
Sell LTT shares next bar lowest(l,55)[BB] - (1.5*N) or lower;
end;
if currentcontracts = LTT * 3 then 
Sell LTT shares next bar lowest(l,55)[BB] - (1.5*N) or lower; 
end;
ExitShort ("out-B") next bar highest(h,10) or higher;
{// STOPS}
if currentcontracts = (2 * LTT) then StopLoss = DV * 3.5 * LTT;
if currentcontracts = (3 * LTT) then StopLoss = DV * 4.5 * LTT;
if currentcontracts = (4 * LTT) then StopLoss = DV * 5.0 * LTT;
setstoploss (StopLoss);
{// COMMENTARY}
commentary ("LTT: ",LTT,Newline);
commentary ("currentcontracts: ",currentcontracts,Newline);
commentary ("StopLoss: ",StopLoss,Newline);
commentary ("AccountBalance:",AccountBalance,NewLine);
commentary ("LastTrade: ",LastTrade,NewLine);

Heap Sort

def sort(number):
    tmp = [0] * (len(number) + 1)
    for i in range(1, len(tmp)):
    tmp[i] = number[i - 1]
    doHeap(tmp)
    m = len(number)
    while m > 1:
    tmp[1], tmp[m] = tmp[m], tmp[1]
    m -= 1
    p = 1
    s = 2 * p
    while s <= m:
        if s < m and tmp[s + 1] < tmp[s]: 
            s += 1
        if tmp[p] <= tmp[s]:
            break
        tmp[p], tmp[s] = tmp[s], tmp[p]
        p = s
        s = 2 * p 
        for i in range(len(number)):
            number[i] = tmp[i + 1]

def doHeap(tmp):
    heap = [-1] * len(tmp) 
    for i in range(1, len(heap)): 
        heap[i] = tmp[i] 
        s = i
        p = i // 2 
    while s >= 2 and heap[p] > heap[s]:
        heap[p], heap[s] = heap[s], heap[p]
        s = p
        p = s // 2
    for i in range(1, len(tmp)):
        tmp[i] = heap[i]