Julia: An attempt to visualize the back-test based on CTA strategy _ Visualization

Source: Internet
Author: User
Tags sprintf

Related library: WINSTON,TK.

Features: Pure Julia to build, rare, hehe.

Basic functions of back-Test visualization:

It is easy to see the date of day trading in each transaction point, the day of each profit and loss situation. Do not go to the market to find and control, that too hard. With this analysis tool, we can greatly improve the efficiency of the analysis of the flow of the back-test transaction.

It can be used in front of the pan or back. You can customize the date and the label.

This analysis tool is mainly based on day-trading, if it is based on cross-date transactions, the framework is similar, only need to make a small number of changes can be.

Description

When Julia is at 0.2, this dongdong has been put into use. But for a while in the Julia to 0.4 stage, Wiston Library also does not follow the upgrade, resulting in no use. This time see Winston followed Julia rose to 0.5, very happy. Leave it to the remembrance.

Winston drawing function is limited, in fact, with Pyplot and other libraries to replace the Winston is also possible, I have tried.

The code is as follows:

Using Tk using Winston;

Using Strategydata;
W = tk.toplevel ("Policy multiplexer Helper _ Days Policy", 400,300) F = tk.frame (W); Tk.pack (f, Expand=true, fill= "both") ei = tk.entry (f) #输入标的 e = Tk.entry (f) # Enter the starting Time RB = Tk.radio (f, ["back to disk "", "forward Back"]) # Forward or backward recovery disk B = Tk.button (f, "policy reset Please press =>ok") txt = Tk.text (f, width=50,height=40) # If you have more transactions on the day, you can set up ' height=4 0 ", width=10,height=10 sc = Tk.scrollbar (f,txt," vertical ") Map (U-> Pack (u,side=" left ", anchor=" W "), (Ei,e, Rb,b,txt /SC)) # # Pack in left and right, ' left ': ' Top ', ' n ', ' W ' # layout: Question tk.formlayout (EI, "select object:") Tk.formlayout (E, "Tradedat E: ") Tk.formlayout (RB," select ") tk.formlayout (b, nothing) tk.formlayout (TXT," tradeflows ") #pack (TXT, expand=true, fill= "Both") Tk.formlayout (sc,nothing) Tk.grid (SC, 5:20,200,sticky= "News") # Set the position of the scroll bar #grid (Slider (f, 1:10), 1, 2:3, sticky=
"News" Tk.focus (e) # # put keyboard focus on widget Currenttrade = ' "; NextDay = dates.date (2000,1,1) function callback (PATH) instrument = Uppercase(Get_value (EI)) # PData:D ict{date,array{kbardata,1}} ();
    !isdefined (: totaldictdictdictdata_nmin) && error ("Totaldictdictdictdata_nmin is not exist!") If Haskey (totaldictdictdictdata_nmin,instrument) PData = Strategydata.getmaincontractcontinousdata (totalDictDict dictdata_nmin,instrument) Else msg =string ("The data does not contain this object:", instrument, ".) ") Tk.messagebox (f, msg) End tradedates = sort (Collect (keys (pData))) P = Winston.framedplot (Heig
    HT=200,WIDTH=400);
    val = Get_value (e) datestr= split (Val, "-");
    Yyear = Parse (int64,datestr[1]);
    Mmonth = Parse (int64,datestr[2]);
    DDay = Parse (int64,datestr[3]) ddate = Dates.date (Yyear,mmonth,dday);
    #currentTrade =string ("Re-disk Strategy:", Strategyname, "date of Recovery:", String (ddate), "\ n");
    Currenttrade =string ("Recovery date:", String (ddate), "\ n");
    TOTALPL = 0.0;
    NextDay = ddate; If Get_value (RB) = = "Back Disk" if!haskey (pdata,ddate) for I =1:length (tradedates) if Tradedates[i]>ddate ddate =tradedates[i];
                Break End End msg = "This date is not a trading day." Automatically moves the next recent trading day. "Tk.messagebox (F, msg) end for I =1:length (tradedates) if tradedates[i] > DDA
                Te NextDay =tradedates[i];
            Break End ' if nextday==ddate msg = ' has been to the last trading day. "Tk.messagebox (F, msg) END else if!haskey (pdata,ddate) for I =length (traded
                    Ates): -1:1 if Tradedates[i]<ddate ddate =tradedates[i];
                Break End End msg = "This date is not a trading day." Automatically moves to the last trading day. "Tk.messagebox (F, msg) end for I =length (tradedates): -1:1 if Tradedates[i]<d
                Date NextDay =tradedates[i];
            Break End END if nextday==ddate msg = "has been to the first trading day."
    "Tk.messagebox (F, msg) end #println (Currenttrade);
    #println (String (nextday)); # Find the next trading day Tradedata = pdata[ddate] contract = tradedata[1].
    Code;
    #setattr (p,draw_nothing=true);
    # Trading Today Water Series = 0;
    Currentflow=tradeflow[];
    Currsortflows =tradeflow[]; # Transaction Detail section: Sequential output transaction for I =1:length (tradeflows) if Dates.date (tradeflows[i].opendate) ==ddate p ush!
        (Currentflow,tradeflows[i]) end-if!isempty (Currentflow) curopentime=datetime[]; For Currentflow if!in (flow.opendate,curopentime) # guaranteed not to repeat push! (curopentime,flow.opendate) End sort!
                (curopentime) #排序 # Put the transactions of the day in the order of the open time for DT-curopentime for flows in Currentflow If Flow.opendate==dt push!
 (Currsortflows,flow)               Currsortflows series =series+1; Otime =dates.hour (flow.opendate) *100+dates.minute (flow.opendate) if otime>=1000 opentime
            =string (Otime);
            else opentime =string ("0", String (otime)) End Openprice =string (Flow.openprice); If Length (openprice) >7 openprice =openprice[1:7] End CTime =dates.ho ur (flow.closedate) *100+dates.minute (flow.closedate) if ctime>=1000 closetime =string (cTime)
            ; 
            else closetime =string ("0", String (cTime)) End Closeprice =string (Flow.closeprice); If Length (closeprice) >7 Closeprice =closeprice[1:7] End If flow.tr
                Adetype >0 PL =flow.closeprice-flow.openprice;
      Direction = "L"      else PL =-flow.closeprice+flow.openprice;
            Direction = "S" End TOTALPL =TOTALPL+PL;  STRPL = @sprintf ("%0.1f", PL) str0 = "---------------------------------------" str1 =string ("\ n", "section ", String (series)," Sub-transaction => ", Flow.strategyname," \ n ") str2 =string (" Opening direction: ", direction," this
            Pen profit and Loss: ", STRPL," \ n ") Str3 =string (" Open Time: ", Opentime," open warehouse Price: ", Openprice," \ n ") STR4 =string ("Close the Time:", Closetime, "flat Price:", Closeprice, "\ n") tempstring =string (str0,str1,s
            TR2,STR3,STR4);
        Currenttrade =string (currenttrade,tempstring);
    End-End STRTOTALPL = @sprintf ("%0.1f", TOTALPL) # Total Profit and loss Currcount =length (currentflow);
    # Paint Winston.setattr (p,title=string date: ", Val," "," the subject of the duplicate: ", contract," Recovery strategy: ", Strategyname));   Winston.setattr (p,title=string Date: ", Val," ","Duplicate the subject matter: ", contract," the day opened the warehouse times: ", Currcount," cumulative Profit and Loss: ", STRTOTALPL)); #x =[Hour (tradedata[i). DateTime) *100+minute (Tradedata[i]. DateTime) for I =1:length (Tradedata)];
    # horizontal axis, time y =float64[]; For I=1:length (Tradedata) push! (Y,tradedata[i].
    Close) end x =int64[]; For I=1:length (Tradedata) push!
    (X,i);
            End Winston.add (P,curve (x,y)) # Transaction summary if!isempty (Currentflow) for I=1:length (Currentflow)
            Optime = Dates.hour (currentflow[i].opendate) *100+dates.minute (currentflow[i].opendate);
            Cltime = Dates.hour (currentflow[i].closedate) *100+dates.minute (currentflow[i].closedate);
            LS = Currentflow[i].tradetype; For J=1:length (tradedata) mkTime = Dates.hour (tradedata[j). DateTime) *100+dates.minute (Tradedata[j].
                DateTime); If mktime==optime Buyp = winston.points (j,tradedata[j). close*0.995,kind= "Filled circle", color= "Red") # If Ls>0 #Winston. SetAttr (Buyp, ticklabels=["Openbuy"]) #else #Winston. SetAttr (Buyp, ticklabels=["Opensell"]) # End Winston.add
                (P,BUYP); ElseIf mkTime ==cltime SellP = winston.points (j,tradedata[j).
                    close*1.005,kind= "Filled circle", color= "green"); Winston.add (P,SELLP) end end totalStr1 =string ("\ n", "--------------------- ------------------", \ n") totalStr2 =string ("Total number of transactions of the day:", Currcount, "total Profit and Loss:", STRTOTALPL, "\ n") Tota Lstr =string (TOTALSTR1,TOTALSTR2) Currenttrade =string (currenttrade,totalstr) Else totalStr1 =string ( "---------------------------------------", "\ n") Currenttrade =string (CURRENTTRADE,TOTALSTR1, "There is no deal in today's strategy."
    ") End # Updates the information for the corresponding control Tk.set_value (e,string (nextday));
    Tk.set_value (Txt,currenttrade); # Dot, enter point, exit Point, a straight line complement. Winston.display (P) #hold (true) end Tk.bind (b, "command", callback) Tk.bind (b, "<Return>", callback) Tk.bind (TXT, "<Return>", callback) Tk.bind (E, "<Return>", callback) tk.bind (EI, "<Return>", callback) Tk.bind (SC,
 "<Return>", callback)

Effect Chart:

Improved 1

About arrows:

I've written it again with the Pyplot library, and there's been a big improvement:

About callback function rewrite, no way, power is insufficient, lazy ...

Now the function is too long, it is best to split into a combination of several small functions. The main blame is that I'm a bit lazy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.