Python primer for Trading

UberMachine

Well-Known Member
#11
Now for some analysis

Let's calculate the daily returns on close_price

Python:
df['Close'].pct_change(1)
You could calculate the percent change for any number of days on any colums by changing the arguments to the pct_change function.
So you need to calculate the 5 day returns on Adj Close then
Python:
df['Adj Close'].pct_change(5)
But you need to get back in the original dataframe. So

Code:
df['DailyReturn'] = df['Close'].pct_change(1)
df
You would get the following output
Screenshot from 2018-08-07 18-02-29.png


Instead of percentage values, you need the difference value, then
Python:
 df['Close'].diff(1)
 

UberMachine

Well-Known Member
#12
Moving averages calculation

Let's calculate the 7 day moving average
Python:
df['MA'] = df['Close'].rolling(7).mean()
Screenshot from 2018-08-07 18-20-14.png


You can also calculate standard deviation, median and others on any column for any period
To calculate the median, use
Python:
df['Close'].rolling(5).median()
Try calculating 10 day moving standard deviation on close
Python:
df['Close'].rolling(10).std()

And also, 5 day maximum for close prices
Python:
df['Close'].rolling(5).max()
 

UberMachine

Well-Known Member
#13
So some plotting

Python:
# Required to display plots
import seaborn as sns
sns.set()
or
Python:
%pylab inline
The first one gives you nicer graphs

Plotting a single column
Python:
df['Close'].plot()
Screenshot from 2018-08-07 18-31-17.png


Plotting multiple columns
Python:
cols = ['MA7', 'Close']
df[cols].plot()
Screenshot from 2018-08-07 18-31-54.png

You can generate box plot and histograms quite easily

Python:
df['Close'].plot('box')
df['Close'].plot('hist')
 
Last edited:

UberMachine

Well-Known Member
#15
And finally, after doing the hard work.
You need to export it for future use


Python:
output_filename = 'my_output.csv'
df.to_csv(output_filename)
This will generate a file myoutput.csv in the same folder from which you ran the notebook

But you need the output in Excel, then
Python:
output_excel= 'my_output.xlsx'
df.to_excel(output_excel)
That's it to keep you get started in Python
 

MSN1979

Well-Known Member
#16
Done all that Successfully saved file
 
Last edited:

MSN1979

Well-Known Member
#18
all complete I think
 
Last edited:

MSN1979

Well-Known Member
#19
ignore this message
 
Last edited: