In [1]:
import pandas as pd
import numpy as np
from ipywidgets import Button, HBox, VBox,Layout
from IPython.display import Image, display, clear_output
import ipywidgets as widgets
import ctcsound
import time
from  datetime import datetime as py_dtime
from bqplot import *



print("Press Shift+Enter to initiate app. Click and Drag to select an area and choose the options below:")


try:
    pt
except NameError:
    var_exists = False
else:
    pt.stop()
    pt.join()
    time.sleep(2)
    
cs = ctcsound.Csound()
from bqplot import DateScale, LinearScale, Axis, Lines, Scatter, Bars, Hist, Figure
from bqplot.interacts import (
    FastIntervalSelector, IndexSelector, BrushIntervalSelector,
    BrushSelector, MultiSelector, LassoSelector, PanZoom, HandDraw
)
from traitlets import link

from ipywidgets import ToggleButtons, VBox, HTML

symbol = 'Stock Price of XYZ Incorporated'
symbol2 = 'Stock Price of Company 2'

thread = 0
price_data = pd.DataFrame(np.cumsum(np.random.randn(150, 2).dot([[0.5, 0.4], [0.4, 1.0]]), axis=0) + 100,
                          columns=['Stock Price of XYZ Incorporated', 'Stock Price of Company 2'],
                          index=pd.date_range(start='01-01-2007', periods=150))

dates_actual = price_data.index.values
prices = price_data[symbol].values



dt_x_index = DateScale(min=np.datetime64(py_dtime(2007, 1, 1)))
lin_y2 = LinearScale()

lc2_index = Lines(x=dates_actual, y=prices,
            scales={'x': dt_x_index, 'y': lin_y2})

x_ax1 = Axis(label='Date', scale=dt_x_index)
x_ay2 = Axis(label=(symbol + ' US $'), scale=lin_y2, orientation='vertical')

dt_x_brush = DateScale(min=np.datetime64(py_dtime(2007, 1, 1)))
lin_y2_brush = LinearScale()

lc3_brush = Lines(x=dates_actual, y=prices,
            scales={'x': dt_x_brush, 'y': lin_y2_brush})

x_ax_brush = Axis(label='Date', scale=dt_x_brush)
x_ay_brush = Axis(label=(symbol + ' US $'), scale=lin_y2_brush, orientation='vertical')

intsel_dateintsel_  = FastIntervalSelector(scale=dt_x_index, marks=[lc2_index])

db_brush = HTML(value='[]')
brushsel_date = BrushIntervalSelector(scale=dt_x_brush, marks=[lc3_brush], color='FireBrick')




def date_brush_change_callback(change):
    db_brush.value = str(change.new)
    
lc3_brush.observe(date_brush_change_callback, names=['selected'])

fig_brush_sel = Figure(marks=[lc3_brush], axes=[x_ax_brush, x_ay_brush],
                       title='Drag to Select Area of Interest in Time Series', interaction=brushsel_date)

words = ['Sonify']
items_layout = Layout( width='60%')

button = widgets.Button(description="Sonify Single Points",button_style='danger')
button2 = widgets.Button(description="Sonify All Points",button_style='danger')
button3 = widgets.Button(description="Collective Points",button_style='danger') 

box= HBox([button,button2])
container = widgets.VBox([box,fig_brush_sel])





csd_string = '''
<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-odac    ;;;realtime audio out
;-iadc    ;;;uncomment -iadc if real audio input is needed too
; For Non-realtime ouput leave only the line below:
; -o pluck.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

instr 1

kcps = p4
icps = p5
ifn  = 0
imeth = p6

asig pluck 0.6, kcps, icps, ifn, imeth, .1, 10
     outs asig, asig

endin
</CsInstruments>

<CsScore>
f 0 14400


</CsScore>

</CsoundSynthesizer>
'''

cs.compileCsdText(csd_string)
cs.start()

pt = ctcsound.CsoundPerformanceThread(cs.csound())
pt.play()


    

   
    



'''def on_button_clicked(b):
    pt.scoreEvent(False, 'i', (1, 0, 0.1, 500, 220, 1))'''
        

def on_button_clicked(b):
    in_min  = 80
    in_max = 110
    out_min= 100
    out_max = 900
    min_val = 0
    max_val = 0
    
    global prices
    global db_brush
    
    db_list = list()
    values = list()
    db_list = db_brush.value.strip("[").strip("]").split(",")
    for item in db_list:
        values.append(prices[int(item)])
        
    in_min = min(values)
    in_max = max(values)
    
    for item in values:
        freq = (item - in_min) * (out_max - out_min) / (in_max - in_min) + out_min  
    #print(freq)  

        pt.scoreEvent(False, 'i', (1, 0, 0.1, freq, 220, 1))
        time.sleep(0.1)

        
def on_button2_clicked(b):
    in_min  = 80
    in_max = 110
    out_min= 50
    out_max = 200
    min_val = 0
    max_val = 0
    
    global prices
    global db_brush
    
    db_list = list()
    values = list()
    db_list = db_brush.value.strip("[").strip("]").split(",")
    for item in db_list:
        values.append(prices[int(item)])
        
    in_min = min(values)
    in_max = max(values)
    
    for item in values:
        freq = (item - in_min) * (out_max - out_min) / (in_max - in_min) + out_min  
    #print(freq)  

        pt.scoreEvent(False, 'i', (1, 0, 10, freq, 220, 1))
        time.sleep(0)
        
        
display(container)      
button.on_click(on_button_clicked)
button2.on_click(on_button2_clicked)


Press Shift+Enter to initiate app. Click and Drag to select an area and choose the options below:

In [ ]: