Python primer for Trading

TradeOptions

Well-Known Member
#41
Sir that is waste of time and energy. If you know where the documents are. Simply take backup of them. Or get a 16 year old teenager to get it done for u.
brother, I already followed travi bhai instructions. I value his words a lot, he is a true master. :up:
So far windows 10 is working well. No Issues. Thanks to all for giving me the courage to make this move.

Best Regards
 

UberMachine

Well-Known Member
#43
Hi UberMachine

Thanks for sharing, followed the steps and was able to install the software. I was wondering if you could help me how to read the JSON data from URL (example - https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo) and store that in MYSQL -DB.

Thanks in Advance.
That's a bit advanced. But would give you a few pointers
Python:
# This code is customized for the details given by you
# Change appropriately

import requests
import pandas as pd
# Replace the url below with your url
url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo'
req = requests.get(url)
content = req.json()
df = pd.DataFrame(content['Time Series (Daily)']).T
df.to_sql(tablename, connection) # tablename name of the table, connection - sqlAlchemy connection string
So, you use the requests library to pull data, convert into pandas dataframe and load data into SQL
 

UberMachine

Well-Known Member
#44
Continuing with the primer, a few data structures, infact just two; list and dictionaries.

A list is just a sequence of elements
Python:
list_one = [1,2,3,4,5]
To access an element,
list_one[0] returns the first element.
List indices start with 0 in Python. So the first element is 0.

A few more examples
Python:
list_one[0]  # First element
list_one[1]  # Second element
list_one[-1] # The last element
list_one[-2] # Second from last element
You can also select multiple numbers. Say you want to select elements 2 to 4.
Then,
Python:
list_one[1:4]
returns
[2,3,4]

You can nest lists within each other
Python:
nested_list = [[1,2,3],[10,20,30],[100,200,300]]
nested_list[0][0] # returns 1
nested_list[1][2] # returns 30
You can try out a lot of variations with lists.
 
Last edited:

UberMachine

Well-Known Member
#45
Dictionaries are key value pairs, something you see with json.
Keys must be unique, values can be anything

Python:
dct = {'a': 10, 'b': 20, 'c': 25}
dct['a'] # returns 10
Infact, the columns in dataframe we saw earlier in the reading files example is some sort of a dictionary (not exactly in Pythonic sense but you can think on those lines)

Python:
dct.keys() # returns dict_keys(['a', 'b', 'c'])
dct.values() # returns dict_values([10, 20, 25])

# To convert them into list, use
list(dct.keys())
 

UberMachine

Well-Known Member
#47
Mixing up lists and dictionaries
You can mix up lists and dictionaries as you like

List of dictionaries

Python:
list_of_dicts = [
    {'symbol': 'GAIL', 'price': 375},
    {'symbol': 'TECHM', 'price': 663},
    {'symbol': 'SUNPHARMA', 'price': 564.8},
    
]
list_of_dicts[0]['symbol'] # returns GAIL
list_of_dicts[1]['price'] # returns 663

Dictionary of lists

The above could be also be represented as
Python:
dict_of_lists = {
    'symbol': ['GAIL', 'TECHM', 'SUNPHARMA'],
    'price': [375, 663, 564.8]
}
dict_of_lists['symbol']  # returns ['GAIL', 'TECHM', 'SUNPHARMA']
dict_of_lists['price'][1]  # returns 663
You can combine them as you wish but beware things could easily get complex. So don't get drawn too much with this simplicity.
Nesting too many levels of list or dictionary would make things extremely confusing. So utmost keep them to a level of three to be comfortable.
Though it may look not useful now, this could be really important as we move on. So take time to understand them
 

UberMachine

Well-Known Member
#48
Now, let's try some calculations and comparison

Python:
import pandas as pd
filename = 'SBIN.csv'
df = pd.read_csv(filename, parse_dates=['Date'])
df['MA3'] = df['Close'].pct_change(3)
df['MA7'] = df['Close'].pct_change(7)
df.query('MA3>MA7')
Should get the following output
Screenshot from 2018-08-13 22-29-38.png


For the above to work
  1. All your column names should start with an alphabet
  2. Column names should not have spaces
If your columns has spaces, then use the following
Python:
import pandas as pd
filename = 'SBIN.csv'
df = pd.read_csv(filename, parse_dates=['Date'])
df['MA3'] = df['Close'].pct_change(3)
df['MA7'] = df['Close'].pct_change(7)
df[df['MA3'] > df['MA7']]
Only the last line is changed in the above code. But it works everywhere
 

UberMachine

Well-Known Member
#49
A few more code examples to try.

Python:
import pandas as pd
filename = 'cm13AUG2018bhav.csv.zip' # Replace with your filename
df = pd.read_csv(filename, parse_dates=['TIMESTAMP'])  # Replace Date with the date column in your file[/SIZE][/SIZE][/SIZE][/SIZE]

[SIZE=5][SIZE=5][SIZE=5]# Calculate one-day returns
df['RET'] = (df['CLOSE']/df['PREVCLOSE'])-1[/SIZE][/SIZE][/SIZE]

[SIZE=5][SIZE=5]# Get all stocks with open equals high price
df.query('OPEN == HIGH')[/SIZE][/SIZE]

[SIZE=5][SIZE=5][SIZE=5]# Get all stocks with open equals low price
df.query('OPEN == LOW')[/SIZE][/SIZE][/SIZE]

[SIZE=5][SIZE=5][SIZE=5]# Get all stocks with returns greater than 15 percent
df.query('RET > 0.15')[/SIZE][/SIZE][/SIZE]

[SIZE=5][SIZE=5][SIZE=5]# Get all stocks with close price greater than 10000
df.query('CLOSE > 10000')[/SIZE][/SIZE][/SIZE]

[SIZE=5][SIZE=5][SIZE=5]
And finally a compound query to try
Get all stocks with more than 10 percent returns and close price greater than 100
Python:
df.query('(RET > 0.1) & (CLOSE > 100)')
And as a bonus, you can make your condition as a string. Leave this if this is confusing
Python:
cond = '(RET > 0.1) & (CLOSE > 100)'
df.query(cond)

Warning
Don't use the inside your python code. (Not sure about how it came, may be font resizing)
If you find any errors, see the new post
 

Attachments

Last edited: