zwQuant学習ノート(2)pyalgotrade空テスト

2767 ワード

# -*- coding: utf-8 -*-
#  python2.7
#  
#   
#  
import numpy as np
import pandas as pd
import matplotlib as mpl

from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns
from pyalgotrade.stratanalyzer import sharpe
from pyalgotrade.stratanalyzer import drawdown
from pyalgotrade.utils import stats


n_lever = 500        # 
n_risk  = 0.02       # 
total_mount = 10000 # 

class MyStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed):
        strategy.BacktestingStrategy.__init__(self, feed, 1000) #Pat 

        # We wan't to use adjusted close prices instead of close.
        self.setUseAdjustedValues(False)
        
        # Place the orders to get them processed on the first bar.
        # 
        orders = {
            "EURUSD": 500,

        }
        for instrument, quantity in orders.items():
            self.marketOrder(instrument, quantity*(-1), onClose=True, allOrNone=True)
            
    def onBars(self, bars):
        pass
# csv
def ret2csv(ftg):
    xd=retAnalyzer.getReturns()
    print 'type of xd is: ',type(xd)
    x8=[];
    for x1 in xd:
        x8=x8+[x1];
    xs1=pd.Series(x8);
    print(xs1.tail())
    xs1.to_csv(ftg)  
    print(fss)
    
    return xs1
    



    
# Load the yahoo feed from CSV files.
feed = yahoofeed.Feed()

# CSV 
feed.addBarsFromCSV("EURUSD", "dat\\EURUSD.csv")


# Evaluate the strategy with the feed's bars.
myStrategy = MyStrategy(feed)

# Attach returns and sharpe ratio analyzers.
retAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(retAnalyzer)
sharpeRatioAnalyzer = sharpe.SharpeRatio()
myStrategy.attachAnalyzer(sharpeRatioAnalyzer)
drawDownAnalyzer = drawdown.DrawDown()
myStrategy.attachAnalyzer(drawDownAnalyzer)


# Run the strategy
myStrategy.run()


# Print the results.
print("")
print( "  Final portfolio value: $%.2f" % myStrategy.getResult())
print( "  Anual return: %.2f %%" % (retAnalyzer.getCumulativeReturns()[-1] * 100))
print( "  Average daily return: %.2f %%" % (stats.mean(retAnalyzer.getReturns()) * 100))
print( "  Std. dev. daily return: %.4f" % (stats.stddev(retAnalyzer.getReturns())))
print( "  Sharpe ratio: %.2f" % (sharpeRatioAnalyzer.getSharpeRatio(0)))
print("  Max. drawdown: %.2f %%" % (drawDownAnalyzer.getMaxDrawDown() * 100))
print("  Longest drawdown duration: %s" % (drawDownAnalyzer.getLongestDrawDownDuration()))

print('')
fss='tmp\dret010.csv'
xs1=ret2csv(fss);

mpl.style.use('seaborn-whitegrid');
xs1.plot()

空にするのはmarketOrderのquantity*(-1)でいいです.他に方法があるかもしれません.でも、私もこれを使うと記憶しやすいと思います.もし私が他の方法を見つけたら、私はまた修正します.